cointoss.explorer¶
explorer
¶
What the Dataset explorer decides, kept out of its Streamlit script (cointoss.explorer_app).
The explorer knows only what datasets() describes (ADR-0010). From a Dataset's params JSON
Schema it derives one input widget per parameter; from its column roles it derives a chart
(the time column on x, a chosen measure on y, one line per entity) and a pivot (time by
entity for one measure). The functions here are plain, so they are tested without Streamlit.
Three parameter names get richer widgets than their schema type gives: universe picks from
the stored universes, instruments from the instruments Dataset, and a date named start
defaults to DEFAULT_LOOKBACK before today. A measure whose name ends in _return is a simple
return, so the chart can compound it.
Cached reads are keyed on the viewer as well as the request (viewer_key), so one viewer's
data is never served to another.
ROW_COUNT = '(row count)'
module-attribute
¶
The measure charted for a Dataset with a time column but no measure: rows per time.
ParamWidget
dataclass
¶
One parameter's input. An optional parameter left empty is not sent.
Source code in src/cointoss/explorer.py
ChartSpec
dataclass
¶
How a Dataset charts: time on x, one of measures on y, a line per entity value.
compounding are the measures that are simple returns, which the chart can show
cumulatively. Without an entity column, there is one line.
Source code in src/cointoss/explorer.py
param_widgets(schema, today)
¶
The widgets for a params JSON Schema, in property order.
>>> schema = {
... "properties": {
... "start": {"type": "string", "format": "date", "title": "Start"},
... "end": {"type": "string", "format": "date"},
... "source": {"anyOf": [{"$ref": "#/$defs/S"}, {"type": "null"}], "default": None},
... "universe": {"anyOf": [{"type": "string"}, {"type": "null"}], "default": None},
... "ever": {"type": "boolean", "default": False},
... },
... "required": ["start", "end"],
... "$defs": {"S": {"enum": ["yahoo", "coingecko"], "type": "string"}},
... }
>>> for w in param_widgets(schema, dt.date(2026, 10, 23)):
... print(w.name, w.kind, w.required, w.default, w.options)
start date True 2026-07-25 ()
end date True 2026-10-23 ()
source choice False None ('yahoo', 'coingecko')
universe universe False None ()
ever bool False False ()
Source code in src/cointoss/explorer.py
build_params(widgets, values)
¶
The frame params for widget values: dates as ISO text, empty optional values left out.
A boolean is sent only when it differs from its default, so an unticked flag is not sent.
>>> ws = param_widgets(
... {
... "properties": {
... "start": {"type": "string", "format": "date"},
... "instruments": {"type": "array", "items": {"type": "string"}},
... "universe": {"type": "string"},
... "ever": {"type": "boolean", "default": False},
... },
... "required": ["start"],
... },
... dt.date(2026, 1, 1),
... )
>>> build_params(ws, {"start": dt.date(2026, 1, 2), "instruments": [], "universe": "", "ever": False})
{'start': '2026-01-02'}
>>> build_params(ws, {"start": dt.date(2026, 1, 2), "instruments": ["a"], "ever": True})
{'start': '2026-01-02', 'instruments': ['a'], 'ever': True}
Source code in src/cointoss/explorer.py
chart_spec(columns)
¶
The chart for a Dataset's columns as datasets() lists them; None without a time column.
A Dataset with no numeric measure charts its row count per time instead.
>>> def col(name, type_, role):
... return {"name": name, "type": type_, "role": role}
>>> chart_spec([
... col("date", "date", "time"), col("instrument_id", "str", "entity"),
... col("close", "float", "measure"), col("simple_return", "float", "measure"),
... ])
ChartSpec(time='date', entity='instrument_id', measures=('close', 'simple_return'), compounding=frozenset({'simple_return'}))
>>> chart_spec([col("valid_from", "date", "time"), col("universe", "str", "attribute")])
ChartSpec(time='valid_from', entity=None, measures=('(row count)',), compounding=frozenset())
>>> chart_spec([col("instrument_id", "str", "entity")]) is None
True
Source code in src/cointoss/explorer.py
pivot(df, spec, measure)
¶
measure as a time by entity table, sorted by time; the row count per time for ROW_COUNT.
>>> df = pd.DataFrame({
... "date": pd.to_datetime(["2024-03-02", "2024-03-01", "2024-03-01"]),
... "id": ["a", "a", "b"],
... "close": [2.0, 1.0, 10.0],
... })
>>> spec = ChartSpec("date", "id", ("close",), frozenset())
>>> wide = pivot(df, spec, "close")
>>> wide.index.strftime("%d").tolist(), wide.to_dict("list")
(['01', '02'], {'a': [1.0, 2.0], 'b': [10.0, nan]})
>>> pivot(df, spec, ROW_COUNT)["rows"].tolist()
[2, 1]
Source code in src/cointoss/explorer.py
chart_frame(df, spec, measure, *, entities=None, cumulative=False)
¶
The wide frame a line chart draws: pivot, narrowed to entities, maybe compounded.
Compounding treats a missing return as zero, so a line carries on across a date with no return, and stays blank before an entity's first return.
>>> df = pd.DataFrame({
... "date": pd.to_datetime(["2024-03-01", "2024-03-02", "2024-03-02", "2024-03-03"]),
... "id": ["a", "a", "b", "b"],
... "simple_return": [0.1, 0.1, 0.5, None],
... })
>>> spec = chart_spec([
... {"name": "date", "type": "date", "role": "time"},
... {"name": "id", "type": "str", "role": "entity"},
... {"name": "simple_return", "type": "float", "role": "measure"},
... ])
>>> chart_frame(df, spec, "simple_return", cumulative=True).round(4).to_dict("list")
{'a': [0.1, 0.21, 0.21], 'b': [nan, 0.5, 0.5]}
>>> list(chart_frame(df, spec, "simple_return", entities=["b"]).columns)
['b']
Source code in src/cointoss/explorer.py
viewer_key(user, token)
¶
Who a cached read belongs to: the User and a digest of their Delegated Token.
The token changes with each Session, so a read cached in one Session is not served in another, even to the same User; the digest keeps the token itself out of cache keys.
>>> ann = ViewingUser(id="u1", name="Ann")
>>> viewer_key(ann, "t1") == viewer_key(ann, "t1")
True
>>> len({viewer_key(ann, "t1"), viewer_key(ann, "t2"), viewer_key(ViewingUser(id="u2", name="Bo"), "t1")})
3
>>> viewer_key(None, None)
'anonymous:'
Source code in src/cointoss/explorer.py
header(headers, name)
¶
A request header by case-insensitive name.