Skip to content

Data I/O

Parquet serialization and writer registry.

load_data

load_data(path: str | Path) -> dict[str, pd.DataFrame]

Load pre-processed pipeline data from a Parquet folder.

Parameters:

Name Type Description Default
path str or Path

A folder written by :func:save_data in its default Parquet format. Each .parquet file inside is loaded as a DataFrame keyed by its stem (events.parquet → "events").

required

Returns:

Type Description
dict of str to pandas.DataFrame

Raises:

Type Description
ConfigError

If path is not a folder, a file in it is not a Parquet file this build can read, or a Parquet file declares a schema version this build does not support. A file written with no version key (legacy data, or the bundled sample) loads with a warning — see :func:ob_analytics.schemas.check_schema_version.

FileNotFoundError

If the folder holds no Parquet file.

save_data

save_data(
    data: PipelineResult | dict[str, DataFrame],
    path: str | Path,
    *,
    fmt: str = "parquet",
    writer: DataWriter | None = None,
    config: Any = None,
    ctx: Any = None,
    extra_tables: Iterable[str] = (),
    **write_kwargs: Any,
) -> None

Save pipeline data to disk.

Parameters:

Name Type Description Default
data PipelineResult or dict of str to pandas.DataFrame

A pipeline result, or the DataFrames to save (keys become file stems). A result is saved as its four tables, with its own config unless config is given, and with its declarations and level. :func:load_result reads a Parquet folder back as the same result.

required
path str or Path

A folder for this package's own formats ("parquet", "depth_csv", "bitstamp", "lobster"), and a file for an export to another tool ("hftbacktest", "nautilus", "databento"). Each writer declares which it takes as its :attr:~ob_analytics.protocols.DataWriter.target. A folder is created when missing.

required
fmt str

The format, one of :func:list_writers. The default, "parquet", writes one file per key and tags each with :data:SCHEMA_VERSION in its metadata (checked by :func:load_data). A source name (e.g. "bitstamp", "lobster") round-trips through that source's own writer (its create_writer method, so no separate writer registration is needed); a source that needs run state — LOBSTER's trading_date — reads it from ctx. A generic, source-independent writer registered via :func:register_writer is also resolved by name, and wins over a source of the same name.

'parquet'
writer DataWriter

A pre-constructed writer instance. When provided, fmt is ignored and the writer is used directly.

None
config Any

Forwarded to a registered writer factory when fmt names one. The "parquet" writer records config in each file, so the files keep the run's tick size, lot size and display precision. ctx defaults to an empty :class:~ob_analytics.protocols.RunContext.

None
ctx Any

Forwarded to a registered writer factory when fmt names one. The "parquet" writer records config in each file, so the files keep the run's tick size, lot size and display precision. ctx defaults to an empty :class:~ob_analytics.protocols.RunContext.

None
extra_tables str or iterable of str

Per-order tables of a result to save beside its four tables: "lifecycles" (:meth:~ob_analytics.pipeline.PipelineResult.lifecycles) and "queue" (:meth:~ob_analytics.pipeline.PipelineResult.queue at the touch). The default saves neither. The "parquet" format writes them; other formats leave them out. :func:load_result reads them back, so the accessors of the loaded result do not build them again. When a result is saved to a folder, a per-order table left there by an earlier save and not saved this time is removed, so it cannot be read back with the wrong run.

()
**write_kwargs Any

Extra keyword arguments forwarded to writer.write().

{}

Raises:

Type Description
UnknownNameError

If fmt is not one of :func:list_writers.

ConfigError

If path is a file where the writer takes a folder, or a folder where it takes a file. The message says which the writer expected. Also if the writer declares no target, if extra_tables names a table other than "lifecycles" and "queue", or if it is given with tables that are not a result.

load_result

load_result(
    path: str | Path, *, source: Any = None
) -> PipelineResult

Load a saved run back into a :class:~ob_analytics.pipeline.PipelineResult.

The inverse of save_data(result, path): the four tables come back as they were saved, and so does the run's :class:~ob_analytics.config.PipelineConfig, which each Parquet file records. A result rebuilt this way shows the same prices and sizes as the run did, for example in :func:~ob_analytics.display.display_result or a gallery.

A folder that records only the tick and lot size (written by :meth:~ob_analytics.pipeline.Pipeline.run_windows, or by an older version) gets those two, with the display precision that shows one step of each. A folder with neither (prices and sizes stored as floats) gets a tick size of 1, so its prices read as they are.

The run's :class:~ob_analytics.protocols.Level comes back as each Parquet file records it. A folder written by an older version does not record it; its level comes from the tables instead: :attr:~ob_analytics.protocols.Level.L2 when the events table is empty, :attr:~ob_analytics.protocols.Level.L3 otherwise.

The loader's counts (such as :data:~ob_analytics.schemas.MAYBE_BAD_BOOK_ATTR) come back on the tables' attrs, so :meth:~ob_analytics.pipeline.PipelineResult.audit makes the same checks as on the run itself.

