Skip to content

Depth

Order book depth: price-level volume tracking, the depth summary in basis-point bins, the signals read from it, spread extraction, and depth filtering.

PriceLevelBook is the book at L2: the size at each price level, kept one depth row at a time. DepthSummaryEngine builds the depth summary on it, and price_level_snapshots replays it to give the book at many instants, so a snapshot's touch always equals the depth summary's at that instant. book_levels replays it too, and gives the best few levels of each side after every event, as integer arrays.

PriceLevelBook

PriceLevelBook(price_dtype: type | dtype = np.int64)

The book at L2: the size resting at each price level, kept one row at a time.

Each side is a set of parallel numpy arrays, read ascending by price, so the best ask is the first entry of its side and the best bid the last. The rows are applied by a loop that numba compiles to machine code.

:meth:update applies one row of the depth table: a positive volume sets the size at that price, and zero removes the price level. Every level is kept until its own row removes it, as in the depth table, even when a quote on the other side crosses it.

The touch the book reports is uncrossed. :meth:quoted_bids and :meth:quoted_asks leave out the crossed levels at each side's best end, by the rule of :func:~ob_analytics.engine.crossed_prefix_counts, which order_book(..., uncross=True) also uses: while the best bid is at or above the best ask, the level updated less recently is left out. A level left out is not lost: once the quote that crossed it goes, the level is quoted again, even if it is stale, as the depth table still holds it.

Recency is the order the rows are applied in, one price level at a time. order_book applies the rule to orders by their receive timestamps, so the two can differ: at one instant the depth summary follows the row order, where order_book leaves out the bid; and a new order at a stale price makes the whole level recent here, while order_book still sees the stale order as old.

:class:~ob_analytics.depth.DepthSummaryEngine builds the depth summary on this class, so the quoted levels here are the depth summary's book after every row.

The arrays :attr:bid_prices, :attr:ask_prices and the other array properties return, and those the quoted_* methods return, are views of the book's own storage, so a later :meth:update can change them. Copy one to keep it.

Parameters:

Name Type Description Default
price_dtype numpy dtype

The dtype prices are held in: int64 ticks (the default), or float64 for a depth table already converted to the quote currency.

int64

bid_prices property

bid_prices: ndarray

Every bid level's price, ascending.

bid_volumes property

bid_volumes: ndarray

Every bid level's volume, in the order of :attr:bid_prices.

ask_prices property

ask_prices: ndarray

Every ask level's price, ascending.

ask_volumes property

ask_volumes: ndarray

Every ask level's volume, in the order of :attr:ask_prices.

crossed_bids property

crossed_bids: int

How many of the highest bids the quoted book leaves out.

crossed_asks property

crossed_asks: int

How many of the lowest asks the quoted book leaves out.

update

update(price: float, volume: float, side: int) -> bool

Apply one depth row and return whether the other side's quote changed.

Parameters:

Name Type Description Default
price int or float

The price level, in the book's price units.

required
volume float

The size now resting at price; 0 removes the level.

required
side int

0 for a bid, 1 for an ask (the codes of :class:ob_analytics.engine.Direction).

required

Returns:

Type Description
bool

True when the row changed which levels of the other side are quoted, so that side's quoted book changed too.

quoted_bids

quoted_bids() -> tuple[np.ndarray, np.ndarray]

The quoted bid levels, ascending by price: prices and volumes.

quoted_asks

quoted_asks() -> tuple[np.ndarray, np.ndarray]

The quoted ask levels, ascending by price: prices and volumes.

BookLevels

Bases: NamedTuple

The best price levels of each side of a book, one row per book state.

Each array is (rows, levels): column 0 is the touch, and each side runs best first (asks from the lowest price, bids from the highest). Prices are integer ticks and volumes integer lots. A price level the side does not have holds price 0 and volume 0, so an empty one has volume 0.

book_levels

book_levels(
    events: DataFrame,
    depth: DataFrame,
    *,
    num_levels: int,
    quoted: bool = True,
) -> BookLevels

Return the best num_levels levels of each side after each event.

