Skip to content

Pipeline

The main orchestrator. Runs the full sequence: load → build trades → classify → depth. Use Pipeline(source=...) for LOBSTER or other registered sources, or pass individual components (loader=, trade_reader=) to override specific stages. Flow-toxicity metrics are computed after the run by calling vpin / kyle_lambda / trade_imbalance on result.trades.

The source registry (register_source / list_sources / get_source) lives in ob_analytics.sources.

Pipeline

Pipeline(
    config: PipelineConfig | None = None,
    *,
    source: Source | None = None,
    loader: EventLoader | None = None,
    trade_reader: TradeReader | None = None,
    ctx: RunContext | None = None,
)

Configurable, composable order book analytics pipeline.

Each processing stage is handled by a pluggable component that satisfies the corresponding protocol. Pass your own implementations to override any stage.

Parameters:

Name Type Description Default
config PipelineConfig

Central configuration. The fields it sets are laid over the source's instrument grid (source.grid), and the result is what each run's loader and trade reader are built from.

None
source OfflineSource

A source descriptor that builds each run's loader and trade reader, and gives the instrument grid the config starts from (its grid). Defaults to :class:~ob_analytics.bitstamp.BitstampSource. Explicit component arguments take precedence over the source's factories.

None
loader EventLoader

Loads raw events from a data source. Overrides the source's loader, and is used for every run.

None
trade_reader TradeReader

Builds the trades DataFrame. Overrides the source's trade reader, and is used for every run.

None
ctx RunContext

