Skip to content

cointoss.stock_bars

stock_bars

Stock bars (#40): Yahoo daily history for every stock a universe holds or recently held.

ADR-0009 amendment of 2026-11-28. Stock bars are Yahoo's, and a Yahoo re-fetch is a new vintage of the same history, so unlike CoinGecko's they are overwritten. For one US session:

  • A stock with no stored Yahoo bar gets its whole history, period="max".
  • Any other gets a trailing window of WINDOW_DAYS calendar days, reaching back further to its latest stored bar when that is older, and the sessions in it not yet stored are written. The sessions Yahoo returns are the calendar; none is kept here. Reaching back to the latest bar means a machine down longer than the window leaves no gap, whichever of the stock sweep and cointoss backfill runs first.
  • When the window shows a split or a dividend not yet stored, the stock's whole history is fetched again and overwritten, with its Corporate Actions: Yahoo has rescaled every earlier OHLC for a split, or every earlier adj_close for a dividend, so appending the window alone would put a false return into stored history. Store.upsert_bars files a Restatement for any change the actions do not explain. Should that fetch fail, the window is not written either, and the next run sees the action again.

The stocks covered are the current members, on the session, of every universe, the standing Inclusions of every universe, such as a stock traded into portfolio-held (#41), and each former member with a stored Yahoo bar in the last FORMER_MEMBER_DAYS days, so one that leaves a universe but still trades keeps its bars, and a delisted one, which Yahoo answers with no history, drops out 30 days after its last bar. A stock is fetched by the symbol its Ticker History at yahoo names on the session, else its latest there; one with none is skipped.

No bar or action dated after the session is written, so a run before the close never stores the session still trading. Tickers are fetched BATCH_SIZE at a time through one yf.download, YAHOO_INTERVAL between batches. Every fetch happens outside the lock and each batch's writes inside it, reading the store again once it is held.

WINDOW_DAYS = 10 module-attribute

Calendar days of trailing window a daily run fetches: two trading weeks, a holiday or two.

FORMER_MEMBER_DAYS = 30 module-attribute

How recent a former member's latest bar must be for it to stay fetched.

BATCH_SIZE = 50 module-attribute

Tickers per yf.download.

YAHOO_INTERVAL = 2.0 module-attribute

Seconds between Yahoo batches, as cointoss.backfill paces its requests.

StockBarsReport

Bases: BaseModel

What one run of stock bars did, for a caller to log or report.

targets counts the stocks covered. full are those whose whole history was written, new or after a split or dividend; bars counts bars written, overwritten ones included, and actions the Corporate Actions newly stored. failed maps a stock Yahoo gave no history or an unreadable one this run to why; skipped maps one with no Yahoo ticker to why.

Source code in src/cointoss/stock_bars.py
class StockBarsReport(BaseModel):
    """What one run of stock bars did, for a caller to log or report.

    `targets` counts the stocks covered. `full` are those whose whole history was written, new
    or after a split or dividend; `bars` counts bars written, overwritten ones included, and
    `actions` the Corporate Actions newly stored. `failed` maps a stock Yahoo gave no history
    or an unreadable one this run to why; `skipped` maps one with no Yahoo ticker to why.
    """

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

    session: date
    targets: int = 0
    full: list[InstrumentId] = []
    bars: int = 0
    actions: int = 0
    restatements: int = 0
    failed: dict[InstrumentId, str] = {}
    skipped: dict[InstrumentId, str] = {}

stock_bars(store, at, session, *, lock=None) async

Fetch and write the bars of every stock covered, through session. See the module.

at is the moment of the run and stamps the bars' fetched_at.

Source code in src/cointoss/stock_bars.py
async def stock_bars(
    store: Store,
    at: datetime,
    session: date,
    *,
    lock: WriteLock | None = None,
) -> StockBarsReport:
    """Fetch and write the bars of every stock covered, through `session`. See the module.

    `at` is the moment of the run and stamps the bars' `fetched_at`.
    """
    run = _Run(store, as_utc(at), session, lock or nullcontext)
    targets, skipped = _targets(store, session)
    window_start = session - timedelta(days=WINDOW_DAYS)
    starts = {
        t.instrument_id: min(window_start, t.last_bar) for t in targets if t.last_bar is not None
    }
    await run.full([t for t in targets if t.last_bar is None])
    rescaled: list[_Target] = []
    # Ordered by start and asked from each batch's earliest, so differing starts after a
    # downtime still batch; a window reaching back further than needed writes nothing extra.
    held = sorted(
        (t for t in targets if t.instrument_id in starts), key=lambda t: starts[t.instrument_id]
    )
    for batch in _batches(held):
        frames = await run.fetch(batch, start=starts[batch[0].instrument_id])
        rescaled += await run.window(batch, frames)
    await run.full(rescaled)

    report = StockBarsReport(
        session=session,
        targets=len(targets),
        full=run.written_full,
        bars=run.bars,
        actions=run.actions,
        restatements=run.restatements,
        failed=run.failed,
        skipped=skipped,
    )
    log.info(
        "stock bars %s: %d targets, %d full, %d bars, %d actions, %d restatements, "
        "failed %d, skipped %d",
        session,
        report.targets,
        len(report.full),
        report.bars,
        report.actions,
        report.restatements,
        len(report.failed),
        len(report.skipped),
    )
    return report