The per-order tables saved with save_data(..., extra_tables=...) come back too: :meth:~ob_analytics.pipeline.PipelineResult.lifecycles and :meth:~ob_analytics.pipeline.PipelineResult.queue (at the touch) return them without building them again.

The run's declarations (:attr:PipelineResult.declarations) come back too. A folder written by an older version does not record them; it gets those of the capture record ob-analytics process keeps beside the tables, over those of source (:func:~ob_analytics.capture_record.run_declarations).

Parameters:

Name Type Description Default
path str or Path

A Parquet folder written by :func:save_data or by ob-analytics process.

required
source Source

The source whose declarations to use when the folder records none. None leaves them undeclared. Recorded declarations always win, since they describe the data the run read.

None

Returns:

Type Description
PipelineResult

The saved run.

Raises:

Type Description
ConfigError

If path is not a folder (it does not exist, or it is a file), if the folder lacks one of the four tables, or if a Parquet file declares a schema version this build does not support.

FileNotFoundError

If the folder holds no Parquet file at all.

register_writer

register_writer(name: str, factory: WriterFactory) -> None

Register a writer factory under name for use with save_data(fmt=name, ctx=...).

The factory is called as factory(config, ctx) and must return a :class:DataWriter. This is what lets format-specific writers (e.g. :class:~ob_analytics.lobster.LobsterWriter, which needs trading_date) participate in the registry — they pull required parameters from the :class:~ob_analytics.protocols.RunContext.

list_writers

list_writers() -> list[str]

Return every format :func:save_data accepts, sorted.

The formats are the writers registered via :func:register_writer and the sources that write their own format (those with a create_writer method). This is the list save_data checks fmt against and names in its error.

load_writer_plugins

load_writer_plugins(*, force: bool = False) -> list[str]

Discover and register writers advertised via entry points.

Scans the :data:ENTRY_POINT_GROUP entry-point group; each entry's value is loaded to a writer factory (config, ctx) -> DataWriter and registered under the entry-point name, as :func:register_writer would. This is what lets a writer live in a separate installable package without editing ob-analytics.

The scan runs once per process unless force is set. A plug-in that fails to load is skipped with a warning, so one broken package cannot stop the rest from loading.

Returns:

Type Description
list of str

The names newly registered by this call.

Writing

OutputTables

OutputTables(
    tables: dict[str, DataFrame],
    *,
    tick_sizes: dict[str, float] | None = None,
    lot_sizes: dict[str, float] | None = None,
    config: PipelineConfig | None = None,
    declarations: FeedDeclarations | None = None,
    level: Level | None = None,
)

Bases: dict[str, DataFrame]

A run's output tables, as pandas, that a writer can also ask for in Arrow.

DataWriter.write takes a mapping of pandas frames, and this is that mapping — every existing writer treats it as the dict it is, and the protocol's annotation stays honest. What it adds is :meth:arrow, for a writer whose target is columnar: Parquet here, and the Nautilus catalogue.

Without it such a writer would call pa.Table.from_pandas itself and silently drop the schema version and tick size that make the output canonical, because the function that attaches them is private. The frame type therefore stays out of the protocol: a writer asks for the shape it wants rather than the pipeline guessing which one every writer needs.

Parameters:

Name Type Description Default
tables mapping of str to pandas.DataFrame

The run's tables, keyed by name.

required
tick_sizes dict of str to float

Tick sizes to record in :meth:arrow's metadata. None when the caller declared no config, which writes no tick metadata rather than a default one.

None
lot_sizes dict of str to float

Lot sizes to record, in the same way.

None
config PipelineConfig

The run's configuration, recorded whole so :func:load_result can rebuild the run.

None
declarations FeedDeclarations

The run's declarations, recorded so the rebuilt run is audited against them. None when the tables are not a run's.

None
level Level

The run's level, recorded so :func:load_result gives it back. None when the tables are not a run's.

None

arrow

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

Return the same tables as canonical Arrow, keyed the same way.

Each table carries the schema version and, when the run declared one, the tick size, the lot size, the configuration, the :attr:declarations, the :attr:level and the loader's counts — the same key-value metadata a canonical Parquet file carries, so a writer building one is no worse off than :class:ParquetWriter.

ParquetWriter

ParquetWriter(config: Any = None)

Write a run's frames as one canonical Parquet file per key.

The library's default output format, and a registered writer like any other rather than a branch inside :func:save_data, so a user can register their own under "parquet" and replace it. It writes a folder.

Satisfies the :class:~ob_analytics.protocols.DataWriter protocol.

write

write(
    data: dict[str, DataFrame],
    dest: str | Path,
    **kwargs: Any,
) -> Path

Write each frame in data to <dest>/<key>.parquet.

dest is a directory and is created when missing. Each file carries the schema version and, when the writer was given the run's config, the tick size, the lot size and the config itself, so :func:load_data can check the first and restore prices and sizes, and :func:load_result can rebuild the run. When data is a run's :class:OutputTables, its declarations and level are recorded too.