The depth rows are replayed through a :class:PriceLevelBook, each with the event it names, the events in the order of events. The depth table's own order is kept within one event.

Parameters:

Name Type Description Default
events DataFrame

The run's events, with an event_id column. Their order sets the order of the result's rows.

required
depth DataFrame

The depth table of the same run, as :func:price_level_volume returns it. Each row names its event in event_id.

required
num_levels int

How many levels of each side to return.

required
quoted bool

With True, each side holds its quoted levels, which leave out the crossed levels at the touch, as the depth summary does. With False, each side holds every level the depth table leaves resting, crossed or not.

True

Returns:

Type Description
BookLevels

One row per event: row i is the book after events.iloc[i]. A side with fewer than num_levels levels fills the rest with price 0 and volume 0.

Raises:

Type Description
ConfigError

If a column is missing, if num_levels is below 1, if the depth table is in display units (float prices, or sizes that are not whole lots), or if it names an event that events does not have.

price_level_snapshots

price_level_snapshots(
    depth: DataFrame,
    *,
    times: Iterable[datetime | Timestamp],
    max_levels: int | None = None,
) -> list[BookSnapshot]

Return the book at L2 at each of times, replayed from the depth table.

One pass over depth drives a :class:PriceLevelBook, the book :class:DepthSummaryEngine builds the depth summary on, and copies it out at each instant. So the touch of each snapshot equals the depth summary's last row at or before that instant: each snapshot holds the quoted levels, which leave out a level crossed by a more recently updated quote on the other side, as the depth summary does. This is the L2 counterpart of :func:ob_analytics.book.order_book, which rebuilds the per-order book at one instant from the events.

Parameters:

Name Type Description Default
depth DataFrame

The depth table: timestamp, price, volume and direction. Prices are integer ticks, or floats in the quote currency when the table was converted for display; both are kept as given.

required
times iterable of datetime.datetime or pandas.Timestamp

The instants to take a snapshot at, in any order. A row counts at an instant when its timestamp is at or before it.

required
max_levels int

Keep only this many price levels per side, nearest the touch first. None keeps every level.

None

Returns:

Type Description
list of BookSnapshot

One per entry of times, in the same order. Each has the shape :func:~ob_analytics.book.order_book returns, with one row per price level: bids best first and asks best last, each with price, volume and liquidity (cumulative volume from the touch).

Raises:

Type Description
TypeError

If an instant and the depth timestamps disagree about being time-zone aware.

DepthSummaryEngine

DepthSummaryEngine(config: PipelineConfig | None = None)

Build the depth summary one depth row at a time.

:meth:compute processes a whole depth frame. It applies the rows to a :class:PriceLevelBook and writes one summary row after each into a pre-allocated numpy matrix, in one loop that numba compiles to machine code. The matrix becomes a DataFrame once, at the end. :meth:update_side applies a single row the same way.

The first call in a new Python process compiles the loop, or loads it from numba's cache on disk when an earlier process has compiled it.

Parameters:

Name Type Description Default
config PipelineConfig

Pipeline configuration.

None

compute

compute(depth: DataFrame) -> pd.DataFrame

Process an entire depth DataFrame and return the depth summary.

This is the main entry point; :func:summarize_depth calls it.

Parameters:

Name Type Description Default
depth DataFrame

Price-level volume data with columns timestamp, price, volume, direction.

required

Returns:

Type Description
DataFrame

Depth summary with timestamp, best_bid_price, best_bid_vol, best_ask_price, best_ask_vol, and volume-in-BPS-bin columns (e.g. bid_vol25bps).

update_side

update_side(
    price: int, volume: float, side: int, out: ndarray
) -> None

Process one depth event and write a metrics row into out.

Parameters:

Name Type Description Default
price int

Price as an integer tick count.

required
volume float

Volume at this price level (0 means deletion).

required
side int

0 = bid, 1 = ask.

required
out ndarray

Pre-allocated 1-D array of length row_len to fill.

required

summarize_depth