The per-run parameters (such as LOBSTER's trading_date) every run uses unless :meth:run is given its own.

None
Notes

A live capture records the instrument's tick size and lot size in its meta.json (see :mod:ob_analytics.capture_record). :meth:run and :meth:run_windows use them for that capture when config does not set them, so a capture replays on its own price and size grid, as ob-analytics process reads it. A tick size you set (or a price_decimals) keeps the recorded tick size out, and a lot size (or a volume_decimals) the recorded lot size. When you pass your own loader or trade_reader, the record is not used: those components hold their own config.

from_source classmethod

from_source(
    name: str,
    *,
    ctx: RunContext | None = None,
    **kwargs: Any,
) -> Pipeline

Create a pipeline from a registered source name.

Parameters:

Name Type Description Default
name str

Registered source name (case-insensitive), e.g. "bitstamp" or "lobster".

required
ctx RunContext

Per-run parameters (e.g. trading_date) forwarded to OfflineSource.create_* factories.

None
**kwargs Any

Passed to the :class:~ob_analytics.protocols.Source constructor.

{}

Raises:

Type Description
UnknownNameError

If no source is registered under name; the message names the registered names closest to it.

run

run(
    path: Any, *, ctx: RunContext | None = None
) -> PipelineResult

Execute the full pipeline on path and return results.

Parameters:

Name Type Description Default
path Any

What the loader reads, typically a file or directory path.

required
ctx RunContext

Override the pipeline's default :class:RunContext for this single call. When None, the ctx provided at construction (or the default empty context) is used.

None

Returns:

Type Description
PipelineResult

Frozen dataclass with events, trades, depth, depth_summary, config, level and declarations.

Steps (L3 / per-order feeds)
  1. Load events (EventLoader.load)
  2. Build trades (TradeReader.load)
  3. Classify order types
  4. Compute price-level depth
  5. Compute depth metrics, and sign the trades the venue left unlabelled
  6. Compute order aggressiveness

Steps 3 to 6 are STAGES in this module. For an :attr:~ob_analytics.protocols.Level.L2 source the loader yields the depth frame directly, depth metrics and trade signs are computed on it, and the per-order stages (3, 6) are skipped.

run_windows

run_windows(
    path: Any,
    boundaries: Iterable[Any],
    output: str | Path,
    *,
    carry: bool = True,
    ctx: RunContext | None = None,
) -> Path

Run the pipeline one time window at a time and write the result.

Cuts path at each of the boundaries, runs the depth stages on one window at a time, and writes each window's rows to output as soon as the window is done. The depth stages are what makes a run large, so their peak memory is set by the largest window rather than by the whole input. The output is one Parquet file per table, the same folder a single run saved with :func:~ob_analytics.data.save_data gives, and :func:~ob_analytics.data.load_data reads it back.

With carry on, each window starts from the book the previous window ended with, so the cuts do not show in the output: every table matches a single run row for row, though events comes out in window order. With carry off, each window starts from an empty book, as if it were a separate input: the orders resting at a cut are missing from the next window's depth.

Parameters:

Name Type Description Default
path Any

What the loader reads, typically a file or directory path, as for :meth:run.

required
boundaries time or iterable of times

Where to cut, anything :class:pandas.Timestamp accepts; one time on its own is one cut. A time with no zone is read as UTC. n cuts make n + 1 windows that cover the whole input: a window holds the rows at or after its start and before its end.

required
output str or Path

The folder to write events, trades, depth and depth_summary to, created when missing. Files already there under those names are replaced, but only once every window is done: a run that fails part-way leaves the folder as it was. The run works in a .run_windows-* folder inside it and deletes that folder when it ends. A run stopped hard cannot, so each run first deletes any such folder an earlier run left. Do not give two runs at the same time the same output.

required
carry bool

Start each window from the previous window's book. Default True.

True
ctx RunContext

The context for this run, as for :meth:run.

None

Returns:

Type Description
Path

The output folder.

Raises:

Type Description
ConfigError

If no boundary is given, if the boundaries do not strictly increase, or if no window produced rows for one of the tables.

Notes

A loader that can read one window at a time does so when the source built both the loader and the trade reader. The loaders of the Databento, Bitstamp and L2 CSV sources can; so can every capture that replays through the Bitstamp or the L2 CSV source. The run then never holds more than one window's events or depth rows.

For per-order events the run goes over the windows twice. The first time it reads each window and saves its events, and the few values per order that the order types are read from, to a working folder inside output. The trade reader then builds the trades from what the loader kept: the Databento loader keeps the trade records, and the Bitstamp loader matches the trades to their orders as it reads. Order types and trade signs are decided over the whole run, as in a single run: the order types one group of orders at a time, from the saved values. The second time, the run reads each saved window back and runs the depth stages on it. While it does, it holds only the time of each trade; the trades wait in the working folder until the last window is done. carry does not change how such a loader reads: an order's size and price always carry from one window to the next, as they do when the input is read whole.

A loader that reads a CSV file (Bitstamp, L2) first sorts its rows on disk, in the working folder, so the file need not be in time order. The Bitstamp loader sorts them by order, puts each order's rows in order, and then sorts them by window. The Databento loader reads the file in order, so its records must be in receive-time order.

Any other loader, and a loader the caller passes, reads the whole input, and the events table (or, for a price-level source, the depth rows) is held for the whole run.

A source's own depth is not used. LOBSTER's order book file states the book after each message of the whole session, so it cannot be cut; a windowed LOBSTER run rebuilds its depth from the messages instead.

PipelineResult dataclass

PipelineResult(
    events: DataFrame,
    trades: DataFrame,
    depth: DataFrame,
    depth_summary: DataFrame,
    config: PipelineConfig,
    level: Level = Level.L3,
    declarations: FeedDeclarations = FeedDeclarations(),
)

Immutable container for the core outputs of a pipeline run.

Analytic outputs (VPIN, trade imbalance, Kyle's λ) are intentionally not stored here — compute them post-pipeline from trades and append them to the gallery model's analytics (build cards with the *_card helpers).

Attributes:

Name Type Description
events, trades, depth, depth_summary DataFrame

Core pipeline tables. For an :attr:~ob_analytics.protocols.Level.L2 run events is empty (a schema-valid zero-row frame): a price-level feed has no per-order identity, so the per-order stages do not run — read depth / depth_summary / trades instead.

config PipelineConfig

The configuration used for the run.

level Level

The order-book resolution the run was produced at (:attr:~ob_analytics.protocols.Level.L3 by default, :attr:~ob_analytics.protocols.Level.L2 for price-level feeds). Downstream code (the gallery, data-quality) reads it to decide which per-order faces / metrics apply.

declarations FeedDeclarations

What the run's data is declared to show: its source's declarations, with what a live capture recorded in their place (see :func:~ob_analytics.capture_record.run_declarations). :meth:audit holds the run to them. The defaults declare nothing.

Notes

The tables built from the run after it ends are kept on the result: :meth:lifecycles, :meth:queue, :meth:book, :meth:bars and :meth:features build their table on the first call, and a later call with the same settings returns the same table. The display-unit tables and the gallery's view of the run, which :meth:plot and the gallery build, are kept the same way. So the kept tables are shared: copy one before you change it. A result made with :func:dataclasses.replace starts with nothing kept.

tables

tables() -> dict[str, pd.DataFrame]

Return the run's four core tables keyed by name.

This is what :func:~ob_analytics.data.save_data saves for a result, and what :meth:to_arrow converts.

Returns:

Type Description
dict of str to pandas.DataFrame

events, trades, depth and depth_summary. The keys are the same for every run: on an :attr:~ob_analytics.protocols.Level.L2 run events is a schema-valid zero-row frame rather than a missing key.

to_arrow

to_arrow() -> dict[str, pa.Table]

Return the run's four core tables as Arrow tables.

Each table carries the same key-value metadata a canonical Parquet file carries — the schema version, the run's tick and lot size, its config, its declarations and the loader's counts (see :mod:ob_analytics.schemas) — so a reader handed these tables in memory is no worse off than one reading the files.

Returns:

Type Description
dict of str to pyarrow.Table

events, trades, depth and depth_summary.

Examples:

>>> from ob_analytics import Pipeline, sample_csv_path
>>> tables = Pipeline().run(sample_csv_path()).to_arrow()
>>> sorted(tables)
['depth', 'depth_summary', 'events', 'trades']

to_polars

to_polars() -> dict[str, Any]

Return the run's four core tables as Polars DataFrames.

Polars is not a dependency of ob-analytics (see adr/0002-dataframe-library.md): the public API takes and returns pandas, and this accessor is a convenience for users who already have Polars installed. Install it yourself with pip install polars.

Returns:

Type Description
dict of str to polars.DataFrame

The same keys as :meth:to_arrow.

Raises:

Type Description
ImportError

When polars is not installed.

Notes

Polars keeps no schema-level key-value metadata, so the schema version and tick size that :meth:to_arrow attaches do not survive this conversion. Read the tick size from result.config.tick_size, or use :meth:to_arrow when the metadata has to travel with the tables.

audit

audit(
    *, venue_book: BookLevels | None = None
) -> DataQualitySummary

Check this run's data quality against its :attr:declarations.

The same checks as ob-analytics audit: this calls :func:~ob_analytics.quality.data_quality_summary with the run's tables, its faithful depth, its tick size and its declarations.

Parameters:

Name Type Description Default
venue_book BookLevels

The venue's own book after every message, when the source supplies one (LOBSTER's orderbook file, read by :meth:~ob_analytics.lobster.LobsterSource.venue_book). The book rebuilt from the events is then compared with it.

None

Returns:

Type Description
DataQualitySummary

metric

metric(
    name: Literal["vpin"], **settings: Any
) -> VpinResult
metric(
    name: Literal["kyle_lambda"], **settings: Any
) -> KyleLambdaResult
metric(name: str, **settings: Any) -> Any
metric(name: str, **settings: Any) -> Any

Compute the registered metric name over this result.

Metrics are computed on demand, not stored: a run pays for a metric only when it is asked for, and a third-party metric that raises cannot break :meth:Pipeline.run.

Parameters:

Name Type Description Default
name str

Registered metric name (case-insensitive), e.g. "amihud". See :func:~ob_analytics.metrics.list_metrics.

required
**settings Any

Keyword arguments for the metric's :meth:~ob_analytics.protocols.Metric.compute, e.g. result.metric("vpin", n_buckets=20). Leave them out to use the metric's defaults.

{}

Returns:

Type Description
pandas.DataFrame or result object

What the metric's :meth:~ob_analytics.protocols.Metric.compute returns, which is what the function it wraps returns: a table, or the function's result object when the function has side results. So result.metric("vpin") returns a :class:~ob_analytics.flow_toxicity.VpinResult and result.metric("kyle_lambda") a :class:~ob_analytics.flow_toxicity.KyleLambdaResult, as :func:~ob_analytics.flow_toxicity.vpin and :func:~ob_analytics.flow_toxicity.kyle_lambda do.

Raises:

Type Description
UnknownNameError

If no metric is registered under name; the message names the registered names closest to it.

metrics

metrics() -> dict[str, Any]

Compute every registered metric that applies to this run.

A metric declares the tables it needs (:attr:~ob_analytics.protocols.Metric.needs), so a metric that reads per-order events is skipped on an L2 run, and a trade metric on a run with no trades, rather than failing on an empty table.

Returns:

Type Description
dict of str to pandas.DataFrame or result object

Metric name → what :meth:metric returns for it, for the metrics that apply to this run (see :meth:~ob_analytics.protocols.Needs.unmet).

lifecycles

lifecycles() -> pd.DataFrame

Return one row per order, from placement to outcome.

The table :func:~ob_analytics.book.order_lifecycles builds from :attr:events. It is built on the first call and kept.

Returns:

Type Description
DataFrame

One row per order id, with the columns :func:~ob_analytics.book.order_lifecycles describes.

Raises:

Type Description
ConfigError

On a run with no per-order events (an :attr:~ob_analytics.protocols.Level.L2 run).

queue

queue(*, levels: str = 'touch') -> pd.DataFrame

Return each visible limit order's place in its price level's queue.

The table :func:~ob_analytics.queue.queue_positions builds from :attr:events. It is built on the first call for each levels and kept.

Parameters:

Name Type Description Default
levels ('touch', 'all')

"touch" (the default) keeps the rows where the order rests at the best bid or ask. "all" keeps every visible level.

"touch"

Returns:

Type Description
DataFrame

One row per order event, with the columns :func:~ob_analytics.queue.queue_positions describes.

Raises:

Type Description
ConfigError

On a run with no per-order events, or for an unknown levels.

book

book(
    *,
    at: datetime | Timestamp | None = None,
    max_levels: int | None = None,
    bps_range: int = 0,
    uncross: bool = False,
) -> BookSnapshot

Return the order book at at, rebuilt from :attr:events.

The snapshot :func:~ob_analytics.book.order_book returns for the same arguments. One snapshot is kept for each set of arguments, so a second call for the same instant costs nothing. A call for a new instant rebuilds the book.

Parameters:

Name Type Description Default
at datetime or Timestamp

The instant to show. None (the default) shows the book after the last event.

None
max_levels int | None

As :func:~ob_analytics.book.order_book takes them.

None
bps_range int | None

As :func:~ob_analytics.book.order_book takes them.

None
uncross int | None

As :func:~ob_analytics.book.order_book takes them.

None

Returns:

Type Description
BookSnapshot

Raises:

Type Description
ConfigError

On a run with no per-order events, or events without the order type column.

bars

bars(
    *,
    rule: str = "time",
    threshold: Any = None,
    target_bars: int = 50,
    sign_method: str | None = None,
) -> pd.DataFrame

Return :attr:trades resampled into bars.

The table :func:~ob_analytics.bars.bars builds from :attr:trades, with :attr:depth_summary as the quotes the Lee-Ready classifier reads. It is built on the first call for each set of arguments and kept.

Parameters:

Name Type Description Default
rule str

As :func:~ob_analytics.bars.bars takes them.

'time'
threshold str

As :func:~ob_analytics.bars.bars takes them.

'time'
target_bars str

As :func:~ob_analytics.bars.bars takes them.

'time'
sign_method str

As :func:~ob_analytics.bars.bars takes them.

'time'

Returns:

Type Description
DataFrame

One row per bar, with the columns :data:~ob_analytics.bars.BAR_COLUMNS.

features

features(
    *,
    rule: str = "time",
    threshold: Any = None,
    target_bars: int = 50,
    include: Sequence[str] | None = None,
    sign_method: str | None = None,
) -> pd.DataFrame

Return the feature table of this run: one row per bar.

The table :func:~ob_analytics.features.features builds from :attr:trades, with :attr:depth_summary as the book. It is built on the first call for each set of arguments and kept.

Parameters:

Name Type Description Default
rule str

As :func:~ob_analytics.features.features takes them.

'time'
threshold str

As :func:~ob_analytics.features.features takes them.

'time'
target_bars str

As :func:~ob_analytics.features.features takes them.

'time'
include str

As :func:~ob_analytics.features.features takes them.

'time'
sign_method str

As :func:~ob_analytics.features.features takes them.

'time'

Returns:

Type Description
DataFrame

One row per bar, with the columns :func:~ob_analytics.features.features describes.

plot

plot(
    concept: str,
    level: Level | str | None = _UNSET,
    *,
    backend: str = "matplotlib",
    ax: Axes | None = None,
    theme: PlotTheme | None = None,
    **overrides: Any,
) -> Any

Render one plot concept from this result in a single call.

The method form of :func:ob_analytics.visualization.plot_result, which takes the same arguments, e.g. result.plot("depth_heatmap", col_bias=0.1). Pass level when this result has the concept at both L2 and L3. See :func:~ob_analytics.visualization.available_concepts for what a given result can plot (it varies by format).

concept and level may be given by position because together they name the picture to draw, as a registry key does. They are not settings of the picture; every setting (backend, ax, theme and the overrides) is keyword-only.

display

display() -> PipelineResult

Return this result with prices and sizes in display units.

The method form of :func:~ob_analytics.display.display_result: each price in the four tables becomes a float in the quote currency and each size a float in the instrument's own units. The converted result is built on the first call and kept, and the gallery and :meth:plot share it.

The tables the accessors build (:meth:lifecycles, :meth:queue, :meth:book, :meth:bars) are not part of it. Convert one with :func:~ob_analytics.display.display_result, for example display_result(result.bars(), table="bars", config=result.config).

Returns:

Type Description
PipelineResult

A new result of the same type, with each table converted.