Skip to content

Visualization

To plot straight from a pipeline result, the one-liner plot_result (or result.plot) names a concept and wires up the prepare function and context for you; available_concepts(result) lists what a given result can render:

from ob_analytics import Pipeline, sample_csv_path
from ob_analytics.visualization import plot_result

result = Pipeline().run(sample_csv_path())

fig = plot_result(result, "depth_heatmap")          # drawn at L2 only
fig = result.plot("trade_tape", "L3", backend="plotly")

For full control, the unified plot() dispatcher renders a concept at a resolution level on a chosen backend from already-prepared data. Prepare the payload with the function of the same name in the public prepare namespace and spread it as keyword arguments. Each prepare function takes level= by the same rule as plot(), below:

from ob_analytics.visualization import plot, prepare

fig = plot("trade_tape", level="L2", **prepare.trade_tape(result.trades, level="L2"))

backend="matplotlib" (default) returns a Matplotlib figure; backend="plotly" returns an interactive Plotly figure (requires pip install ob-analytics[interactive]); backend="bokeh" returns a Bokeh figure (requires pip install ob-analytics[bokeh]) for nine concepts: trade_tape, depth_heatmap, book_snapshot, depth_chart, order_outcome, trade_size, volume_profile, cumulative_signed_volume and spread. A Bokeh figure is drawn once and does not update as new data arrives. Renderers never call plt.show().

Every concept declares a resolution level — Level.L2 (Market-By-Price aggregate) or Level.L3 (Market-By-Order, per order). A concept registered at a single level resolves it automatically, so you pass only the concept name; comparable concepts (both L2 and L3 registered) take an explicit level=. The prepare functions follow the same rule: prepare.depth_heatmap(...) needs no level, and prepare.trade_tape(...) needs level="L2" or level="L3", with the arguments of that face.

Concepts with both L2 and L3 faces: trade_tape, order_activity, book_snapshot, depth_chart, book_replay, liquidity_at_touch. L2-only: depth_heatmap, depth_bands, events_histogram, price_view, spread, trade_size, volume_profile, cumulative_signed_volume. L3-only: cancellations, order_outcome, queue_position, hidden_executions. Level-less: time_series, which only plot draws, and the analytics vpin, trade_imbalance, kyle_lambda, trade_imbalance_by_window, l1_ticker, book_signals, transaction_costs, amihud, roll_spread, bars, trading_halts. All but the last two are also registered metrics, so result.plot("vpin") computes and draws them.

The level says what data a face needs. An L2 face needs only aggregated data: the depth table, the depth summary and the trades. So every L2 face draws on an L2 run, and on an L3 run it shows the aggregated view of the same book. An L3 face needs per-order events, and some L3 faces also need the order types or a column that only one source fills. For example, hidden_executions needs LOBSTER's raw_event_type. available_concepts(result) checks these needs against the result. In the gallery, the card of a face that the run cannot draw says what the face needs.

Book replay

book_replay steps through the book over part of a run. The ladder shows the book at one instant per interval. Beside it, the trades panel shows every trade of the replay and the mid, with a line at the time on screen. Drag the slider, or press a play button: Play 1× is real time, and each speed in speeds gets a button. A speed is smooth only when a frame lasts about 50 ms or less, so at 1 s per frame, Play 20× glides and the slower speeds step. For smoother slow playback, pass a shorter interval. The file grows with the number of frames, which max_frames caps at 600. When interval would need more frames, the replay uses a longer interval and logs a warning.

result.plot() and the gallery replay the gallery's zoom window: the busiest stretch of trading (busiest_window), half as long as a run shorter than two hours, or a quarter as long as a longer run. They set interval to 1 s, or longer so that the window fits in about 300 frames. On the sample data the window is about 15 minutes, so each frame is about 3 s and every speed steps. To choose the window and the interval yourself, pass start_time, end_time and interval:

import pandas as pd

start = result.trades["timestamp"].iloc[100]
fig = result.plot(
    "book_replay", "L2", backend="plotly",
    start_time=start, end_time=start + pd.Timedelta("5min"), interval="1s",
)

Click a trade to move the replay to the last frame at or before it. The price level the trade took is marked in the trade's colour: the ask for a buy, the bid for a sell.

The L2 face replays the depth table, so its touch equals the depth summary's at every frame. The L3 face rebuilds the per-order book from the events at each frame, with stale crossed orders removed (uncross=True, the default here) so that both faces show the same market. Pass uncross=False for the faithful L3 book. Every frame keeps one price range: the mid's path, wide enough for about price_levels price levels per side. A crossed frame has no mid, so it adds its best bid and best ask to the path instead.

from ob_analytics.visualization import plot_result

fig = plot_result(result, "book_replay", "L3", backend="plotly")
fig.write_html("replay.html")

The replay is drawn by Plotly only, and the concept table says so: asking another backend for it raises a KeyError that names Plotly. The clicking needs a script, which Plotly cannot store inside a figure, so the replay is a BookReplayFigure: a Plotly figure that adds the script whenever it becomes HTML (write_html, to_html, show, and display in a notebook). In a notebook it displays as HTML, so the notebook must be trusted for the clicking to work.

book_replay

