Skip to content

cointoss.sources.yahoofinance

yahoofinance

YfPeriod = Literal['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y', '10y', 'ytd', 'max'] module-attribute

SECTORS = ('basic-materials', 'communication-services', 'consumer-cyclical', 'consumer-defensive', 'energy', 'financial-services', 'healthcare', 'industrials', 'real-estate', 'technology', 'utilities') module-attribute

NoSuchTicker

Bases: LookupError

Yahoo has no history for ticker.

Source code in src/cointoss/sources/yahoofinance.py
class NoSuchTicker(LookupError):
    """Yahoo has no history for `ticker`."""

    ticker: str

    def __init__(self, ticker: str) -> None:
        super().__init__("no such ticker")
        self.ticker = ticker

ticker = ticker instance-attribute

__init__(ticker)

Source code in src/cointoss/sources/yahoofinance.py
def __init__(self, ticker: str) -> None:
    super().__init__("no such ticker")
    self.ticker = ticker

IndustryList

Bases: StrEnum

Which of an industry's two published lists named a company.

Source code in src/cointoss/sources/yahoofinance.py
class IndustryList(StrEnum):
    """Which of an industry's two published lists named a company."""

    TOP = "top"
    GROWTH = "growth"

TOP = 'top' class-attribute instance-attribute

GROWTH = 'growth' class-attribute instance-attribute

IndustryListing

Bases: BaseModel

One company named by one of an industry's lists, under Yahoo's sector and industry keys.

Source code in src/cointoss/sources/yahoofinance.py
class IndustryListing(BaseModel):
    """One company named by one of an industry's lists, under Yahoo's sector and industry keys."""

    model_config: ClassVar[ConfigDict] = ConfigDict(frozen=True)

    ticker: str
    sector: str
    industry: str
    named_by: IndustryList

model_config = ConfigDict(frozen=True) class-attribute

ticker instance-attribute

sector instance-attribute

industry instance-attribute

named_by instance-attribute

Industry

Bases: BaseModel

One of Yahoo's industries, under the key of the sector it belongs to.

Source code in src/cointoss/sources/yahoofinance.py
class Industry(BaseModel):
    """One of Yahoo's industries, under the key of the sector it belongs to."""

    model_config: ClassVar[ConfigDict] = ConfigDict(frozen=True)

    sector: str
    industry: str

model_config = ConfigDict(frozen=True) class-attribute

sector instance-attribute

industry instance-attribute

get_info(ticker)

Source code in src/cointoss/sources/yahoofinance.py
@require_cache
@nsnode(tags=["api"])
def get_info(ticker: str) -> dict[str, Any]:
    return cast(dict[str, Any], yf.Ticker(ticker).info)

get_prices(ticker, period='max')

Source code in src/cointoss/sources/yahoofinance.py
@require_cache
@nsnode(tags=["api"])
def get_prices(ticker: str, period: YfPeriod = "max") -> FrameData:
    df = yf.Ticker(ticker).history(period=period, interval="1d", auto_adjust=False, timeout=10)  # pyright: ignore[reportUnknownMemberType]
    # yfinance answers a ticker it does not know with an empty frame, not an error.
    if df.empty:
        raise NoSuchTicker(ticker)
    dd: list[str] = list(map(str, df.index.date))  # pyright: ignore[reportAttributeAccessIssue,reportUnknownArgumentType]
    df.insert(loc=0, column="date", value=dd)  # pyright: ignore
    return FrameData.pd.from_frame(df)

get_prices_batch(tickers, *, period=None, start=None)

Each ticker's daily history from one yf.download, from start or over period.

Each frame is shaped as get_prices shapes one: a date column, then Yahoo's columns, auto_adjust=False with the action columns, and only the sessions the ticker has a close for, since the batch's index is the union of every ticker's sessions. A ticker with no close at all is NoSuchTicker: yfinance logs a failed download and leaves its columns empty, so an unknown ticker and a failed fetch look alike. Not cached: a daily window must be fetched fresh. Fetches the tickers one after another, so a caller pacing batches paces the requests.

Source code in src/cointoss/sources/yahoofinance.py
def get_prices_batch(
    tickers: list[str], *, period: YfPeriod | None = None, start: date | None = None
) -> dict[str, FrameData | NoSuchTicker]:
    """Each ticker's daily history from one `yf.download`, from `start` or over `period`.

    Each frame is shaped as `get_prices` shapes one: a `date` column, then Yahoo's columns,
    `auto_adjust=False` with the action columns, and only the sessions the ticker has a close
    for, since the batch's index is the union of every ticker's sessions. A ticker with no
    close at all is `NoSuchTicker`: yfinance logs a failed download and leaves its columns
    empty, so an unknown ticker and a failed fetch look alike. Not cached: a daily window must
    be fetched fresh. Fetches the tickers one after another, so a caller pacing batches paces
    the requests.
    """
    if (period is None) == (start is None):
        raise ValueError("ask for a period or start, and not both")
    when: dict[str, Any] = {"period": period} if start is None else {"start": start.isoformat()}
    download = cast(Any, yf.download)
    df = cast(
        pd.DataFrame | None,
        download(
            tickers,
            interval="1d",
            auto_adjust=False,
            actions=True,
            group_by="ticker",
            multi_level_index=True,
            progress=False,
            threads=False,
            timeout=10,
            **when,
        ),
    )
    held = set[str]() if df is None else {str(t) for t in cast(Any, df.columns).get_level_values(0)}
    frames: dict[str, FrameData | NoSuchTicker] = {}
    for ticker in tickers:
        if df is None or ticker not in held:
            frames[ticker] = NoSuchTicker(ticker)
            continue
        one = cast(pd.DataFrame, df[ticker])
        one = cast(pd.DataFrame, one[one["Close"].notna()]).copy()
        if one.empty:
            frames[ticker] = NoSuchTicker(ticker)
            continue
        one.columns.name = None
        dates = [str(d) for d in cast(Any, one.index).date]
        one.insert(loc=0, column="date", value=dates)  # pyright: ignore[reportUnknownMemberType]
        frames[ticker] = FrameData.pd.from_frame(one)
    return frames

