Skip to content

cointoss.backfill

backfill

History backfill (#26): fill every date with no stored bar, from CoinGecko and from Yahoo.

The daily sweep writes one CoinGecko bar per coin per day, and only within the bar window, so a day the machine was down or swept late has no bar, and nothing before the first sweep has one. backfill fills those dates for every coin that has ever been a member of any universe (folded through Supersession), from two sources:

  • CoinGecko market_chart over the last days days (90 to 365, the free tier's reach). Each date gets the bar the sweep would have written: the 00:00 UTC price, with volume and market cap. A day whose payload has no point at exactly 00:00 -- today, before CoinGecko publishes it -- is left alone rather than given a later price.
  • Yahoo, for a coin paired with Yahoo: get_prices(period="max"), back to the pair's listing, for dates strictly before today UTC, so no Provisional Bar is written.

A coin is paired by trying its YAHOO_PAIRS entry, if it has one, then {SYMBOL}-USD (ADR-0009 amendment of 2026-10-30), then the tickers Yahoo search lists for the symbol with a numeric suffix, such as UNI7083-USD; the first whose prices agree is the pair. A ticker is accepted when Yahoo's close for session D and CoinGecko's bar stamped D+1, which closes D, differ by less than PAIR_TOLERANCE in median over the last PAIR_SESSIONS sessions both hold. An accepted pair is recorded through the Instrument Registry as an Observation from Yahoo carrying the coin's CoinGecko id and a Yahoo provider id, which adds the Yahoo External Reference and opens a Ticker History record at source yahoo without touching the display symbol or the Price Sources. A refused ticker is logged; a coin none of whose tickers agree stores nothing, and is tried again on the next backfill. A ticker whose Yahoo reference another Instrument already holds is refused too: recording it would be read as evidence the two are one coin, and supersede one of them.

Stocks are not filled here but by cointoss.stock_bars (#40), as the stock sweep fills them, for the latest US session closed: a new stock's whole history, the rest from their latest stored bar, and a whole history again after a split or dividend. Running it here too fills the bars of a stock sweep that did not run, or ran before the bars were written.

For coins, only dates with no stored bar from the source are written, so no stored bar is overwritten and no Restatement is filed. Membership is not backfilled: record_membership refuses a date earlier than the latest Evaluation Run.

Network fetches run outside the sweep lock and each write inside it, through the lock the caller passes: the store is read again for what is missing once the lock is held, so a sweep that wrote today's bar meanwhile keeps it, and a sweep waiting for the lock is held up for one coin's write rather than the whole backfill. CoinGecko is paced by its client's rpm, Yahoo by YAHOO_INTERVAL between requests, searches included.

DEFAULT_DAYS = MARKET_CHART_MAX_DAYS module-attribute

The CoinGecko window asked for by default: all the free tier serves.

MIN_DAYS = 90 module-attribute

The shortest CoinGecko window: below it the API spaces points hourly, off 00:00 UTC.

PAIR_SESSIONS = 30 module-attribute

How many of the latest sessions both sources hold a Yahoo pair is checked over.

PAIR_TOLERANCE = 0.03 module-attribute

The median relative difference under which a Yahoo pair is the coin CoinGecko names.

3% rather than 2% admits SHIB-USD, which differs by 2.7%; the coins that collide with an unrelated Yahoo asset differ by far more.

COINGECKO_RPM = 10.0 module-attribute

Requests per minute to CoinGecko's free tier, which throttles a second immediate call.

YAHOO_INTERVAL = 2.0 module-attribute

Seconds between Yahoo requests. yfinance has no limiter of its own.

YAHOO_PAIRS = {'blockstack': 'STX4847-USD', 'bittensor': 'TAO22974-USD', 'layerzero': 'ZRO26997-USD', 'ondo-us-dollar-yield': 'USDY29256-USD', 'polygon-ecosystem-token': 'POL28321-USD', 'quack-ai': 'Q38236-USD', 'united-stables': 'U39120-USD', 'usd1-wlfi': 'USD136148-USD', 'venice-token': 'VVV35509-USD'} module-attribute

CoinGecko id -> Yahoo ticker, for coins Yahoo lists that neither the guess nor search finds.

Tried before the guess, and accepted only when its prices agree, as any other ticker.

BackfillReport

Bases: BaseModel

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

paired are the Instruments whose Yahoo pair was accepted this run; rejected maps an Instrument whose pair was tried and refused, or has no Yahoo history, to why. failed maps an Instrument to a fetch that failed, which leaves its dates for the next run. skipped maps a coin that cannot be backfilled, with no CoinGecko id, to why. targets counts the coins; stocks is what the stock path did.

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

    `paired` are the Instruments whose Yahoo pair was accepted this run; `rejected` maps an
    Instrument whose pair was tried and refused, or has no Yahoo history, to why. `failed` maps
    an Instrument to a fetch that failed, which leaves its dates for the next run. `skipped`
    maps a coin that cannot be backfilled, with no CoinGecko id, to why. `targets` counts the
    coins; `stocks` is what the stock path did.
    """

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

    at: datetime
    days: int
    targets: int
    coingecko_bars: int
    yahoo_bars: int
    paired: list[InstrumentId]
    rejected: dict[InstrumentId, str]
    failed: dict[InstrumentId, str]
    skipped: dict[InstrumentId, str]
    stocks: StockBarsReport

median_disagreement(yahoo, coingecko, sessions=PAIR_SESSIONS)

Median relative difference of two close series over the last sessions both hold.

Both are keyed by the session closed, so a CoinGecko close is keyed by its stamped date less its Session Offset. Relative to CoinGecko's close. None when fewer sessions overlap.

>>> d = [date(2026, 10, n) for n in range(1, 5)]
>>> median_disagreement({d[0]: 99.0, d[1]: 110.0, d[2]: 200.0}, {d[0]: 100.0, d[1]: 100.0, d[2]: 100.0}, 3)
0.1
>>> median_disagreement({d[0]: 1.0}, {d[0]: 1.0, d[1]: 1.0}, 2) is None
True
Source code in src/cointoss/backfill.py
def median_disagreement(
    yahoo: Mapping[date, float],
    coingecko: Mapping[date, float],
    sessions: int = PAIR_SESSIONS,
) -> float | None:
    """Median relative difference of two close series over the last `sessions` both hold.

    Both are keyed by the session closed, so a CoinGecko close is keyed by its stamped date
    less its Session Offset. Relative to CoinGecko's close. None when fewer sessions overlap.

    >>> d = [date(2026, 10, n) for n in range(1, 5)]
    >>> median_disagreement({d[0]: 99.0, d[1]: 110.0, d[2]: 200.0}, {d[0]: 100.0, d[1]: 100.0, d[2]: 100.0}, 3)
    0.1
    >>> median_disagreement({d[0]: 1.0}, {d[0]: 1.0, d[1]: 1.0}, 2) is None
    True
    """
    both = sorted(set(yahoo) & set(coingecko))[-sessions:]
    if len(both) < sessions:
        return None
    return statistics.median(abs(yahoo[d] - coingecko[d]) / coingecko[d] for d in both)

backfill(store, at, *, days=DEFAULT_DAYS, coingecko=None, lock=None) async

Fill every missing CoinGecko and Yahoo date for every coin ever a member, then stock bars.

at is the moment of the run: its UTC date is today, the first date no Yahoo bar is written for a coin, and it stamps the bars' fetched_at. lock is entered around each write. Raises ValueError for a days outside MIN_DAYS to MARKET_CHART_MAX_DAYS, before anything is fetched. See the module docstring for what is written and how a coin is paired.

Source code in src/cointoss/backfill.py
async def backfill(
    store: Store,
    at: datetime,
    *,
    days: int = DEFAULT_DAYS,
    coingecko: CoinGeckoClient | None = None,
    lock: WriteLock | None = None,
) -> BackfillReport:
    """Fill every missing CoinGecko and Yahoo date for every coin ever a member, then stock bars.

    `at` is the moment of the run: its UTC date is today, the first date no Yahoo bar is written
    for a coin, and it stamps the bars' `fetched_at`. `lock` is entered around each write. Raises
    `ValueError` for a `days` outside `MIN_DAYS` to `MARKET_CHART_MAX_DAYS`, before anything
    is fetched. See the module docstring for what is written and how a coin is paired.
    """
    if not MIN_DAYS <= days <= MARKET_CHART_MAX_DAYS:
        raise ValueError(f"days={days} is outside {MIN_DAYS}..{MARKET_CHART_MAX_DAYS}")
    moment = as_utc(at)
    run = _Run(
        store,
        moment,
        coingecko or CoinGeckoClient(rpm=COINGECKO_RPM),
        lock or nullcontext,
    )
    targets = _targets(store)
    for instrument in targets:
        await run.instrument(instrument, days)
    stocks = await stock_bars(store, moment, session_date(moment), lock=run.lock)
    log.info(
        "backfill %s: %d targets, %d CoinGecko bars, %d Yahoo bars, paired %s, rejected %d",
        moment.date(),
        len(targets),
        run.coingecko_bars,
        run.yahoo_bars,
        sorted(run.paired) or "none",
        len(run.rejected),
    )
    return BackfillReport(
        at=moment,
        days=days,
        targets=len(targets),
        coingecko_bars=run.coingecko_bars,
        yahoo_bars=run.yahoo_bars,
        paired=run.paired,
        rejected=run.rejected,
        failed=run.failed,
        skipped=run.skipped,
        stocks=stocks,
    )