book_replay(
    depth: DataFrame | None = None,
    trades: DataFrame | None = None,
    events: DataFrame | None = None,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    interval: str | timedelta = "1s",
    max_frames: int = 600,
    price_levels: int = 20,
    speeds: tuple[float, ...] = (1, 5, 20),
    uncross: bool = True,
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare the book at one instant per interval, for a replay.

Each frame is a :func:prepare_book_snapshot_data payload, so a replay frame draws exactly as a book_snapshot does at that instant.

level="L2" replays depth with :func:~ob_analytics.depth.price_level_snapshots: one bar per price level, and a touch equal to the depth summary's at every frame. level="L3" rebuilds the book from events at each frame with :func:~ob_analytics.book.order_book: one segment per order. The L3 rebuild reads the whole event table once per frame, so it is the slower of the two.

Both faces show the book with stale crossed orders removed. The L2 face gets this from the depth table, replayed as the depth summary replays it: of two crossed price levels, the one updated less recently is left out. The L3 face gets it from uncross=True, the default here, which applies the same rule order by order. The two faces then show the same market, and the trades sit around the mid on both. Pass uncross=False to replay the faithful L3 book instead; on a diff feed with stale orders, its touch can sit far from the trades.

Every frame keeps the same price range: the path of the mid, widened so a typical frame shows about price_levels price levels per side. A crossed frame has no mid; it adds its best bid and best ask to the path instead, so a faithful replay still shows the orders that cross. Each frame holds every price level inside that range, so a bar leaves the plot only when its price level leaves the book or the range.

Parameters:

Name Type Description Default
depth DataFrame

The depth table. Required at L2.

None
trades DataFrame

The trades table; the replay shows every trade between the first and last frame. None shows none.

None
events DataFrame

The events table, classified (it needs the type column). Required at L3.

None
start_time Timestamp

The first and last frame. Default to the first and last timestamp of the table the face replays.

None
end_time Timestamp

The first and last frame. Default to the first and last timestamp of the table the face replays.

None
interval str or timedelta

The time between frames, as a pandas offset string or a duration.

'1s'
max_frames int

The most frames to build, at least 1. Each frame is a book snapshot held in the payload and in the figure, so this caps their size. When interval would need more, the interval is widened to fit, and a warning says so.

600
price_levels int

About how many price levels per side a typical frame shows; it sets the width of the price range.

20
speeds tuple of float

The playback speeds offered, as multiples of real time; each gets a play button. A frame is shown for interval divided by the speed, so a speed is smooth only when that is short (about 50 ms or less) and steps visibly otherwise. The fastest speeds run a little slower than stated, by the time the browser takes to draw each frame.

(1, 5, 20)
uncross bool

L3 only: evict crossed resting orders before the price range is chosen, as order_book(uncross=True) does. True by default, to match the L2 face; the L2 face is uncrossed by the depth table and ignores it.

True
level Level or str

"L2" for the L2 face, "L3" for the L3 face. Required.

_UNSET

Returns:

Type Description
dict

snapshots (one book-snapshot payload per frame, in time order), price_range (the (low, high) price range every frame shares, or None when no frame has both sides), interval (the time between frames, as a :class:pandas.Timedelta), speeds, trades (timestamp, price, volume and direction, from the first frame to the last), per_order (True at L3), bar_thickness (one bar thickness for every frame, the smallest of the frames' :func:book_bar_thickness), size_max (the longest bar of any frame, so every frame shares one size axis) and view_range (price_range widened by a bar thickness each side, so the bars at its edges are drawn whole; None with it).

Raises:

Type Description
ConfigError

If level is left out or is not L2 or L3, the table the face replays is missing or empty, interval is not positive, max_frames or price_levels is less than 1, speeds is empty or holds a speed that is not positive, or end_time is before start_time.

Dispatcher

plot

plot(
    concept: str,
    level: Level | str | None = _UNSET,
    *,
    backend: str = "matplotlib",
    ax: Axes | None = None,
    **data: Any,
) -> Any

Render concept at level on backend from already-prepared data.

Prepare data with the function of the same name in :mod:ob_analytics.visualization.prepare and spread it as keyword arguments::

from ob_analytics.visualization import plot, prepare
fig = plot("trade_tape", "L2", backend="matplotlib",
           **prepare.trade_tape(trades, level="L2"))

Parameters:

Name Type Description Default
concept str

Plot concept, e.g. "trade_tape" or "order_activity".

required
level Level or str or None

Resolution level (Level.L2/"L2" or Level.L3/"L3"). Leave it out when backend draws the concept at one level; it is required when backend draws the concept at both L2 and L3.

_UNSET
backend str

Registered backend name (default "matplotlib").

'matplotlib'
ax Axes

Axes to draw on (Matplotlib only; another backend refuses it). The figure that holds ax is yours: the face draws on ax and leaves the figure's layout alone, so call fig.tight_layout() (or use a layout engine) once all the panels are drawn. Without ax, the face creates its own figure and lays it out.

None
**data Any

Prepared plot data, as returned by the matching prepare function. May include theme=PlotTheme(...) to override :data:DEFAULT_THEME for this call, on any backend.

{}

Returns:

Type Description
Figure or Figure or figure

Raises:

Type Description
UnknownNameError

If backend is not registered, or does not draw concept (at level). The message names the backends that do.

ConfigError

If level was left out and backend draws concept at both L2 and L3, or ax is given for a backend other than Matplotlib.

Prepare functions

One function per concept, in the prepare namespace. Each turns a result's tables into the keyword arguments plot() takes for that concept. prepare.book_replay is under Book replay.

amihud

amihud(
    amihud_df: DataFrame,
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare an :func:~ob_analytics.cost.amihud table for its face.

The face draws one point per window, joined by a line, or the one value as a number when there is a single window. The payload is the shared window-measure shape: times, values, title, ylabel, notice, a note for the title (the number of windows, and how many have no value), and headline, the single value as text (empty when there are several windows).

bars

bars(
    bars: DataFrame,
    label: str = "",
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare data for a candlestick chart with a signed-volume strip.

bars is a table from :func:ob_analytics.bars.bars. label names the rule and threshold it was cut with; the default reads them off the frame.

The x axis follows the rule. Time bars occupy equal spans of time, so they are drawn on a real time axis, each centred in its own span: a stretch with no trading shows as the gap it was. Bars cut by trading activity (tick, volume, dollar, imbalance) occupy wildly unequal spans — a burst can close several inside a second — so a time axis would pile them on top of one another. They are drawn one to a slot instead, evenly spaced, with their closing times as the tick labels. That even spacing is the point of an activity bar: it is what puts the same amount of market in each one.

The payload says which axis it built in x_axis ("time" or "ordinal"); x and bar_width are in that axis's own units, and ticks carries the (positions, labels) an ordinal axis needs. volume_top is the top of the volume axis.

book_signals

book_signals(
    depth_summary: DataFrame,
    *,
    levels: int = 5,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    level: Level | str | None = _UNSET,
    time_bins: int | None = SERIES_BINS,
) -> dict[str, Any]

Predictive touch signals: micro-price vs mid, plus order-book imbalance.

Reads the touch (best bid/ask price and size) and the bps depth-bin volume columns from depth_summary and derives, per timestamp, the plain mid, the size-weighted micro-price (:func:~ob_analytics.depth.micro_price), the touch OBI and the cumulative-depth OBI over levels (:func:~ob_analytics.depth.book_imbalance). levels is clamped to the depth bins actually present so a summary with fewer bins does not raise. A quote that cannot be read as a price (:func:~ob_analytics.depth.readable_quotes) has no mid of either kind, no spread, and no part in the price range.

A long series is thinned to time_bins time steps by :func:thin_positions; None keeps every row. The payload's thinned says how many rows were kept.

book_snapshot

book_snapshot(
    order_book: BookSnapshot,
    show_quantiles: bool = False,
    top_n: int | None = 40,
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare an order-book snapshot at one resolution.

Feeds both the book_snapshot ladder and the depth_chart curve (see :func:prepare_depth_chart_data). level is required: level="L2" collapses each price level to one row (Market-By-Price); level="L3" keeps every order as its own row with within-level stacking bounds (Market-By-Order).

top_n windows each side to its N nearest price levels (None = whole book); the default keeps the touch region where bars stay tall enough that per-order separators read. show_quantiles overlays up to three heavy-level guide lines per side and is off by default.

The book is drawn as it is given. For the L2 face, a book from :func:~ob_analytics.depth.price_level_snapshots reads the depth table and is never crossed. For the L3 face, a per-order book from :func:~ob_analytics.book.order_book can be crossed; to draw a clean best_bid < best_ask ladder from it, pass the book order_book(..., uncross=True) returns.

Returns bids/asks frames ordered best-first with columns price, volume, liquidity, seg_lo, seg_hi (sizes in the instrument's units), the same rows in rising price order as bid_curve/ask_curve for the depth curve, the mid (see :func:book_mid), the ladder's bar_thickness (see :func:book_bar_thickness), high-volume *_quantiles price marks, timestamp, and the per_order flag (True at L3).

cancellations

cancellations(
    *args: Any,
    level: Level | str | None = _UNSET,
    **kwargs: Any,
) -> dict[str, Any]

Prepare the cancellations plot, an L3 plot.

events, and optionally start_time, end_time, age_floor_s, distance_floor_bps and distance_cap_bps. Draws each cancellation by how long the order rested and how far from the touch it sat.

cumulative_signed_volume

cumulative_signed_volume(
    trades: DataFrame,
    *,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    level: Level | str | None = _UNSET,
    min_trades: int = 1,
    time_bins: int | None = SERIES_BINS,
) -> dict[str, Any]

Cumulative signed volume: the running sum of buy volume minus sell volume.

The running sum comes from :func:~ob_analytics.flow_toxicity.cumulative_signed_volume, which infers the aggressor side of a trade that has none. The sum starts at zero at the start of the window. A long series is thinned to time_bins time steps by :func:thin_positions, which keeps the lowest and highest value of each step; None keeps every trade.

The payload holds timestamp and cumulative_signed_volume (in the instrument's own units), thinned, y_range and too_few. With fewer than min_trades trades (by default, none), too_few says so and the face draws that message in place of the line.

depth_bands

depth_bands(
    depth_summary: DataFrame,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    perc_line: bool = True,
    side_line: bool = True,
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare data for depth-band stacked area chart.

The volume in each band comes from :func:~ob_analytics.depth.depth_bands, averaged over seconds, or over minutes for a window longer than 15 minutes. The bands are read from the (bid|ask)_vol<N>bps columns of depth_summary, so any depth_bps / depth_bins configuration works. A window with no rows gives empty asks_cumsum / bids_cumsum_neg frames that keep the bin columns; the renderers draw a "no data" figure.

depth_chart

depth_chart(
    order_book: BookSnapshot,
    *,
    level: Level | str | None = _UNSET,
    **options: Any,
) -> dict[str, Any]

Prepare a depth chart: the payload of :func:prepare_book_snapshot_data.

The depth chart draws the same book as the book snapshot, as a cumulative curve, so it takes the same arguments.

depth_heatmap

depth_heatmap(
    depth: DataFrame,
    spread: DataFrame | None = None,
    trades: DataFrame | None = None,
    show_mp: bool = True,
    show_all_depth: bool = False,
    col_bias: float = 1.0,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    price_from: float | None = None,
    price_to: float | None = None,
    volume_from: float | None = None,
    volume_to: float | None = None,
    price_by: float | None = None,
    iceberg_lines: DataFrame | None = None,
    iceberg_refills: DataFrame | None = None,
    hidden_trades: DataFrame | None = None,
    *,
    level: Level | str | None = _UNSET,
    time_bins: int | None = SERIES_BINS,
) -> dict[str, Any]

Prepare data for the price-level depth heatmap.

col_bias is the gamma of a power-law color normalization (volume ** col_bias mapped onto the colormap). 1.0 (the default) is linear: high-volume walls stand out against a dark field. Values in (0, 1) progressively brighten low-volume levels, revealing near-touch structure in heavy-tailed books (0.1 matches the R package's palette bias). Values <= 0 select a log10 scale.

By default a price level that does not change in the window is left out: it would be one flat line from start to end. When no level changes at all, every level is kept instead, so a quiet book still draws. show_all_depth=True keeps every level in all cases.

The payload's notice is None or a short sentence for the renderer to show on the chart: why the heatmap is empty, or that no level changed.

iceberg_lines, iceberg_refills and hidden_trades are the optional hidden-liquidity overlay (see :func:prepare_hidden_liquidity_overlay), already clipped to the caller's display window. None (the default) draws the heatmap with no overlay. The payload's iceberg_chains holds the lines one chain per iceberg (:func:iceberg_chains).

color_limits is the volume range the colours span (:func:color_limits). With price_by, price_ticks are price axis ticks price_by apart across y_range; otherwise it is None.

A long quote line is thinned to time_bins time steps by :func:thin_positions; None keeps every row. The payload's thinned says how many rows were kept.

events_histogram

events_histogram(
    events: DataFrame,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    val: str = "volume",
    bw: float | None = None,
    price_from: float | None = None,
    price_to: float | None = None,
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare data for an events price/volume histogram.

price_from/price_to clip the events to a price window before binning. Without it the price face collapses to a single 1px spike: even the 1st-99th percentile of a heavy-tailed book still spans the far-from- touch cancelled orders, so the caller passes a mid-anchored focus window (the same one the depth heatmap uses) to keep the near-touch distribution legible.

The events are binned here, for every backend: edges are the bin edges (of width bw, or a width chosen from the data when bw is None; see :func:histogram_edges), and bid_counts and ask_counts the events of each side per bin, None for a side with no events. edges is None when no event is left.

hidden_executions

hidden_executions(
    events: DataFrame,
    trades: DataFrame,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare data for a hidden-executions overlay chart.

Shows hidden execution volume (raw_event_type == 5) scattered over the trade price time series. Degrades to an empty plot with a message when no hidden execution data is present.

hidden_liquidity_overlay

hidden_liquidity_overlay(
    slices: DataFrame,
    hidden: DataFrame,
    *,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    price_from: float | None = None,
    price_to: float | None = None,
) -> dict[str, pd.DataFrame]

Clip iceberg refills and hidden trades to a face's display window.

Clips :func:~ob_analytics.hidden_liquidity.iceberg_slices's rows and :func:~ob_analytics.hidden_liquidity.hidden_trades's output to start_time/end_time/price_from/price_to -- the same window the depth heatmap and order-activity map already clip to, so a full day's ~900 icebergs / ~9,600 hidden trades do not flood a face meant to show a few minutes.

Parameters:

Name Type Description Default
slices DataFrame

Output of :func:~ob_analytics.hidden_liquidity.iceberg_slices.

required
hidden DataFrame

Output of :func:~ob_analytics.hidden_liquidity.hidden_trades.

required
start_time Timestamp

Keep only rows with a timestamp in [start_time, end_time]. Both ends are inclusive. None (the default) leaves that end open.

None
end_time Timestamp

Keep only rows with a timestamp in [start_time, end_time]. Both ends are inclusive. None (the default) leaves that end open.

None
price_from float

Keep only rows with a price in [price_from, price_to]. Both ends are inclusive. Give them in the unit of the price column of slices and hidden: integer ticks for a raw result, the quote currency for a display result. None (the default) leaves that end open.

None
price_to float

Keep only rows with a price in [price_from, price_to]. Both ends are inclusive. Give them in the unit of the price column of slices and hidden: integer ticks for a raw result, the quote currency for a display result. None (the default) leaves that end open.

None

Returns:

Type Description
dict of str to pandas.DataFrame

"iceberg_lines" -- one row per surviving slice, for icebergs with at least two slices left in the window (draw as a joining line). "iceberg_refills" -- one row per refill slice (slice > 1) in the window (draw as a marker). "hidden_trades" -- hidden-trade rows in the window.

kyle_lambda

kyle_lambda(
    kyle_result: KyleLambdaResult,
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare data for Kyle's Lambda regression scatter.

fit_line is a frame of the x and y of the fitted line across the signed order flow, through the mean of the points with slope lambda_; it is None when there is no fit.

l1_ticker

l1_ticker(
    l1: DataFrame,
    *,
    at: Timestamp | str | None = None,
    symbol: str = "",
    start_time: Timestamp | str | None = None,
    end_time: Timestamp | str | None = None,
    level: Level | str | None = _UNSET,
    time_bins: int | None = SERIES_BINS,
) -> dict[str, Any]

The Level 1 quote: best bid, best ask and last trade.

l1 is the l1_ticker metric's table (see :class:~ob_analytics.metrics.L1TickerMetric). The face draws one of two pictures:

  • With at, the quote card for that instant: the last row at or before at. symbol names the instrument on the card.
  • Without at, the three prices over time, from start_time to end_time (default: the whole table). The price axis covers every trade and the 1st to 99th percentile of the quotes.

A time with no time zone (at, start_time, end_time) is read in the data's time zone. The card's payload is plain numbers, so a card can also be drawn without a result: plot("l1_ticker", bid=99, ask=101, last=100).

Returns:

Type Description
dict

For the card: bid / ask / last (prices), bid_size / ask_size / last_size, at and symbol; a value the table does not have yet is None. For the prices over time: timestamp, best_bid_price, best_ask_price, last_price and y_range, with only the rows where a price changes, and thinned. A long series is thinned to time_bins time steps by :func:thin_positions; None keeps every row. thinned says how many rows were kept.

liquidity_at_touch

liquidity_at_touch(
    *args: Any,
    level: Level | str | None = _UNSET,
    **kwargs: Any,
) -> dict[str, Any]

Prepare the liquidity at the touch. level is required.

L2: depth_summary, and optionally start_time, end_time and events. Draws the resting size at the best bid and ask, with a strip of the events beneath when events is given.

L3: events, and optionally side, n_time, start_time and end_time. Draws the touch queue, each cell coloured by the age of the order at that place in the queue.

order_activity

order_activity(
    *args: Any,
    level: Level | str | None = _UNSET,
    **kwargs: Any,
) -> dict[str, Any]

Prepare the order activity map. level is required.

L2: depth, and optionally start_time, end_time, price_from, price_to, volume_from and volume_to. Draws the size added to and removed from each price level, at its price.

L3: events, and optionally start_time, end_time, price_from, price_to, max_spans, marker_threshold and the three frames of :func:hidden_liquidity_overlay. Draws each order as one span from placement to its end.

order_outcome

order_outcome(
    events: DataFrame,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    *,
    level: Level | str | None = _UNSET,
    distance_bins: int | Sequence[float] = 10,
    min_bin_orders: int = MIN_BIN_ORDERS,
    lifecycles: DataFrame | None = None,
) -> dict[str, Any]

L3 (MBO) order outcome: how often orders filled, by placement distance.

Takes every order placed in the window whose life has ended, from :func:~ob_analytics.book.order_lifecycles, and groups it by placement distance (aggressiveness_bps: the distance from the best price on its own side at placement, positive when it improved the touch) with :func:~ob_analytics.book.fill_rate_by_distance. Each bar is one distance bin: the share of its orders that filled in full, with the share that filled in part stacked on top. The rest were cancelled. Orders still resting are left out.

The payload holds bins (the :func:~ob_analytics.book.fill_rate_by_distance table, with label, the bin's x label, filled_pct and partial_pct, the two shares in percent, and thin, whether the bin holds fewer than min_bin_orders orders), min_bin_orders, touch_at (the x position of the bin edge at a distance of 0, between two bars, or None when no edge is at 0), notice and too_few. A thin bar is drawn faded, and every bar is labelled with its number of orders, so a high rate from a few orders is not over-read. With fewer than min_bin_orders orders in all, too_few says so and the face draws that message in place of the bars.

lifecycles is order_lifecycles(events) when the caller already has it; None (the default) builds it here.

price_view

price_view(
    depth_summary: DataFrame,
    trades: DataFrame | None = None,
    *,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    level: Level | str | None = _UNSET,
    time_bins: int | None = SERIES_BINS,
) -> dict[str, Any]

L2 price view: the spread ribbon plus the volume-weighted microprice.

Reads best_bid_price / best_ask_price / best_bid_vol / best_ask_vol from the depth summary and derives the microprice (bid * ask_vol + ask * bid_vol) / (bid_vol + ask_vol) (:func:~ob_analytics.depth.micro_price) -- which leans toward the side with the heavier opposite book, i.e. the direction price is likely to move -- and the plain mid. A quote that cannot be read as a price (:func:~ob_analytics.depth.readable_quotes: an empty side or a crossed book) has no mid of either kind, so neither line is drawn there. Optionally overlays executions (buy/sell dots at trade price) when trades is given.

A long series is thinned to time_bins time steps by :func:thin_positions; None keeps every row. The payload's thinned says how many rows were kept.

queue_position

queue_position(
    events: DataFrame,
    *,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    marker_threshold: int = 400,
    level: Level | str | None = _UNSET,
    time_bins: int | None = SERIES_BINS,
    queue: DataFrame | None = None,
    lifecycles: DataFrame | None = None,
) -> dict[str, Any]

L3 (MBO) queue position: each touch order's FIFO rank over time, by fate.

Consumes the queue engine (:func:ob_analytics.queue.queue_positions at the touch) and joins each order's terminal outcome (:func:~ob_analytics.book.order_lifecycles), so a trajectory traces an order marching toward the front (rank 1) as the orders ahead fill or cancel, coloured by how it ended. Visible-only: hidden orders and market orders are absent. events must be classified (the type column of :func:~ob_analytics.analytics.set_order_types) and carry fill.

Returns one frame per fate (filled / cancelled / resting) with timestamp, id, rank, age_s, in time order; ends, the last row of each filled and each cancelled order (where its terminal mark goes); max_rank for the (inverted) y-axis; and show_markers (terminal × / ○ only when few enough orders).

With time_bins, each order's line is thinned to its lowest, highest and last rank in each of that many time steps (:func:thin_order_lines); None keeps every row. The payload's thinned says how many rows were kept.

queue is queue_positions(events, levels="touch") and lifecycles is order_lifecycles(events), when the caller already has them; None (the default) builds each here.

roll_spread

roll_spread(
    roll_df: DataFrame,
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare a :func:~ob_analytics.cost.roll_spread table for its face.

The face draws the implied spread, in the quote currency, one point per window, or the one value as a number when there is a single window. The note says how many windows the model could not measure, and the median lag-1 autocorrelation of the price changes, which Roll's model puts at -0.5.

spread

spread(
    depth_summary: DataFrame,
    *,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    level: Level | str | None = _UNSET,
    time_bins: int | None = SERIES_BINS,
) -> dict[str, Any]

Spread through time: best ask minus best bid, from the depth summary.

The spread comes from :func:~ob_analytics.depth.quoted_spread, so only quotes that can be read as a price count. When the window holds more than four quotes per time bin, the face draws one point per window of round length (at least the window's span divided by time_bins): the mean spread over the window, weighted by time, with a band from the smallest to the largest spread in it, so every spike is still drawn. Otherwise it draws every quote as a step line. None keeps every quote.

The payload holds timestamp, spread (in the quote currency), spread_min and spread_max (the band, or None when every quote is drawn), window (the window length, or None), y_range, notice and too_few. A windowed series ends with one more point, at the end of the last window, so the last window is drawn its full length. With no readable quote, too_few says so and the face draws that message in place of the line.

time_series

time_series(
    timestamp: Series,
    series: Series,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    title: str = "time series",
    y_label: str = "series",
    *,
    level: Level | str | None = _UNSET,
    time_bins: int | None = SERIES_BINS,
) -> dict[str, Any]

Prepare data for a generic time-series step plot.

A long series is thinned to time_bins time steps by :func:thin_positions; None keeps every row. The payload's thinned says how many rows were kept.

trade_imbalance

trade_imbalance(
    imbalance_df: DataFrame,
    trades: DataFrame | None = None,
    *,
    min_trades: int = MIN_TRADES,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare data for a trade-imbalance bar chart.

Bar colours (the theme's buy / sell split on the sign of the trade imbalance) and bar width (which depends on the renderer's x-axis units; matplotlib uses date numbers) are chosen by each backend rather than here.

A window with fewer than min_trades trades (the n_trades column of :func:~ob_analytics.flow_toxicity.trade_imbalance) is left out of imbalance_df, and notice says how many were. When the table has an n_takers column, the floor counts taker orders instead of trades, and the messages say so. When no window is left, too_few says so and the face draws that message in place of the bars. A table with neither column is drawn whole. bar_gap is the median time between windows before any are left out, so a bar stays as wide as its window; it is None for fewer than two windows.

trade_imbalance_by_window

trade_imbalance_by_window(
    trades: DataFrame,
    *,
    windows: tuple[str, ...] = TRADE_IMBALANCE_WINDOWS,
    grid: str = "5s",
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Trade imbalance over several trailing windows, for the horizon graph.

A single trade imbalance line shows one window; this computes trade imbalance over several trailing windows on one grid (:func:~ob_analytics.flow_toxicity.trade_imbalance_by_window) from the trades between start_time and end_time, so pressure over short and long windows can be compared at a glance. Each row is a window; the value is trade imbalance in [-1, +1] (buy pressure positive), rendered as a stacked horizon-graph band per row.

Returns trade_imbalance (a len(windows) x n_grid array, longest window last so it plots at the top), times (grid timestamps), windows, and the fill of each colour band: band_alphas, buy_bands and sell_bands, the height of each band as a fraction of its row.

trade_size

trade_size(
    trades: DataFrame,
    *,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    level: Level | str | None = _UNSET,
    size_bins: int = TRADE_SIZE_BINS,
    min_trades: int | None = None,
) -> dict[str, Any]

Trade-size distribution: how many trades fell in each size range, by side.

Trade sizes are heavy-tailed, so the bins are of equal width in the logarithm of the size, and the axis is drawn in powers of ten with the sizes written out in full, in the instrument's units whether the trades hold integer lots or display sizes. The axis starts at the size of the smallest 1% of trades (:data:TRADE_SIZE_LOW_QUANTILE), so a few one-lot trades do not stretch it; trades below that size are left out, and notice says how many. Buys are drawn above the zero line and sells below it, so the two distributions can be compared bar by bar. A trade with no aggressor side gets one from the tick rule (:func:~ob_analytics.trade_sign.resolve_direction).

The payload holds size_edges (the size_bins + 1 bin edges, in the instrument's units), buy_counts and sell_counts (trades per bin), x_ticks / x_tick_labels (tick sizes and their plain labels), y_ticks / y_tick_labels (count positions, sells negative, and their labels without a sign), y_range, notice and too_few. With fewer than min_trades trades (default :data:MIN_TRADES), too_few says so and the face draws that message in place of the bars.

trade_tape

trade_tape(
    *args: Any,
    level: Level | str | None = _UNSET,
    **kwargs: Any,
) -> dict[str, Any]

Prepare the trade tape. level is required.

L2: trades, and optionally spread, start_time and end_time. Draws the trade price as a step line.

L3: events and trades, and optionally spread, start_time, end_time, price_from, price_to and density_threshold. Draws each trade at the end of a bar that shows how long the maker order had rested.

trading_halts

trading_halts(
    trades: DataFrame,
    halts: DataFrame | None = None,
    events: DataFrame | None = None,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    *,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare data for a trading-halts overlay chart.

Draws vertical shaded bands on the trade price chart for halt periods. Accepts either a halts DataFrame directly or extracts halt events (raw_event_type == 7) from the events DataFrame.

transaction_costs

transaction_costs(
    costs: DataFrame,
    *,
    window: str = "1min",
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare the transaction-cost decomposition for plotting.

The face shows where a taker's cost went: the effective spread is the whole of it, the realized spread is the part the liquidity provider kept, and the gap between the two lines is the price impact. Because they add up row by row, drawing them as two lines makes the third readable as the band between them, with no third line to follow.

Per-trade costs are far too noisy to read directly, so they are averaged onto window, weighted by trade size the same way :func:~ob_analytics.cost.cost_summary weights the session figure. The raw per-trade effective spread is passed through as well, for a faint scatter behind the lines that shows the spread of what was averaged.

Parameters:

Name Type Description Default
costs DataFrame

A :func:~ob_analytics.cost.transaction_costs frame.

required
window str

Length of the averaging window, a fixed duration such as "1min"; windows count from the Unix epoch. Default "1min".

'1min'

Returns:

Type Description
dict

times / effective / realized / impact (the windowed series, in basis points), trade_times / trade_effective (the raw per-trade scatter), and horizon (the realized-spread horizon the costs were measured at, for the title). impact is carried for a backend that wants to draw it outright; the two shipped faces read it off the chart as the band between the other two lines.

volume_profile

volume_profile(
    trades: DataFrame,
    *,
    start_time: Timestamp | None = None,
    end_time: Timestamp | None = None,
    level: Level | str | None = _UNSET,
    price_bins: int = 50,
    min_trades: int = 1,
) -> dict[str, Any]

Volume profile: the size traded at each price, buys and sells stacked.

The bins come from :func:~ob_analytics.bars.volume_profile, which cuts the traded price range into at most price_bins bins. The payload holds profile (that table, with price_mid, the centre of each bin), bin_height (the width of a bin in price), y_range and too_few. With fewer than min_trades trades (by default, none), too_few says so and the face draws that message in place of the bars.

vpin

vpin(
    vpin_result: VpinResult,
    threshold: float = 0.7,
    *,
    min_trades: int = MIN_TRADES,
    level: Level | str | None = _UNSET,
) -> dict[str, Any]

Prepare data for a VPIN time-series chart.

vpin_result is what :func:~ob_analytics.flow_toxicity.vpin returns. The payload's note says how the buckets were sized when bucket_volume="fit" sized them from the total volume, and is empty otherwise. The gallery shows it under the card.

When the median bucket holds fewer than min_trades trades (the n_trades column of :func:~ob_analytics.flow_toxicity.vpin), the payload's too_few says so and the face draws that message in place of the chart. Otherwise too_few is empty. When the table has an n_takers column, the floor counts taker orders instead of trades, and the message says so.

Theme and Saving

Pass theme=PlotTheme(...) to plot() to override DEFAULT_THEME for a single call, on any backend; there is no global theme to set.

PlotTheme dataclass

PlotTheme(
    style: str = "white",
    context: str = "notebook",
    font_scale: float = 1.05,
    palette: Palette = DEFAULT_PALETTE,
    rc: dict[str, object] = (
        lambda: {
            "axes.grid": True,
            "grid.linestyle": ":",
            "grid.alpha": 0.35,
            "axes.spines.top": False,
            "axes.spines.right": False,
            "axes.edgecolor": DEFAULT_PALETTE.rule,
            "axes.titlelocation": "left",
            "axes.titleweight": "bold",
            "lines.linewidth": 2.0,
        }
    )(),
    plotly_layout: dict[str, object] = (
        lambda: {
            "title": {
                "x": 0.0,
                "xanchor": "left",
                "xref": "paper",
                "font": {"weight": "bold"},
            }
        }
    )(),
    bokeh_figure: dict[str, object] = dict(),
)

Configurable visual theme for ob-analytics plots, in every backend.

Attributes:

Name Type Description
style str

Seaborn style name: "white", "whitegrid", "ticks", "dark", or "darkgrid". In plotly and bokeh the two dark styles draw on seaborn's gray background and "ticks" draws outside tick marks.

context str

Seaborn context name: "paper", "notebook", "talk", or "poster". Scales text in every backend.

font_scale float

Font scaling factor, applied on top of context in every backend.

palette Palette

The colours every backend draws with.

rc dict[str, object]

Matplotlib rc overrides applied on top of the seaborn theme (matplotlib only).

plotly_layout dict[str, object]

Plotly layout properties applied on top of the theme's template (plotly only), e.g. {"font": {"family": "Georgia"}}.

bokeh_figure dict[str, object]

Keyword arguments passed to :func:bokeh.plotting.figure on top of the theme's defaults (bokeh only), e.g. {"width": 1200}.

dark property

dark: bool

Whether the style draws on a dark (gray) background.

text_scale property

text_scale: float

Text size relative to the default theme (context x font_scale).

The plotly and bokeh backends multiply their base font sizes by this, so the default theme keeps their base sizes exactly.

DEFAULT_THEME module-attribute

DEFAULT_THEME: PlotTheme = PlotTheme()

Palette dataclass

Palette(
    bid: str = "#0072B2",
    ask: str = "#D55E00",
    buy: str = "#009E73",
    sell: str = "#D55E00",
    filled: str = "#009E73",
    partial: str = "#CC79A7",
    cancelled: str = "#E69F00",
    hidden_trade: str = "#F0E442",
    price_line: str = "#222222",
    reference_line: str = "#888888",
    rule: str = "#444444",
    label: str = "#555555",
    spread_fill: str = "#9aa0a6",
    neutral: str = "#7f8c8d",
    series: str = "#5dade2",
    emphasis: str = "#e74c3c",
    threshold: str = "#f39c12",
    secondary_axis: str = "#f1c40f",
    imbalance: str = "#6d28d9",
    effective_spread: str = "#0072B2",
    realized_spread: str = "#CC79A7",
)

Named plot colours, shared by every rendering backend.

Every field is a hex colour string. Override single fields with :func:dataclasses.replace or by passing them to the constructor::

Palette(bid="#1f77b4", ask="#d62728")

Attributes:

Name Type Description
bid, ask str

Side of a resting order (Okabe–Ito blue / vermillion).

buy, sell str

Aggressor side of an execution: buyer-initiated (lifts the ask) and seller-initiated (hits the bid).

filled, partial, cancelled str

Order-outcome fate: fully executed / partly executed with the remainder removed / removed without any execution.

hidden_trade str

A trade that printed inside the visible spread, against an order the book did not show.

price_line str

The main price line (trade price, microprice) and dark markers.

reference_line str

Secondary reference marks: the mid line, dotted guides, "created" markers, and "no data" messages.

rule str

Zero lines, the book's mid rule, and axis edges.

label str

Annotation text.

spread_fill str

The band between best bid and best ask.

neutral str

Points with no side (for example hidden executions of unknown direction).

series str

A single unclassified data series (time series, VPIN buckets, Kyle's-lambda scatter).

emphasis str

A summary drawn over a series: rolling average, fitted line, halt span.

threshold str

A threshold line.

secondary_axis str

A series on a secondary y-axis, and that axis's labels.

imbalance str

The order book imbalance line.

effective_spread, realized_spread str

The two transaction-cost series.

DEFAULT_PALETTE module-attribute

DEFAULT_PALETTE: Palette = Palette()

save_figure

save_figure(
    fig: Figure,
    path: str | Path,
    *,
    dpi: int = 150,
    **kwargs: object,
) -> None

Save a matplotlib fig to path with sensible defaults.

Parameters:

Name Type Description Default
fig Figure

The matplotlib figure to save.

required
path str or Path

Destination file path (e.g. "output/plot.png").

required
dpi int

Resolution in dots per inch (default 150).

150
**kwargs object

Additional keyword arguments forwarded to :meth:~matplotlib.figure.Figure.savefig. Pass bbox_inches="tight" explicitly to crop to artist extents — it is not the default because it forces a second full draw (roughly doubling save time on dense figures), and every renderer already lays out the figures it creates.

{}

Display windows

The gallery picks one time window and one price band per run, and every face it clips gets the same bounds. Pass them to your own faces to match it.

busiest_window module-attribute

busiest_window = busiest_window

focus_window module-attribute

focus_window = focus_window

FocusWindow module-attribute

FocusWindow = FocusWindow

format_time_axis

format_time_axis(ax: Axes) -> None

Consistent intraday ticks for a date-valued x-axis.

Sets an explicit AutoDateLocator + ConciseDateFormatter pair. Renderers that plot date2num floats stay off matplotlib's date units converter, whose registration forces the slow collection-draw path (one Path rebuilt per segment on every draw, as profiling showed); for unit-converted axes only the tick style changes (the default formatter rendered "02 02:45"-style day prefixes).

Renderer registry

Every plot of the package is declared once, in a concept table, at the coordinate (concept, level, backend) (where level is a Level or None for level-less analytics). The table says which backends draw each plot, and the built-in backends register their renderers into RENDERERS from it. Asking a backend for a plot it does not draw raises UnknownNameError (also a KeyError) that names the backends that do. A concept is level-less or drawn at a level, and the same kind on every backend: registering it the other way raises ConfigError. Register a whole new backend module with register_plot_backend (or advertise it under the ob_analytics.plot_backends entry-point group), or a single renderer directly with RENDERERS.register((concept, level, backend), fn); plot(), plot_result() and the gallery find such a renderer as they find the table's. To see how a concept is registered before adding to it, list its (level, backend) pairs with RENDERERS.placements(concept).

register_plot_backend

register_plot_backend(name: str, module_path: str) -> None

Register a visualization backend module.

The module at module_path must call RENDERERS.register((concept, level, name), fn) for each plot it supports (typically at import time). It is imported lazily on the first :func:~ob_analytics.visualization.plot call that targets name.

Parameters:

Name Type Description Default
name str

Backend name used in plot(..., backend=name).

required
module_path str

Dotted import path, e.g. "my_package._bokeh_backend".

required

Examples:

>>> from ob_analytics.visualization import register_plot_backend
>>> register_plot_backend("bokeh", "my_pkg._bokeh")

load_plot_backend_plugins

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

Discover and register plot backends advertised via entry points.

Scans the :data:ENTRY_POINT_GROUP entry-point group and registers each entry's module under the entry-point name, as :func:register_plot_backend would. The module is not imported here: it is imported on the first :func:~ob_analytics.visualization.plot call that targets the backend.

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

Returns:

Type Description
list of str

The backend names newly registered by this call.

RENDERERS module-attribute

RENDERERS: RendererRegistry = RendererRegistry('renderer')

RendererRegistry

RendererRegistry(kind: str)

Bases: Registry[RendererKey, RendererFn]

The renderer :class:Registry, which keeps each concept one kind.

A concept is either level-less, registered at None, or drawn at a level, registered at Level.L2 and/or Level.L3. It is the same kind on every backend: :func:~ob_analytics.visualization.plot and the gallery call it the same way whichever backend draws it.

get

get(key: RendererKey) -> RendererFn

Return the renderer for (concept, level, backend).

Raises:

Type Description
UnknownNameError

If no renderer is registered under key. The message says which backends or levels do draw the concept, or names the concepts closest to it when no backend draws it.

missing

missing(
    concept: str, level: Level | None, backend: str
) -> UnknownNameError

The error for a concept that backend does not draw at level.

placements

placements(
    concept: str,
) -> tuple[tuple[Level | None, str], ...]

Return each (level, backend) concept is registered at, in order.

A snapshot, so a caller can register while looping over it.

register

register(key: RendererKey, value: RendererFn) -> None

Register value under the key (concept, level, backend).

Raises:

Type Description
ConfigError

If key is not (concept, level, backend) with a text concept, a :class:Level or None level and a text backend, or its concept is already registered, on any backend, as the other kind: at a level when key is level-less, or level-less when key has a level.