Skip to content

Data Contracts

The table contracts, the converter to display units, and the validators that check a frame at a package boundary. Validators check that the required columns are present and that the events and trades columns have the dtypes in EVENT_DTYPES and TRADE_DTYPES; extra columns are allowed.

Table contracts

One contract per table the package returns. Each column has its dtype and says whether it is a price, a size or neither. The schema page describes the same tables.

TABLES module-attribute

TABLES: dict[str, Table] = {
    (name): table
    for table in (
        EVENTS,
        TRADES,
        DEPTH,
        DEPTH_SUMMARY,
        LIFECYCLES,
        QUEUE,
        BOOK,
        BARS,
        COSTS,
    )
}

Every table contract, by table name.

The features table is not here: its columns follow the features asked for. Its index columns are :data:ob_analytics.features.INDEX_COLUMNS.

Table dataclass

Table(
    name: str,
    columns: tuple[Column, ...],
    bin_columns: tuple[Column, ...] = (),
)

The contract of one table: its columns, in order, with their dtypes.

Attributes:

Name Type Description
name str

The table's name, as in :data:TABLES.

columns tuple of Column

The columns with fixed names, in the order the table has them.

bin_columns tuple of Column

Columns whose names follow a rule, one :class:Column per rule. Only depth_summary has them: one column per depth bin on each side (see :func:depth_bins).

names property

names: tuple[str, ...]

The names of :attr:columns, in order.

required property

required: tuple[str, ...]

The names of the columns the table's validator requires, in order.

dtypes property

dtypes: dict[str, str | CategoricalDtype]

The dtype of each column every producer writes.

Optional columns are left out, so an empty frame built from this map has the columns every frame of the table has.

column

column(name: str) -> Column | None

Return the :class:Column for name, or None if it is not one.

A depth-bin name gives the bin rule's column under that name.

columns_of

columns_of(
    names: Iterable[str], kind: Kind
) -> tuple[str, ...]

Return those of names that the contract tags with kind, in order.

Parameters:

Name Type Description Default
names iterable of str

Column names, usually a frame's columns. A name the contract does not know is left out.

required
kind ('price', 'size')

Which columns to return.

"price"

Column dataclass

Column(
    name: str,
    dtype: str | CategoricalDtype,
    kind: Kind | None = None,
    presence: Presence = "required",
)

One column of a table contract.

Attributes:

Name Type Description
name str

The column name. In :attr:Table.bin_columns it is a pattern, with {N} where the distance goes.

dtype str or CategoricalDtype

The pandas dtype on a pipeline result. "object" means the column has no one type: the venue's own ids, for example, are ints on some venues and text on others.

kind {'price', 'size', 'turnover'} or None

"price" for a price, "size" for a size, "turnover" for a price times a size, None for any other column. A price on a pipeline result is a whole number of ticks and a size a whole number of lots when the dtype is an integer; a float price or size is already in the quote currency or the instrument's units, except where the table's documentation says otherwise.

presence {'required', 'standard', 'optional'}

"required": the table's validator refuses a frame without it. "standard": every producer writes it, but a frame without it is still accepted. "optional": only some sources or stages add it.

PRICE module-attribute

PRICE: Kind = 'price'

The :attr:Column.kind of a price column.

SIZE module-attribute

SIZE: Kind = 'size'

The :attr:Column.kind of a size column.

TURNOVER module-attribute

TURNOVER: Kind = 'turnover'

The :attr:Column.kind of a price times a size, such as the bars' turnover. On a pipeline result it is ticks times lots.

depth_bins

depth_bins(
    names: Iterable[str], side: str | None = None
) -> list[DepthBin]

Return the depth-bin columns among names, with their side and distance.

Parameters:

Name Type Description Default
names iterable of str

Column names, usually a depth_summary frame's columns.

required
side str

"bid" or "ask" to return one side only. None (the default) returns both.

None

Returns:

Type Description
list of DepthBin

The bid bins and then the ask bins, each from the touch outward. The order does not depend on the order of names, so a summary built with any depth_bps and depth_bins reads the same way.

DepthBin

Bases: NamedTuple

One depth-bin column of a depth_summary table.

Attributes:

Name Type Description
column str

The column name.

side str

"bid" or "ask".

bps int

How far the bin reaches from the best price on its side, in basis points. The bin holds the size between the bin before it and here.

depth_bin_name

depth_bin_name(side: str, bps: int | str) -> str

Return the name of the depth-bin column on side that reaches bps.

Parameters:

Name Type Description Default
side str

"bid" or "ask".

required
bps int or str

The bin's distance in basis points. A string is used as it is, so "{N}" gives the pattern the docs show and "025" a padded label.

required

Display units

display_result

display_result(
    result: DataFrame,
    *,
    table: str,
    config: PipelineConfig | None = None,
) -> pd.DataFrame
display_result(
    result: _ResultT,
    *,
    config: PipelineConfig | None = None,
) -> _ResultT
display_result(
    result: Any,
    *,
    table: str | None = None,
    config: PipelineConfig | None = None,
) -> Any

Return result with prices and sizes converted to display units.

Canonical prices are integer ticks and canonical sizes integer lots (:mod:ob_analytics.schemas). This converts each price column to the ticks * tick_size float in the quote currency, and each size column to the lots * lot_size float in the instrument's units. The table contracts in :data:~ob_analytics.schemas.TABLES say which columns are prices and which are sizes.

