Skip to content

cointoss.stocks

stocks

The stock sweep (#39): Yahoo's industry lists into Instruments and yahoo-industries membership.

yahoo-industries is a reserved Universe Definition holding a Listing Rule over both of each Yahoo industry's lists (ADR-0007 amendment of 2026-11-28), created by the first sweep and never declared in configuration. Each run, for one US session:

  • fetches every industry's lists (cointoss.sources.yahoofinance.industry_listings), about 2,600 tickers;
  • pins each ticker to the Instrument its Ticker History at yahoo names on the session date, and otherwise by cointoss.ingest.pin_with_attempt, the policy of resolve_typed_symbol with its mandatory FIGI attempt (BRK-B asked as BRK/B), which mints stock.us.* on a hit and an unresolved Instrument on a miss or an outage;
  • evaluates the Listing Rule and records the membership and one Evaluation Run;
  • retries the FIGI attempt of every stock Instrument that was unresolved when the run began, anchoring each that OpenFIGI now answers. Crypto has no retry runner yet;
  • records which industry Yahoo lists each Instrument under, in the yahoo-industry Exposure Series, when that differs from its latest entry;
  • fetches and writes the session's stock bars (cointoss.stock_bars, #40): whole histories for stocks new to them, a trailing window for the rest, and a whole history again after a split or dividend.

yahoo-industry relates Instruments to Yahoo's industries, each keyed {sector}/{industry} so the sector travels with it, as an unscaled score: 1 where an industry's lists name the Instrument. Its target axis is the industries Yahoo had on the first run, fixed for the life of the Series; a listing under an industry outside it is logged and left out, since a new taxonomy is a new Series. An Instrument absent from every list today keeps the industries it was last listed under: membership already records who is listed, and an entry per change in it would store a matrix of 2,600 rows nearly every day. So an entry is appended only when an Instrument is listed for the first time or under other industries than before, dated by the session.

OpenFIGI is asked once per run for every ticker not held and every retry together, in batches of the client's size, 10 anonymously or 100 with OPENFIGI_API_KEY, paced to its rate limit and sent again when refused for it. The first run asks for every ticker, about ten minutes without a key; later runs ask only for tickers new to the lists and the unresolved.

The session is the latest weekday whose US close (16:00 New York) has passed (session_date), so the scheduled run after the close and a manual run that evening or weekend record the same date. No exchange calendar is kept: a holiday is recorded as the weekday it is. A run is idempotent within a session: once yahoo-industries has a Run for it, a further run fetches nothing and writes nothing, bars included; cointoss backfill fills bars a run left out.

Every fetch for the membership happens before the lock is taken, and every write after, so the sweep lock is held for the writes alone and not for minutes of OpenFIGI pacing. The store is read again under the lock: a run that finished meanwhile makes this one a no-op, and a ticker another writer pinned meanwhile is taken from the Ticker History. Bars are fetched once those writes are done, and written under the lock one batch at a time.

YAHOO_INDUSTRIES = 'yahoo-industries' module-attribute

The reserved Universe Definition the stock sweep evaluates; never declared in configuration.

YAHOO_INDUSTRY = 'yahoo-industry' module-attribute

The Exposure Series of which industries Yahoo lists each Instrument under.

SCOPE = 'us' module-attribute

Yahoo's industry lists name US listings.

StockSweepReport

Bases: BaseModel

What one stock sweep did, for a caller to log or report.

already_swept means the session had a Run already, so nothing was fetched or written and the counts are zero. listed counts the distinct tickers the lists named; held those pinned by Ticker History, resolved those a FIGI hit pinned and unresolved those pinned to an Instrument with no FIGI anchor. skipped maps a ticker no single Instrument could be named for to why. retried counts the unresolved stock Instruments whose FIGI attempt was retried, and anchored those it anchored. run is the session's Evaluation Run, industries_changed whether a yahoo-industry entry was appended, and bars what was fetched and written of the stocks' bars.

Source code in src/cointoss/stocks.py
class StockSweepReport(BaseModel):
    """What one stock sweep did, for a caller to log or report.

    `already_swept` means the session had a Run already, so nothing was fetched or written and
    the counts are zero. `listed` counts the distinct tickers the lists named; `held` those
    pinned by Ticker History, `resolved` those a FIGI hit pinned and `unresolved` those pinned
    to an Instrument with no FIGI anchor. `skipped` maps a ticker no single Instrument could be
    named for to why. `retried` counts the unresolved stock Instruments whose FIGI attempt was
    retried, and `anchored` those it anchored. `run` is the session's Evaluation Run,
    `industries_changed` whether a `yahoo-industry` entry was appended, and `bars` what was
    fetched and written of the stocks' bars.
    """

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

    at: datetime
    session: date
    already_swept: bool
    listed: int = 0
    held: int = 0
    resolved: int = 0
    unresolved: int = 0
    skipped: dict[str, str] = {}
    retried: int = 0
    anchored: list[InstrumentId] = []
    run: EvaluationRun | None = None
    industries_changed: bool = False
    bars: StockBarsReport | None = None

session_date(at)

The latest weekday whose US close had passed at at.

>>> from datetime import UTC
>>> session_date(datetime(2026, 11, 27, 22, 30, tzinfo=UTC))  # Friday, after the close
datetime.date(2026, 11, 27)
>>> session_date(datetime(2026, 11, 27, 15, 0, tzinfo=UTC))  # Friday, before it
datetime.date(2026, 11, 26)
>>> session_date(datetime(2026, 11, 30, 2, 0, tzinfo=UTC))  # Sunday evening in New York
datetime.date(2026, 11, 27)
Source code in src/cointoss/stocks.py
def session_date(at: datetime) -> date:
    """The latest weekday whose US close had passed at `at`.

    >>> from datetime import UTC
    >>> session_date(datetime(2026, 11, 27, 22, 30, tzinfo=UTC))  # Friday, after the close
    datetime.date(2026, 11, 27)
    >>> session_date(datetime(2026, 11, 27, 15, 0, tzinfo=UTC))  # Friday, before it
    datetime.date(2026, 11, 26)
    >>> session_date(datetime(2026, 11, 30, 2, 0, tzinfo=UTC))  # Sunday evening in New York
    datetime.date(2026, 11, 27)
    """
    local = as_utc(at).astimezone(NEW_YORK)
    day = local.date() if local.time() >= US_CLOSE else local.date() - timedelta(days=1)
    while day.weekday() >= 5:
        day -= timedelta(days=1)
    return day

sweep_stocks(store, at, *, force=False, figi=None, lock=None) async

Evaluate yahoo-industries for the session at closes, then retry unresolved stocks.

See the module docstring. force runs again for a session that has a Run, resolving and retrying anew; its membership is still evaluated once per session, so the Run recorded first is the one reported. lock is entered around the writes.

Source code in src/cointoss/stocks.py
async def sweep_stocks(
    store: Store,
    at: datetime,
    *,
    force: bool = False,
    figi: OpenFigiClient | None = None,
    lock: WriteLock | None = None,
) -> StockSweepReport:
    """Evaluate `yahoo-industries` for the session `at` closes, then retry unresolved stocks.

    See the module docstring. `force` runs again for a session that has a Run, resolving and
    retrying anew; its membership is still evaluated once per session, so the Run recorded
    first is the one reported. `lock` is entered around the writes.
    """
    moment = as_utc(at)
    session = session_date(moment)
    if not force and _swept(store, session):
        log.info("stock sweep %s: already swept", session)
        return StockSweepReport(at=moment, session=session, already_swept=True)

    walked = await asyncio.to_thread(industries)
    listed = await asyncio.to_thread(industry_listings, walked)
    tickers = _distinct_tickers(listed)
    skipped: dict[str, str] = {}
    held: dict[str, InstrumentId] = {}
    for ticker in tickers:
        try:
            found = store.resolve_symbol(Source.YAHOO, ticker, session, scope=SCOPE)
        except AmbiguousSymbol as exc:
            skipped[ticker] = str(exc)
            continue
        if found is not None:
            held[ticker] = found
    asked = [t for t in tickers if t not in held and t not in skipped]
    waiting = [i for i in store.load_registry().unresolved() if i.type is InstrumentType.STOCK]
    attempts = await figi_attempts(
        figi or OpenFigiClient(rate_limit_retries=RATE_LIMIT_RETRIES),
        [(InstrumentType.STOCK, figi_job(Source.YAHOO, t, SCOPE)) for t in asked]
        + [figi_request(i) for i in waiting],
    )
    by_ticker = dict(zip(asked, attempts[: len(asked)], strict=True))
    retries = dict(zip((i.id for i in waiting), attempts[len(asked) :], strict=True))

    async with (lock or nullcontext)():
        if not force and _swept(store, session):
            log.info("stock sweep %s: swept meanwhile", session)
            return StockSweepReport(at=moment, session=session, already_swept=True)
        definition = _definition(store, session)
        pinned, counts = _pin(store, tickers, held, by_ticker, session, skipped)
        run = _evaluate_once(store, definition, listed, pinned, session, moment)
        industries_changed = _record_industries(store, walked, listed, pinned, session)
        anchored = _retry(store, retries, session)
    bars = await stock_bars(store, moment, session, lock=lock)

    report = StockSweepReport(
        at=moment,
        session=session,
        already_swept=False,
        listed=len(tickers),
        held=len(held),
        resolved=counts[FigiResolution.RESOLVED],
        unresolved=counts[FigiResolution.NOT_FOUND] + counts[FigiResolution.NOT_ATTEMPTED],
        skipped=skipped,
        retried=len(retries),
        anchored=anchored,
        run=run,
        industries_changed=industries_changed,
        bars=bars,
    )
    log.info(
        "stock sweep %s: listed %d, held %d, resolved %d, unresolved %d, skipped %d, "
        "retried %d, anchored %d, industries changed %s",
        session,
        report.listed,
        report.held,
        report.resolved,
        report.unresolved,
        len(report.skipped),
        report.retried,
        len(report.anchored),
        report.industries_changed,
    )
    return report