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 ( |
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 |
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 |
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
¶
Create a pipeline from a registered source name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Registered source name (case-insensitive), e.g. |
required |
ctx
|
RunContext
|
Per-run parameters (e.g. |
None
|
**kwargs
|
Any
|
Passed to the :class: |
{}
|
Raises:
| Type | Description |
|---|---|
UnknownNameError
|
If no source is registered under name; the message names the registered names closest to it. |
run ¶
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: |
None
|
Returns:
| Type | Description |
|---|---|
PipelineResult
|
Frozen dataclass with |
Steps (L3 / per-order feeds)
- Load events (
EventLoader.load) - Build trades (
TradeReader.load) - Classify order types
- Compute price-level depth
- Compute depth metrics, and sign the trades the venue left unlabelled
- 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: |
required |
boundaries
|
time or iterable of times
|
Where to cut, anything :class: |
required |
output
|
str or Path
|
The folder to write |
required |
carry
|
bool
|
Start each window from the previous window's book. Default
|
True
|
ctx
|
RunContext
|
The context for this run, as for :meth: |
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: |
config |
PipelineConfig
|
The configuration used for the run. |
level |
Level
|
The order-book resolution the run was produced at
(:attr: |
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: |
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 ¶
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
|
|
to_arrow ¶
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
|
|
Examples:
to_polars ¶
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: |
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 ¶
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: |
None
|
Returns:
| Type | Description |
|---|---|
DataQualitySummary
|
|
metric ¶
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. |
required |
**settings
|
Any
|
Keyword arguments for the metric's
:meth: |
{}
|
Returns:
| Type | Description |
|---|---|
pandas.DataFrame or result object
|
What the metric's
:meth: |
Raises:
| Type | Description |
|---|---|
UnknownNameError
|
If no metric is registered under name; the message names the registered names closest to it. |
metrics ¶
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: |
lifecycles ¶
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: |
Raises:
| Type | Description |
|---|---|
ConfigError
|
On a run with no per-order events (an
:attr: |
queue ¶
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"
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per order event, with the columns
:func: |
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
|
max_levels
|
int | None
|
As :func: |
None
|
bps_range
|
int | None
|
As :func: |
None
|
uncross
|
int | None
|
As :func: |
None
|
Returns:
| Type | Description |
|---|---|
BookSnapshot
|
|
Raises:
| Type | Description |
|---|---|
ConfigError
|
On a run with no per-order events, or events without the order
|
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: |
'time'
|
threshold
|
str
|
As :func: |
'time'
|
target_bars
|
str
|
As :func: |
'time'
|
sign_method
|
str
|
As :func: |
'time'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per bar, with the columns
:data: |
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: |
'time'
|
threshold
|
str
|
As :func: |
'time'
|
target_bars
|
str
|
As :func: |
'time'
|
include
|
str
|
As :func: |
'time'
|
sign_method
|
str
|
As :func: |
'time'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per bar, with the columns
:func: |
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 ¶
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. |