Data quality¶
Checks on a run's frames: venue sequence gaps, orders left resting after the
venue dropped them, and the summary that gathers every check. See
Data quality: matched book, diff feed and price levels
for the concepts and the audit how-to for the CLI.
Summary¶
data_quality_summary ¶
data_quality_summary(
events: DataFrame,
trades: DataFrame,
*,
feed_type: FeedType = FeedType.UNKNOWN,
depth: DataFrame | None = None,
tick_size: float = 1.0,
sequence_kind: SequenceKind = SequenceKind.CONTIGUOUS,
sequence_restarts: int = 0,
trade_attribution: TradeAttribution = TradeAttribution.BOTH,
clocks: Clocks = Clocks.BOTH,
trade_order: TradeOrder = TradeOrder.RECEIVE,
venue_book: BookLevels | None = None,
tick_size_stated: bool | None = None,
) -> DataQualitySummary
Summarise the data quality of one reconstructed session.
Surfaces the health signals that matter before trusting a feed — most
importantly how crossed the resting book is, which distinguishes a matched
book from a diff feed (see :class:~ob_analytics.protocols.FeedType).
A source whose feed flags records that come after a gap it could not
repair (Databento) puts their count on events.attrs under
:data:~ob_analytics.schemas.MAYBE_BAD_BOOK_ATTR; the summary reports
it as maybe_bad_book_records. A source that sets aside orders off
the tick grid (Databento, under $1.00) puts their count under
:data:~ob_analytics.schemas.SET_ASIDE_ORDERS_ATTR; the summary reports
it as set_aside_orders.
For a pipeline run, call
:meth:~ob_analytics.pipeline.PipelineResult.audit instead: it passes
the run's tables, tick size and declarations
(:class:~ob_analytics.protocols.FeedDeclarations) for you. Pass the
declarations here yourself only for tables that are not a run's.
Like :func:detect_stale_orders, this takes either the pipeline's own
tables or the tables :func:~ob_analytics.display.display_result
converts for display, and measures the same crossing and the same stale
orders on both.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
DataFrame
|
Classified events (must carry the canonical columns and the
|
required |
trades
|
DataFrame
|
The trades frame, with |
required |
feed_type
|
FeedType
|
The source's declared feed type, recorded on the summary and used to
interpret |
UNKNOWN
|
depth
|
DataFrame
|
A faithful price-level-volume frame (e.g. |
None
|
tick_size
|
float
|
Quote-currency size of one price tick ( |
1.0
|
sequence_kind
|
SequenceKind
|
What the venue |
CONTIGUOUS
|
sequence_restarts
|
int
|
How many of the sequence's steps back the source counted as the count
starting again at a new opening book. That many are left out of
|
0
|
trade_attribution
|
TradeAttribution
|
Which orders of a trade the feed can name, so the unmatched-trades
check looks only for those. Read it off the source with
:func: |
BOTH
|
clocks
|
Clocks
|
Which clocks the data carries, so the clock checks run only when there
are two to compare. With two, the checks still leave out rows from a
capture's opening book ( |
BOTH
|
trade_order
|
TradeOrder
|
Which clock puts trades in order with the order events for the
stale-order check (see :func: |
RECEIVE
|
venue_book
|
BookLevels
|
The venue's own book after every message, when the source supplies
one: for LOBSTER, the orderbook file read by
:func: |
None
|
tick_size_stated
|
bool or None
|
Whether the venue stated the tick size, as a live capture records it
(read it with :func: |
None
|
Returns:
| Type | Description |
|---|---|
DataQualitySummary
|
|
Raises:
| Type | Description |
|---|---|
ConfigError
|
If a venue_book is passed with events that lack
|
DataQualitySummary
dataclass
¶
DataQualitySummary(
feed_type: FeedType,
n_events: int,
n_orders: int,
n_trades: int,
crossed_pct: float,
crossed_episodes: int,
unmatched_trades_pct: float,
duplicate_event_ids: int,
duplicate_created_ids: int,
pre_existing_orders: int,
events_with_sequence: int = 0,
sequence_gaps: int = 0,
sequence_out_of_order: int = 0,
sequence_restarts: int = 0,
sequence_kind: SequenceKind = SequenceKind.CONTIGUOUS,
orphan_orders: int = 0,
orphan_events: int = 0,
nonpositive_price_rows: int = 0,
negative_volume_rows: int = 0,
negative_level_rows: int = 0,
exchange_time_after_receive: int = 0,
exchange_time_reordered: int = 0,
clocks: Clocks = Clocks.BOTH,
stale_orders: DataFrame = _empty_stale_orders(),
trade_attribution: TradeAttribution = TradeAttribution.BOTH,
trades_matched_by_order: int = 0,
per_order_crossed_pct: float = 0.0,
per_order_crossed_episodes: int = 0,
venue_book_price_levels: int = 0,
venue_book_rows: int = 0,
venue_book_differing_rows: int = 0,
venue_book_first_difference: BookDifference
| None = None,
maybe_bad_book_records: int | None = None,
set_aside_orders: int | None = None,
tick_size_stated: bool | None = None,
)
Per-run data-quality metrics for a reconstructed session.
Built by :func:data_quality_summary. All percentages are 0–100 floats.
The fields are the measurements; :attr:checks turns them into pass/fail
verdicts with a :class:Severity each, and :attr:ok is the one-line
answer to "is this feed trustworthy?" that ob-analytics audit exits on.
Attributes:
| Name | Type | Description |
|---|---|---|
feed_type |
FeedType
|
The source's declared crossing invariant (see
:class: |
n_events, n_orders, n_trades |
int
|
Row / distinct-order / trade counts. |
crossed_pct |
float
|
Percentage of session time the faithful book is crossed
( |
crossed_episodes |
int
|
Number of distinct crossed intervals. |
per_order_crossed_pct |
float
|
Percentage of session time the book rebuilt from the per-order
events is crossed. It differs from |
per_order_crossed_episodes |
int
|
Number of distinct intervals the per-order book is crossed. |
venue_book_price_levels |
int
|
How many price levels per side the venue's own book states (the
|
venue_book_rows |
int
|
Book states compared: one per event, each after its own message. |
venue_book_differing_rows |
int
|
Of those, the states where the book rebuilt from the per-order events
differs from the venue's in any price or size of the best
|
venue_book_first_difference |
BookDifference or None
|
Where the first of those states differs, or |
unmatched_trades_pct |
float
|
Percentage of trades with an order the feed can name left unresolved:
a missing |
duplicate_event_ids |
int
|
Count of |
duplicate_created_ids |
int
|
Count of order ids with more than one |
pre_existing_orders |
int
|
Distinct orders resting before the capture window (classifier label
|
events_with_sequence |
int
|
Rows carrying a non-null venue |
sequence_gaps |
int
|
Dropped-message count: skipped venue sequence numbers. Always |
sequence_out_of_order |
int
|
Reordered or duplicated messages: sequence steps that did not advance,
leaving out |
sequence_restarts |
int
|
Steps back where the source started again from a new opening book
and the venue's count started again with it. The source reports them
( |
sequence_kind |
SequenceKind
|
What the venue sequence promises, and so whether |
orphan_orders |
int
|
Distinct order ids with a |
orphan_events |
int
|
Rows belonging to those orphan orders. |
nonpositive_price_rows |
int
|
Rows priced at or below zero. Legal in the schema (prices are signed integer ticks) but not a tradeable level. |
negative_volume_rows |
int
|
Rows with a negative |
negative_level_rows |
int
|
Depth rows where the events would take a price level below zero: they
took more size off the level than they put on it. The depth table
holds such a level at zero, so it reads less than the orders the
events show resting there. Counted from the events. Always |
exchange_time_after_receive |
int
|
Rows whose venue clock ( |
exchange_time_reordered |
int
|
Steps where the venue clock goes backwards while the receive clock
moves forward: messages that reached the capture out of order.
Always |
clocks |
Clocks
|
Which clocks the data carries (see
:class: |
stale_orders |
DataFrame
|
Resting orders a trade printed through that the venue did not report
again within :data: |
trade_attribution |
TradeAttribution
|
Which orders of a trade the feed can name (see
:class: |
trades_matched_by_order |
int
|
Trades whose taker is an order created with size 0. Bitstamp creates
an instant order bought by quote amount that way and never reports
what it executed, so a trade with no row of its size is matched to
the order by its id (see
:class: |
maybe_bad_book_records |
int or None
|
Records the venue flagged as coming after a gap in its feed that it
could not repair, so the book may be wrong from the first of them on
(Databento's |
set_aside_orders |
int or None
|
Orders the loader left out of the book because they entered it at a
price off the tick grid (a US equity under $1.00 quoting in steps of
$0.0001). |
tick_size_stated |
bool or None
|
Whether the venue stated the tick size a live capture recorded
( |
venue_book_differing_pct
property
¶
Percentage of the compared book states that differ from the venue's.
checks
property
¶
Every check this run was scored against, errors first.
The crossing check reads its severity off :attr:feed_type: a crossed
resting book is a defect in a matched book or a price-level book and a
faithful property of a diff feed, so the same number means opposite
things and only the declared feed type can tell them apart.
errors
property
¶
Failed checks whose severity is :attr:Severity.ERROR.
warnings
property
¶
Failed checks whose severity is :attr:Severity.WARNING.
QualityCheck
dataclass
¶
One named data-quality check and how it read on this run.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Stable identifier, matching the summary field it reads
(e.g. |
passed |
bool
|
Whether the data satisfied the check. |
severity |
Severity
|
What a failure means (see :class: |
detail |
str
|
One line saying what was found and how to read it. |
skipped |
bool
|
Whether the check did not run, because the data cannot answer it.
A skipped check is :attr: |
Severity ¶
Bases: str, Enum
How much a failed data-quality check matters.
A check carries its severity so the policy — what fails a run — lives with
the measurement rather than in each caller. The enum mixes in str
(Severity.ERROR == "error"), which keeps CLI and JSON output plain.
Attributes:
| Name | Type | Description |
|---|---|---|
ERROR |
The data contradicts something that must hold (a duplicate
|
|
WARNING |
A signal worth reading before trusting the feed, but one a sound
capture can legitimately show (orders resting before the capture
began, zero-priced levels, messages reordered in transit). Fails the
run only under |
|
INFO |
Reported for context; never fails a run. |
BookDifference
dataclass
¶
BookDifference(
message_row: int,
direction: str,
price_level: int,
price: float | None,
volume: int,
venue_price: float | None,
venue_volume: int,
)
The first place the book rebuilt from the events differs from the venue's.
Attributes:
| Name | Type | Description |
|---|---|---|
message_row |
int
|
The |
direction |
str
|
|
price_level |
int
|
The price level, counted from the touch (1 is the best price). |
price, venue_price |
float or None
|
The price of that level in the rebuilt book and in the venue's, in
the quote currency ( |
volume, venue_volume |
int
|
The size at that level in the rebuilt book and in the venue's, in
integer lots; |
Crossed book¶
book_crossing ¶
How long the book in a price-level-volume frame is crossed.
The book is crossed when the best bid is above the best ask. The data quality summary uses this for its crossed-book checks, and a loader can use it to check the book it rebuilt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
DataFrame
|
Resting volume per price level over time, as
:func: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
best |
DataFrame or None
|
Columns |
crossed_pct |
float
|
The percentage of the time, from 0 to 100, that the book is crossed. |
crossed_episodes |
int
|
The number of separate intervals in which the book is crossed. |
CROSSED_TOLERANCE_PCT
module-attribute
¶
The share of session time, in percent, that a book may be crossed and still pass.
A matched book or a price-level book that is crossed for this share of the
time or less is treated as uncrossed: the crossings are ties at the touch, not
a defect. The crossed-book checks of :func:data_quality_summary and the
LOBSTER loader's warning compare the crossed_pct of
:func:book_crossing with it.
Sequence gaps¶
detect_sequence_gaps ¶
detect_sequence_gaps(
frame: DataFrame,
*,
sequence_column: str = SEQUENCE_COLUMN,
order_column: str = INGEST_SEQ_COLUMN,
group_columns: Sequence[str] = _SEQUENCE_GROUP_COLUMNS,
sequence_kind: SequenceKind = SequenceKind.CONTIGUOUS,
) -> pd.DataFrame
Find missing or out-of-order venue sequence numbers in frame.
A feed numbers each message on a channel with a sequence that should rise by exactly one; a skip is a dropped message and a step that does not rise is a reordered (or repeated) one. Rows are read in ingest order and grouped per channel, so interleaved channels are scored independently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Events or depth rows. A missing sequence_column (a source with no venue sequence) gives an empty result: the column is optional. |
required |
sequence_column
|
str
|
Column holding the venue's per-event sequence (nullable integer). |
SEQUENCE_COLUMN
|
order_column
|
str
|
Column defining ingest order; when absent, the frame's current row order is used instead. |
INGEST_SEQ_COLUMN
|
group_columns
|
sequence of str
|
Columns that identify one channel (instrument / venue). Only those present in frame are used; with none present the whole frame is one channel. Sequences from different channels are not comparable, so each group is scored on its own. |
_SEQUENCE_GROUP_COLUMNS
|
sequence_kind
|
SequenceKind
|
What the sequence promises. With
:attr: |
CONTIGUOUS
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per break, in ingest order within each channel, so an empty frame means a clean sequence. The columns are the group_columns present in frame, then:
|
Notes
Consecutive equal sequence values are collapsed before comparison, so a single venue update that emits several rows (e.g. every changed level of one book diff) counts once. A non-consecutive repeat still shows as out-of-order.
Stale orders¶
detect_stale_orders ¶
detect_stale_orders(
events: DataFrame,
trades: DataFrame,
*,
grace: Timedelta = STALE_GRACE,
depth: DataFrame | None = None,
tick_size: float = 1.0,
trade_order: TradeOrder = TradeOrder.RECEIVE,
) -> pd.DataFrame
Find resting orders a trade printed through that the venue left in place.
A trade above a resting ask, or below a resting bid, shows that the order had already left the book: a matching engine fills the better price first. The venue normally reports the order within milliseconds. An order it does not report again within grace stays in the rebuilt book although it is no longer at the venue, and distorts the spread, the depth and the queue from then on.
This only reports. It does not change what
:func:~ob_analytics.book.order_book returns: the test needs to know what
the feed said after the trade, which a live capture cannot know in time.
The tables can be the pipeline's own (prices in integer ticks, sizes in
integer lots; pass tick_size) or the tables
:func:~ob_analytics.display.display_result converts for display
(prices in the quote currency, sizes in the base asset; leave
tick_size at 1.0). Both give the same orders and the same times.
The test puts trades and order events in order by timestamp, the
receive time. That is right when both come in one stream. When the
trades come on another connection and can arrive late, pass
trade_order=TradeOrder.VENUE to order them by exchange_timestamp
instead (see :class:~ob_analytics.protocols.TradeOrder).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
DataFrame
|
Order events with |
required |
trades
|
DataFrame
|
Trades with |
required |
grace
|
Timedelta
|
How long after the trade the venue may take to report the order.
Defaults to :data: |
STALE_GRACE
|
depth
|
DataFrame
|
The faithful price-level-volume frame, used to measure how long each
stale order held the touch. Computed from events with
:func: |
None
|
tick_size
|
float
|
Quote-currency size of one price tick, so the reported prices read in
the quote currency. Leave at |
1.0
|
trade_order
|
TradeOrder
|
Which clock puts trades in order with the order events.
:attr: |
RECEIVE
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per stale order, worst first: the longest time at the touch, then the longest time stale. Empty, with its columns, when the venue reported every order in time. The columns are:
|
Raises:
| Type | Description |
|---|---|
ConfigError
|
If a required column is missing, or events has no rows: an L2 run
has no per-order events, and an empty answer would read as "no stale
orders". On the venue clock, both frames need
|