search_pairs(symbol)

Yahoo's USD tickers for the coin symbol, in search order.

Yahoo lists many coins under {SYMBOL}{n}-USD, a numeric suffix telling apart coins that share a symbol, so the candidates are the crypto quotes for {symbol} USD of that shape.

Source code in src/cointoss/sources/yahoofinance.py
def search_pairs(symbol: str) -> list[str]:
    """Yahoo's USD tickers for the coin `symbol`, in search order.

    Yahoo lists many coins under `{SYMBOL}{n}-USD`, a numeric suffix telling apart coins that
    share a symbol, so the candidates are the crypto quotes for `{symbol} USD` of that shape.
    """
    pattern = re.compile(rf"{re.escape(symbol)}\d*-USD", re.IGNORECASE)
    quotes = cast(list[dict[str, Any]], yf.Search(f"{symbol} USD", max_results=20).quotes)
    return [
        str(q["symbol"])
        for q in quotes
        if q.get("quoteType") == "CRYPTOCURRENCY" and pattern.fullmatch(str(q.get("symbol", "")))
    ]

lookup(query)

Source code in src/cointoss/sources/yahoofinance.py
@require_cache
@nsnode(tags=["api"])
def lookup(query: str) -> FrameData:
    df = yf.Lookup(query).all
    df.insert(loc=0, column="ticker", value=df.index)  # pyright: ignore[reportUnknownMemberType]
    return FrameData.pd.from_frame(df)

sector_industries(sector)

The keys of the industries Yahoo lists under sector, in Yahoo's order.

Source code in src/cointoss/sources/yahoofinance.py
@require_cache
@nsnode(tags=["api"])
def sector_industries(sector: str) -> list[str]:
    """The keys of the industries Yahoo lists under `sector`, in Yahoo's order."""
    industries = cast(list[dict[str, Any]], _finance("sectors", sector).get("industries") or [])
    # Yahoo leads the list with an "All Industries" row that has no key.
    return [str(i["key"]) for i in industries if i.get("key")]

industry_companies(industry)

The companies industry's top (up to 50) and fastest-growing (5) lists name.

A company on both lists is named once by each.

Source code in src/cointoss/sources/yahoofinance.py
@require_cache
@nsnode(tags=["api"])
def industry_companies(industry: str) -> list[IndustryListing]:
    """The companies `industry`'s top (up to 50) and fastest-growing (5) lists name.

    A company on both lists is named once by each.
    """
    data = _finance("industries", industry)
    sector = data.get("sectorKey")
    if not sector:
        raise LookupError(f"Yahoo names no sector for industry {industry}")
    named: list[IndustryListing] = []
    for which, field in (
        (IndustryList.TOP, "topCompanies"),
        (IndustryList.GROWTH, "topGrowthCompanies"),
    ):
        companies = cast(list[dict[str, Any]], data.get(field) or [])
        named.extend(
            IndustryListing(
                ticker=str(c["symbol"]), sector=str(sector), industry=industry, named_by=which
            )
            for c in companies
            if c.get("symbol")
        )
    return named

industries()

Every industry of every sector, in Yahoo's order: 145 in 11 sectors.

Source code in src/cointoss/sources/yahoofinance.py
def industries() -> list[Industry]:
    """Every industry of every sector, in Yahoo's order: 145 in 11 sectors."""
    return [
        Industry(sector=sector, industry=industry)
        for sector in SECTORS
        for industry in sector_industries(sector)
    ]

industry_listings(walked=None)

Every company named by the lists of the walked industries, every industry if None.

About 2,600 US tickers over 145 industries in 11 sectors; each sector and industry query is cached on its own, so a walk interrupted part-way resumes from the cache.

Source code in src/cointoss/sources/yahoofinance.py
def industry_listings(walked: list[Industry] | None = None) -> list[IndustryListing]:
    """Every company named by the lists of the `walked` industries, every industry if None.

    About 2,600 US tickers over 145 industries in 11 sectors; each sector and industry query is
    cached on its own, so a walk interrupted part-way resumes from the cache.
    """
    return [
        listing
        for each in (industries() if walked is None else walked)
        for listing in industry_companies(each.industry)
    ]