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 ¶
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
|
bid_volumes
property
¶
Every bid level's volume, in the order of :attr:bid_prices.
ask_volumes
property
¶
Every ask level's volume, in the order of :attr:ask_prices.
update ¶
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; |
required |
side
|
int
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
quoted_bids ¶
The quoted bid levels, ascending by price: prices and volumes.
quoted_asks ¶
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 |
required |
depth
|
DataFrame
|
The depth table of the same run, as
:func: |
required |
num_levels
|
int
|
How many levels of each side to return. |
required |
quoted
|
bool
|
With |
True
|
Returns:
| Type | Description |
|---|---|
BookLevels
|
One row per event: row |
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: |
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
|
Returns:
| Type | Description |
|---|---|
list of BookSnapshot
|
One per entry of times, in the same order. Each has the shape
:func: |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an instant and the depth timestamps disagree about being time-zone aware. |
DepthSummaryEngine ¶
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 ¶
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 |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Depth summary with |
update_side ¶
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 |
required |
summarize_depth ¶
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 ¶
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: |
required |
interval
|
str
|
A length of time such as |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ConfigError
|
If depth_summary has no |
price_level_volume ¶
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 |
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 |
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 |
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 |
filter_depth ¶
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 ¶
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
|
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A pandas DataFrame with the bid/ask spread data. |
quoted_spread ¶
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 |
required |
window
|
str or Timedelta
|
A fixed duration such as |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Rows are in time order. Without window: With window: |
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
|
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: |
required |
levels
|
int
|
Depth for the cumulative |
5
|
stoikov_adjustment
|
(Series, ndarray, float or None)
|
Forwarded to :func: |
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
|
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
|
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: |
Raises:
| Type | Description |
|---|---|
ConfigError
|
If a required column is missing, or stoikov_adjustment is given for
integer prices with no |
book_imbalance ¶
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: |
required |
levels
|
int
|
Depth over which to measure the imbalance. |
1
|
Returns:
| Type | Description |
|---|---|
Series
|
OBI per row, indexed like depth_summary. Rows whose total volume is
zero are |
Raises:
| Type | Description |
|---|---|
ConfigError
|
If levels is below |
readable_quotes ¶
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 |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The readable rows, in their original order. |