summarize_depth(
    depth: DataFrame,
    *,
    depth_bps: int = 25,
    depth_bins: int = 20,
) -> pd.DataFrame

Build the depth summary from a depth table.

This is a convenience wrapper around :class:DepthSummaryEngine.

Parameters:

Name Type Description Default
depth DataFrame

DataFrame containing depth data.

required
depth_bps int

Width of each depth bin, in basis points. Default is 25.

25
depth_bins int

Number of depth bins. Default is 20.

20

Returns:

Type Description
DataFrame

The depth summary: one row per depth event.

depth_bands

depth_bands(
    depth_summary: DataFrame, *, interval: str | None = None
) -> pd.DataFrame

Return the resting volume in each distance band over time.

The bands are the depth summary's basis-point bins: bid_vol<N>bps is the bid volume in one ring of prices, out to N bps from the best bid, and ask_vol<N>bps the same for the asks. Each ring holds only its own volume, so add the bands of a side to get its depth out to the farthest one.

Parameters:

Name Type Description Default
depth_summary DataFrame

Depth summary produced by :func:summarize_depth, with timestamp and the bid_vol<N>bps / ask_vol<N>bps columns.

required
interval str

A length of time such as "1s" or "1min". When given, each band is averaged over each interval, and the row is stamped at the end of its interval. When None (the default), there is one row per timestamp of the summary: the last one when several rows share a timestamp, which is the book after all of them.

None

Returns:

Type Description
DataFrame

timestamp, then the bid bands and the ask bands, each from the touch outward. The volumes are in the instrument's units, whether the summary holds integer lots (with lot_size on the frame's attrs, as on a pipeline result) or display sizes.

Raises:

Type Description
ConfigError

If depth_summary has no bid_vol<N>bps column, the bid and ask bands differ, or the volumes are integers and the frame carries no lot_size.

price_level_volume

price_level_volume(
    events: DataFrame, *, warn_overdrawn: bool = True
) -> pd.DataFrame

Calculate the cumulative volume for each price level over time.

Parameters:

Name Type Description Default
events DataFrame

A pandas DataFrame containing limit order events. Sizes are the pipeline's integer lots, or floats such as the base-asset sizes of a table converted for display. Float sizes on a decimal grid are summed exactly on that grid, so a level that empties reads exactly 0 in either case. Float sizes on no such grid are summed as floats, with a warning.

required
warn_overdrawn bool

Whether to warn when the events take a level's size below zero (see Warns). A caller that reports overdrawn levels in its own way, or that expects them, passes False. The level is held at zero either way.

True

Returns:

Type Description
DataFrame

A pandas DataFrame with the cumulative volume for each price level: one row per change to a level, holding the level's volume after the event named by event_id. Rows are in the canonical event order (:func:~ob_analytics.schemas.time_order_keys), and the sequence and ingest_seq columns are carried over from events when it has them, so the depth rows sort the same way the events do. The volume is in the units and dtype family of events["volume"].

Warns:

Type Description
UserWarning

When the events would take a level's size below zero. That means they take more size off the level than they put on it, which a loader that follows the schema's volume and fill rule never does. The warning names the level and the first event that overdrew it. The level's running total is held at zero, so it never reads a negative size, and the next order on it starts from zero. audit counts these rows as negative_level. Pass warn_overdrawn=False to leave this warning out.

filter_depth

filter_depth(
    depth: DataFrame,
    *,
    start_time: Timestamp,
    end_time: Timestamp,
) -> pd.DataFrame

Filter depth data within a specified time range.

Parameters:

Name Type Description Default
depth DataFrame

DataFrame containing depth data.

required
start_time Timestamp

Start of the time range.

required
end_time Timestamp

End of the time range.

required

Returns:

Type Description
DataFrame

Filtered depth data within the specified time range.

get_spread

get_spread(quotes: DataFrame) -> pd.DataFrame

Extract the bid/ask spread from the quotes.

This function returns the best bid and ask quotes, one row each time they change; :func:quoted_spread returns the width of the spread.

Parameters:

Name Type Description Default
quotes DataFrame

