cointoss.prices¶
prices
¶
Price history: Bars, Corporate Actions, and the Restatement log that keeps them honest.
Implements ADR-0009. A Bar is keyed by instrument, source and session date, so two sources that
disagree about a close each keep their own row rather than one overwriting the other. Only
close is required: a CoinGecko point is a close and a volume and nothing else, and dressing it
up as a full candle with invented open, high and low would make a synthetic candle
indistinguishable from a real one.
One vintage of history is kept, stamped with fetched_at. What a re-fetch changed is recorded
separately as a Restatement rather than by keeping every vintage, which is why the comparison
below has to be careful: a split legitimately rescales every bar before it, so a naive float
comparison would file a Restatement for every date in the series and bury the real anomalies.
detect_restatements therefore asks whether the ratio between the stored and incoming value is
the cumulative split factor implied by the actions dated after that bar, and only reports a
change that neither that factor nor float noise explains.
Yahoo's "unadjusted" prices are already split-adjusted -- auto_adjust=False withholds only the
dividend adjustment -- so the split rescale is a fact about the stored history, not something
this module could avoid by asking for raw prices.
Pure: no network, no clock, no database. Fetch times and detection times are supplied by the caller, which keeps the module testable and makes replaying a recorded frame ordinary.
RELATIVE_TOLERANCE = 1e-06
module-attribute
¶
How far two values for one field may drift, relative to their size, before it is a change.
Relative rather than absolute so a coin quoted at 0.0003 and a share quoted at 400 are held to the same standard: an absolute epsilon would either wave through every real move in the cheap one or file the expensive one's rounding as a restatement.
PRICE_FIELDS = ('open', 'high', 'low', 'close', 'adj_close')
module-attribute
¶
The Bar fields a split rescales downward. volume rescales upward and is handled apart.
PriceError
¶
MissingColumn
¶
Bases: PriceError
A source frame does not carry a column the mapping requires.
MalformedValue
¶
Bases: PriceError
A Bar or Corporate Action carries a value that cannot be a price, size or ratio.
BarKeyMismatch
¶
Bases: PriceError
Two bars offered for comparison are not two vintages of one bar.
CorporateActionKind
¶
Bases: StrEnum
What a Corporate Action did. A dividend carries its amount, a split its ratio.
Source code in src/cointoss/prices.py
Bar
¶
Bases: BaseModel
One session's prices for one instrument, as one source reported them.
close is the only required price. Open, high, low, adjusted close and volume are nullable
because a close-only source -- CoinGecko's market_chart is the one in hand -- has nothing
to put in them, and a null says so where a fabricated value would not.
source and fetched_at are part of the record rather than of the fetch job: a
heterogeneous series stays legible, and a vintage stays identifiable even though only one is
kept.
market_cap is carried where the source reports one, as CoinGecko does. It is not a price
and plays no part in restatement detection: it is price times a circulating supply the
vendor re-estimates freely, so a revised supply would file noise rather than a rewritten
price history.
>>> b = Bar(
... instrument_id=InstrumentId("crypto.eth.usdc"),
... source=Source.COINGECKO,
... bar_date=date(2024, 6, 5),
... close=1.0004,
... volume=8.2e8,
... fetched_at=datetime(2024, 6, 6, 0, 0),
... )
>>> b.open is None and b.adj_close is None
True
>>> b.key
(InstrumentId('crypto.eth.usdc'), <Source.COINGECKO: 'coingecko'>, datetime.date(2024, 6, 5))
Source code in src/cointoss/prices.py
key
property
¶
What identifies the bar. Two sources on one date are two bars, not a conflict.
CorporateAction
¶
Bases: BaseModel
A dividend or a split, as one source reported it.
Stored as its own record so a stored history that changed has a reason on file. Only non-zero rows exist: a source that reports a zero dividend on every ordinary day is saying nothing happened, and storing that would bury the days something did.
>>> CorporateAction(
... instrument_id=InstrumentId("stock.us.nvda"),
... source=Source.YAHOO,
... action_date=date(2024, 6, 10),
... kind=CorporateActionKind.SPLIT,
... value=10.0,
... ).kind
<CorporateActionKind.SPLIT: 'split'>
Source code in src/cointoss/prices.py
Restatement
¶
Bases: BaseModel
A stored value a re-fetch changed, with no corporate action to explain it.
One record per field, not per bar, so the log says what moved rather than only that something did.
Source code in src/cointoss/prices.py
bars_from_yahoo(instrument_id, frame, fetched_at)
¶
Map one Yahoo daily frame into Bars and Corporate Actions in a single pass.
Reads the date column cointoss.sources.yahoofinance.get_prices inserts, plus Yahoo's own
Open, High, Low, Close, Adj Close, Volume, Dividends, Stock Splits. Only date and
Close are required; a frame without the action columns yields bars and no actions.
Zero dividend and zero split cells are ordinary days, so they produce no record. Splits are
reported as a ratio, dividends as an amount per share; both go into value under their own
kind rather than into two differently shaped records.
Source code in src/cointoss/prices.py
is_provisional(bar)
¶
Whether the bar was fetched before its session could be known to have closed.
A bar fetched on or before its own session date may describe a day still in progress: Yahoo serves the running session intraday. Its values are expected to move once the day finishes, so a later re-fetch replacing it is the day completing, not a Restatement.
A CoinGecko bar is the exception. Its bar for a date is the price at that date's 00:00 UTC -- the label CoinGecko puts on its own daily point, and what the daily sweep records from a listing fetched just after midnight -- so it is final from the moment that day begins, and provisional only if fetched before it.
Judged on the UTC calendar, because no session time is stored (ADR-0009). That is exact for
a crypto bar, whose session is the UTC day, and conservative for a listed venue, whose
session for a date closes before that date ends in UTC: a bar fetched after the close but
before UTC midnight is called provisional although it is final. The cost of that error is
one re-fetch left unchecked; the opposite error files ordinary progress as a Restatement.
A naive fetched_at is read as UTC.
>>> bar = Bar(
... instrument_id=InstrumentId("stock.us.nvda"), source=Source.YAHOO,
... bar_date=date(2026, 9, 29), close=118.4, fetched_at=datetime(2026, 9, 29, 21, 0),
... )
>>> is_provisional(bar)
True
>>> is_provisional(bar.model_copy(update={"fetched_at": datetime(2026, 9, 30, 0, 5)}))
False
>>> swept = bar.model_copy(
... update={"source": Source.COINGECKO, "fetched_at": datetime(2026, 9, 29, 0, 5)}
... )
>>> is_provisional(swept)
False
Source code in src/cointoss/prices.py
as_utc(moment)
¶
A moment in UTC, reading a naive one as already UTC.
Naive times are labelled rather than converted, since astimezone would read them as the
machine's local time. Aware ones are converted, so their UTC calendar date is the right one.
>>> as_utc(datetime(2026, 9, 29, 23, 30)).isoformat()
'2026-09-29T23:30:00+00:00'
>>> from datetime import timedelta, timezone
>>> as_utc(datetime(2026, 9, 29, 23, 30, tzinfo=timezone(timedelta(hours=-5)))).isoformat()
'2026-09-30T04:30:00+00:00'
Source code in src/cointoss/prices.py
split_factor_after(actions, when)
¶
The cumulative split ratio implied by splits dated strictly after when.
Strictly after, because a source reports the split on the first session that trades at the new ratio: that day's bar is already post-split and only the days before it get rescaled.
Source code in src/cointoss/prices.py
detect_restatements(stored, incoming, actions)
¶
Which of the bar's fields a re-fetch changed for a reason the actions do not explain.
Both bars must be two vintages of one (instrument, source, date); comparing across keys is
a caller bug and is refused rather than silently reported as a restatement of everything.
A split rescales prices down by its cumulative ratio and volume up by the same ratio, so a
re-fetch across one rewrites every earlier bar. That is the expected shape of the change,
not an anomaly, and it is accepted silently. So is a difference within
RELATIVE_TOLERANCE. What remains -- a value that is neither where it was nor where the
split would have put it -- is the Restatement.
One exception: Yahoo lowers every earlier adj_close for a new dividend, so an adj_close
lowered relative to an explained close is accepted when a dividend is dated after the bar.
A dividend explains no rise, and no move beside an unexplained close.
detected_at is taken from the incoming bar's fetched_at: the change became visible at
the fetch that carried it, and the module holds no clock of its own.
>>> aapl = InstrumentId("stock.us.aapl")
>>> when = datetime(2024, 7, 1, 0, 0)
>>> stored = Bar(
... instrument_id=aapl, source=Source.YAHOO, bar_date=date(2024, 6, 3),
... close=100.0, volume=1000.0, fetched_at=datetime(2024, 6, 4, 0, 0),
... )
>>> split = CorporateAction(
... instrument_id=aapl, source=Source.YAHOO, action_date=date(2024, 6, 10),
... kind=CorporateActionKind.SPLIT, value=10.0,
... )
>>> rescaled = stored.model_copy(update={"close": 10.0, "volume": 10000.0, "fetched_at": when})
>>> detect_restatements(stored, rescaled, [split])
[]
>>> [r.field for r in detect_restatements(stored, rescaled.model_copy(update={"close": 9.5}), [split])]
['close']
Source code in src/cointoss/prices.py
bars_from_market_chart(instrument_id, payload, fetched_at)
¶
Map one CoinGecko market chart payload into one close-only Bar per UTC day.
Each bar carries the day's volume and market cap where the payload has them.
The endpoint is close-only, so open, high and low stay null. So does adj_close:
CoinGecko applies no dividend adjustment, and ADR-0009 keeps the field null rather than
mirroring close so that equal by coincidence and equal by definition do not look alike.
The three series are aligned by UTC day rather than by position, since nothing in the payload promises they are parallel. A day with a price but no volume or market cap point yields a bar with that field null; a volume or market cap point on a day with no price yields nothing, because a Bar needs a close.
Within one day the first point wins. A CoinGecko bar for a date is the price at that date's
00:00 UTC, the point CoinGecko itself labels with the date and the one the daily sweep
records. The API appends a trailing point at the current time, so the final day of a
365-day fetch carries both its 00:00 point and a later one, and short windows space points
hourly; taking the first keeps the 00:00 point in both cases, so the bar does not depend on
days or on the time of the fetch, and is_provisional can treat it as final. The one
exception is the first day of an hourly window, which starts at the fetch time days back
and has no 00:00 point; a backfill that must match the sweep asks for 90 days or more.
Only the window the payload covers is mapped. The free tier stops at 365 days
(cointoss.sources.coingecko.MARKET_CHART_MAX_DAYS), and asking for more raises there
rather than arriving here as a short result.