Skip to content

cointoss.datasets

datasets

Datasets: named, typed, long-form tables read through the frame node (ADR-0010).

A Dataset is a definition in code: a name, a description, a pydantic params model, its columns, and a reader that turns the store and validated params into rows. DATASETS is the registry the datasets and frame nodes on cointoss.app.CointossApp serve, so adding a Dataset means adding one definition here, plus a store read if no existing one fits. Nothing here touches SQL: rows come through cointoss.store (ADR-0008).

Every Dataset is long, one row per fact with a fixed column list, and every column declares a type and a role so a client can pick axes and series without guessing from names. Rows about an Instrument carry its survivor's instrument_id and current symbol; the rest of its attributes are in the instruments Dataset.

woodglue serializes a node's pydantic result with model_dump(mode="json"), so a date reaches a JSON-RPC client as an ISO string. load reads the column types datasets publishes and puts them back on a pandas DataFrame. pandas is imported only there, from the ui extra.

An OwnedDataset holds a User's own records, the Portfolios: it is read for one owner, the caller's User id, which the app passes and no param can set, and a Portfolio named in its params that the owner does not hold is UnknownPortfolio, as one that does not exist.

A response holds at most ROW_CAP rows. The cap is read when a frame is read, so a test can patch it. Over it is TooManyRows naming the matching count; there is no paging.

ROW_CAP = 250000 module-attribute

The most rows one frame call returns.

DEFAULT_NAMESPACE = 'cointoss.data' module-attribute

The JSON-RPC method prefix cointoss init mounts the fragment under.

UnknownDataset

Bases: LookupError

No Dataset by that name.

Source code in src/cointoss/datasets.py
class UnknownDataset(LookupError):
    """No Dataset by that name."""

InvalidParams

Bases: ValueError

Params a Dataset's model refused, with the first error on one line.

Source code in src/cointoss/datasets.py
class InvalidParams(ValueError):
    """Params a Dataset's model refused, with the first error on one line."""

ColumnRole

Bases: StrEnum

What a column is for: the time axis, the thing a row is about, a value, or a label.

Source code in src/cointoss/datasets.py
class ColumnRole(StrEnum):
    """What a column is for: the time axis, the thing a row is about, a value, or a label."""

    TIME = "time"
    ENTITY = "entity"
    MEASURE = "measure"
    ATTRIBUTE = "attribute"

DatasetView

Bases: BaseModel

A Dataset as datasets lists it: its columns and the JSON Schema of its params.

Source code in src/cointoss/datasets.py
class DatasetView(BaseModel):
    """A Dataset as `datasets` lists it: its columns and the JSON Schema of its params."""

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

    name: str
    description: str
    columns: list[Column]
    params: dict[str, Any]

Dataset dataclass

Bases: _Definition[P]

A Dataset anyone with the namespace's Grant reads in full.

rows returns each row's values in columns order.

Source code in src/cointoss/datasets.py
@dataclass(frozen=True)
class Dataset(_Definition[P]):
    """A Dataset anyone with the namespace's Grant reads in full.

    `rows` returns each row's values in `columns` order.
    """

    rows: Callable[[Store, P], Rows]

    def read(self, store: Store, params: P) -> FrameData:
        """The Dataset as a frame, raising `TooManyRows` past `ROW_CAP`."""
        return self._frame(self.rows(store, params))

read(store, params)

The Dataset as a frame, raising TooManyRows past ROW_CAP.

Source code in src/cointoss/datasets.py
def read(self, store: Store, params: P) -> FrameData:
    """The Dataset as a frame, raising `TooManyRows` past `ROW_CAP`."""
    return self._frame(self.rows(store, params))

OwnedDataset dataclass

Bases: _Definition[P]

A Dataset of one User's records, which read cannot be called without.

rows returns the owner's rows, each row's values in columns order.

Source code in src/cointoss/datasets.py
@dataclass(frozen=True)
class OwnedDataset(_Definition[P]):
    """A Dataset of one User's records, which `read` cannot be called without.

    `rows` returns the owner's rows, each row's values in `columns` order.
    """

    rows: Callable[[Store, P, UserId], Rows]

    def read(self, store: Store, params: P, owner: UserId) -> FrameData:
        """The Dataset as `owner` holds it, raising `TooManyRows` past `ROW_CAP`."""
        return self._frame(self.rows(store, params, owner))

read(store, params, owner)

The Dataset as owner holds it, raising TooManyRows past ROW_CAP.

Source code in src/cointoss/datasets.py
def read(self, store: Store, params: P, owner: UserId) -> FrameData:
    """The Dataset as `owner` holds it, raising `TooManyRows` past `ROW_CAP`."""
    return self._frame(self.rows(store, params, owner))

load(client, name, /, *, namespace=DEFAULT_NAMESPACE, **params) async

Read a Dataset over JSON-RPC into a pandas DataFrame with its column types applied.

Async, because WoodglueClient.call is; a sync caller such as Streamlit wraps it in asyncio.run. Calls datasets for the column types, then frame. A date column becomes naive datetime64 at midnight and a datetime column UTC-aware datetime64, so both chart and resample directly; a nullable int or bool column uses pandas' nullable dtype. namespace is the method prefix the fragment is mounted under. A JSON-RPC error raises woodglue.client.WoodglueRpcError.

Needs pandas, from the ui extra.

Source code in src/cointoss/datasets.py
async def load(
    client: WoodglueClient,
    name: str,
    /,
    *,
    namespace: str = DEFAULT_NAMESPACE,
    **params: Any,
) -> pd.DataFrame:
    """Read a Dataset over JSON-RPC into a pandas DataFrame with its column types applied.

    Async, because `WoodglueClient.call` is; a sync caller such as Streamlit wraps it in
    `asyncio.run`. Calls `datasets` for the column types, then
    `frame`. A `date` column becomes naive `datetime64` at midnight and a `datetime` column
    UTC-aware `datetime64`, so both chart and resample directly; a nullable `int` or `bool`
    column uses pandas' nullable dtype. `namespace` is the method prefix the fragment is
    mounted under. A JSON-RPC error raises `woodglue.client.WoodglueRpcError`.

    Needs pandas, from the `ui` extra.
    """
    import pandas as pd

    described = await client.call(f"{namespace}:datasets")
    types = {
        c["name"]: ColumnType(c["type"])
        for d in described
        if d["name"] == name
        for c in d["columns"]
    }
    frame = FrameData.model_validate(
        await client.call(f"{namespace}:frame", dataset=name, params=params)
    )
    df = frame.pd.frame()
    for column, type_ in types.items():
        if column not in df.columns:
            continue
        values = cast("pd.Series", df[column])
        if type_ is ColumnType.DATE:
            df[column] = pd.to_datetime(values, format="ISO8601")
        elif type_ is ColumnType.DATETIME:
            df[column] = pd.to_datetime(values, format="ISO8601", utc=True)
        else:
            df[column] = values.astype(_PANDAS_DTYPES[type_])
    return df