The best bid and ask over time, such as the run's depth summary, with timestamp, best_bid_price, best_bid_vol, best_ask_price and best_ask_vol.

required

Returns:

Type Description
DataFrame

A pandas DataFrame with the bid/ask spread data.

quoted_spread

quoted_spread(
    quotes: DataFrame,
    *,
    window: str | Timedelta | None = None,
) -> pd.DataFrame

Measure the quoted spread, best ask minus best bid, through time.

:func:get_spread returns the best bid and ask quotes as they change; this function returns the width of the spread itself, in the quote currency and in basis points of the mid-price.

Only quotes that can be read as a price count (:func:readable_quotes): a side with nothing resting on it or a crossed book has no spread, so the last readable spread holds until the next one.

Parameters:

Name Type Description Default
quotes DataFrame

A depth summary, or any frame with timestamp, best_bid_price and best_ask_price. Prices may be integer ticks, with tick_size on the frame's attrs (as on a pipeline result), or display prices.

required
window str or Timedelta

A fixed duration such as "1min". None (the default) returns one row per readable quote. With a window, the result has one row per window from the first quote to the last, and each spread is weighted by how long it held. A window with no quote of its own holds the spread that stood when it began. Windows count from the Unix epoch.

None

Returns:

Type Description
DataFrame

Rows are in time order. Without window: timestamp, spread (in the quote currency, whether the frame holds integer ticks or display prices) and spread_bps (the spread in basis points of the mid-price).

With window: timestamp (the start of the window), spread and spread_bps (each the mean over the window, weighted by time), and spread_min and spread_max (the smallest and largest spread in the window, in the quote currency).

Raises:

Type Description
ConfigError

If required columns are missing, window is not a fixed duration, or the prices are integer ticks and the frame carries no tick_size.

book_signals

book_signals(
    depth_summary: DataFrame,
    *,
    levels: int = 5,
    stoikov_adjustment: Series
    | ndarray
    | float
    | None = None,
) -> pd.DataFrame

Append fair-value and pressure signal columns to a depth summary.

Returns a copy of depth_summary with four columns added; existing columns are left untouched, so current consumers keep working.

mid_price Plain mid (best_bid_price + best_ask_price) / 2. micro_price Size-weighted mid from :func:micro_price. obi Touch order-book imbalance -- :func:book_imbalance with levels=1. obi_depth Cumulative-depth order-book imbalance over levels -- :func:book_imbalance with levels=levels.

A row whose quote cannot be read as a price (:func:readable_quotes: an empty side or a crossed book) has no mid of either kind: both are NaN. Its imbalance columns are kept, since all the volume resting on one side is a true imbalance.

Parameters:

Name Type Description Default
depth_summary DataFrame

Depth summary produced by :func:summarize_depth.

required
levels int

Depth for the cumulative obi_depth column. Default 5 (the touch plus the first four bps depth bins). Clamped to the number of depth bins actually present, so a summary with fewer bins does not raise.

5
stoikov_adjustment (Series, ndarray, float or None)

Forwarded to :func:micro_price.

None

Returns:

Type Description
DataFrame

A copy of depth_summary with the signal columns appended.

micro_price

micro_price(
    quotes: DataFrame,
    *,
    stoikov_adjustment: Series
    | ndarray
    | float
    | None = None,
) -> pd.Series

Size-weighted mid price (the micro-price) at the touch.

The micro-price weights each best quote by the size resting on the opposite side::

micro = (best_bid_price * best_ask_vol + best_ask_price * best_bid_vol)
        / (best_bid_vol + best_ask_vol)

so it leans toward the side carrying the heavier opposite book -- the direction price is more likely to move. It is equivalent to the plain mid plus a spread-scaled touch imbalance::

micro = mid + (spread / 2) * (best_bid_vol - best_ask_vol)
                             / (best_bid_vol + best_ask_vol)

Stoikov (2018), "The micro-price: A high frequency estimator of future prices", refines this by replacing the linear imbalance term with a correction g(imbalance, spread) fitted from data. Fitting that correction is outside this function: pass a fitted per-row correction as stoikov_adjustment to add it to the weighted mid and obtain the refined estimator. The default (None) returns the plain weighted mid, which is the zeroth-order Stoikov estimator.