It takes three kinds of input:

  • A pipeline result. Each of its four tables is converted, with the steps and the display precision (price_decimals, volume_decimals) read from result.config. :meth:~ob_analytics.pipeline.PipelineResult.display does the same.
  • One table that has a contract, such as result.lifecycles(), result.queue() or result.bars(). Name its contract with table, for example table="lifecycles".
  • A :class:~ob_analytics.book.BookSnapshot, such as result.book(). Both sides are converted by the book contract.

For a table or a book, pass the run's config as config, for example display_result(result.bars(), table="bars", config=result.config). Without it, the steps are read from the frame's attrs (tick_size and lot_size) and nothing is rounded.

The gallery and :func:~ob_analytics.visualization.plot_result call it once, so every face works in display units. Call it yourself before the low-level prepare.* builders when you plot straight from a result, or to read a run's tables in the quote currency.

A frame holds its prices in ticks when one of its price columns is an integer column, and the same for sizes in lots. Then every price column is converted, including a float one such as the bars' vwap, which is a float number of ticks. The bars' turnover, a price times a size, is scaled by both steps, so turnover / volume is still the vwap.

A frame with no integer price column and no integer size column (a file written before prices and sizes were integers, a table already passed through here, or the transaction costs, which are always in display units) is returned unchanged. So converting twice changes nothing.

Parameters:

Name Type Description Default
result (PipelineResult, DataFrame or BookSnapshot)

A pipeline result (or any dataclass with a config and table fields named as in :data:~ob_analytics.schemas.TABLES), one table, or a book snapshot.

required
table str

The name of the table's contract in :data:~ob_analytics.schemas.TABLES. Required for a table; not taken for a result or a book.

None
config PipelineConfig

The run's config, for the steps and the display precision of a table or a book. A result uses its own.

None

Returns:

Type Description
(PipelineResult, DataFrame or BookSnapshot)

A new object of the same type, converted.

Raises:

Type Description
TypeError

If result is none of the three, or table is missing for a table or given for a result or a book.

UnknownNameError

If table names no contract.

ConfigError

If a table holds integer prices or sizes and neither config nor the frame's attrs gives the step.

Validators and dtypes

validate_events_df

validate_events_df(df: DataFrame) -> None

Raise :class:ConfigError unless df has all :data:EVENT_COLUMNS, each column named in :data:EVENT_DTYPES with its dtype.

validate_trades_df

validate_trades_df(df: DataFrame) -> None

Raise :class:ConfigError unless df has all :data:TRADE_COLUMNS, each column named in :data:TRADE_DTYPES with its dtype.

validate_depth_df

validate_depth_df(df: DataFrame) -> None

Raise :class:ConfigError unless df has all :data:DEPTH_COLUMNS.

EVENT_DTYPES module-attribute

EVENT_DTYPES: dict[str, str | CategoricalDtype] = dtypes

Dtype of each column of the events table: :data:EVENT_COLUMNS plus the provenance columns every loader carries. Prices are integer ticks and sizes integer lots.

TRADE_DTYPES module-attribute

TRADE_DTYPES: dict[str, str | CategoricalDtype] = dtypes

Dtype of each column of the trades table: :data:TRADE_COLUMNS plus the maker and taker provenance columns. direction is null on an L2 feed until trade signing fills it.

cast_events

cast_events(df: DataFrame) -> pd.DataFrame

Return the events frame df cast through :data:EVENT_DTYPES.

Every event loader builds its output through this. Text order ids (UUIDs, say) stay text, as object; any other id column is cast to int64.

MAYBE_BAD_BOOK_ATTR module-attribute

MAYBE_BAD_BOOK_ATTR: str = 'maybe_bad_book_records'

Events attrs key for the count of records the venue flagged as coming after a gap it could not repair, so the book may be wrong from there on.

Databento sets the flag F_MAYBE_BAD_BOOK on such records; :class:~ob_analytics.databento.DatabentoLoader puts the count here, and :func:~ob_analytics.quality.data_quality_summary reads it. A frame without the key comes from a source that does not flag such records, so the count was not checked.

SET_ASIDE_ORDERS_ATTR module-attribute

SET_ASIDE_ORDERS_ATTR: str = 'set_aside_orders'

Events attrs key for the count of orders the loader left out of the book because their price was off the tick grid.

A US equity may quote under $1.00 in steps of $0.0001, finer than a cent tick. :class:~ob_analytics.databento.DatabentoLoader sets aside an order that enters the book at such a price, puts the count here, and :func:~ob_analytics.quality.data_quality_summary reads it. A frame without the key comes from a source that does not set orders aside, or is a run saved by a version that did not record the count.

HIDDEN_ORDER_ID module-attribute

HIDDEN_ORDER_ID: int = 0

The id of an order with no public identity.

LOBSTER gives every execution against a hidden order this id. Hidden orders never join the visible queue, so the queue reconstructions leave them out.

Instrument columns

A frame that holds more than one instrument names each row's venue and symbol in two optional columns.

VENUE_COLUMN module-attribute

VENUE_COLUMN: str = 'venue'

Name of the optional per-row source-venue column.

SYMBOL_COLUMN module-attribute

SYMBOL_COLUMN: str = 'symbol'

Name of the optional per-row instrument-symbol column.

group_by_instrument

group_by_instrument(df: DataFrame) -> DataFrameGroupBy

Group df by whichever identity columns (venue, symbol) it has.

A convenience for splitting a combined, multi-venue frame back into its per-instrument pieces. dropna=False keeps rows whose identity is NA as their own group.

Raises:

Type Description
ConfigError

If df carries neither identity column — a single-instrument frame that was never tagged. Load it with a symbol/venue (for example RunContext(symbol=..., venue=...)) to tag identity first.