Parameters:

Name Type Description Default
quotes DataFrame

The best bid and ask over time, such as the run's depth summary, with best_bid_price, best_bid_vol, best_ask_price and best_ask_vol columns.

required
stoikov_adjustment (Series, ndarray, float or None)

Optional additive Stoikov correction (see above), in the quote currency, whether the prices are integer ticks (with quotes.attrs["tick_size"], as on a pipeline result) or display floats. Default None.

None

Returns:

Type Description
Series

The micro-price per row, indexed like quotes, in the units of its prices. A row whose quote cannot be read as a price (:func:readable_quotes: an empty side or a crossed book) is NaN, and so is a row with no size at the touch.

Raises:

Type Description
ConfigError

If a required column is missing, or stoikov_adjustment is given for integer prices with no tick_size on the frame's attrs.

book_imbalance

book_imbalance(
    depth_summary: DataFrame, *, levels: int = 1
) -> pd.Series

Order-book imbalance (OBI) from resting volume.

OBI is the signed share of resting volume on the bid side::

obi = (bid_vol - ask_vol) / (bid_vol + ask_vol)

ranging from -1 (all volume on the ask) to +1 (all on the bid); 0 is a balanced book.

Parameters:

Name Type Description Default
depth_summary DataFrame

Depth summary produced by :func:summarize_depth.

required
levels int

Depth over which to measure the imbalance. 1 (default) uses the touch only -- best_bid_vol and best_ask_vol. levels > 1 cumulates resting volume over the first levels - 1 bps depth bins (the {side}_vol{N}bps columns, which already include the touch), so the measured window grows monotonically with levels.

1

Returns:

Type Description
Series

OBI per row, indexed like depth_summary. Rows whose total volume is zero are NaN rather than a divide-by-zero error.

Raises:

Type Description
ConfigError

If levels is below 1 or exceeds the available depth bins.

readable_quotes

readable_quotes(quotes: DataFrame) -> pd.DataFrame

Return the rows of quotes whose book can be read as a price.

This is the package's one test of a usable quote. The measurements that read a quote apply it: the mid a trade arrived into (:func:~ob_analytics.trade_sign.mid_before, and so Lee-Ready and the effective spread), the mid at an instant (:func:~ob_analytics.trade_sign.prevailing_mid), the spread a hidden trade printed inside (:func:~ob_analytics.hidden_liquidity.hidden_trades), the book columns of the feature table (:func:~ob_analytics.features.features), the micro-price (:func:micro_price) and the mids of :func:book_signals, the mids the trade tape, the price view, the book signals and the depth heatmap draw, the mid line of the book ladder and the price range of the book replay, and the empty sides of the Level 1 quote table (:class:~ob_analytics.metrics.L1TickerMetric).

Two states get through a depth summary that are not books anything could have traded against, and both would otherwise reach a reader as ordinary numbers:

A side with nothing resting on it. The depth engine writes a price and a volume of 0 for an empty side, which is a marker and not a price. Taken at face value it makes a spread the width of the whole instrument, a mid at half the other side, and a micro-price of zero: three finite numbers, none of them true, and none of them marked.

A crossed book, where the best bid is above the best ask. A diff feed can hold genuinely crossed resting orders, so this is an expected state on such a feed rather than a fault, but its midpoint is not a price and its spread is negative. A locked book, bid equal to ask, is a real state at a spread of zero and is kept.

A reader that drops these rows reaches back to the last quote that could be read, the way it reaches back over any other instant with no quote of its own. The test reads the first bid/ask pair the frame carries: best_bid_price / best_ask_price, best_bid / best_ask, or bid / ask. A frame with none of them cannot be tested and is returned unchanged.

Parameters:

Name Type Description Default
quotes DataFrame

Book snapshots: a pipeline depth_summary, or any frame shaped like one.

required

Returns:

Type Description
DataFrame

The readable rows, in their original order.