Skip to content

Analytics

Accounting, execution metrics and post-trade analytics. Importable from microbook.sim.

Portfolio dataclass

Portfolio(cash: float = 0.0, position: int = 0, avg_cost: float = 0.0, realized_pnl: float = 0.0, fees_paid: float = 0.0, maker_fee: float = 0.0, taker_fee: float = 0.0, volume: int = 0)

Single-asset position and PnL accounting (average-cost method).

Fees are charged per share and are negative for rebates, e.g. a typical maker/taker schedule is maker_fee=-0.002, taker_fee=0.003.

Identity (checked by the test-suite for arbitrary fill sequences)::

total_pnl(mark) == cash - initial_cash + position * mark

cash class-attribute instance-attribute

cash: float = 0.0

Cash balance.

position class-attribute instance-attribute

position: int = 0

Signed position, in shares.

avg_cost class-attribute instance-attribute

avg_cost: float = 0.0

Average entry price of the open position.

realized_pnl class-attribute instance-attribute

realized_pnl: float = 0.0

Realized PnL, gross of fees.

fees_paid class-attribute instance-attribute

fees_paid: float = 0.0

Fees paid, net of rebates.

maker_fee class-attribute instance-attribute

maker_fee: float = 0.0

Fee per share on maker fills; negative for a rebate.

taker_fee class-attribute instance-attribute

taker_fee: float = 0.0

Fee per share on taker fills.

volume class-attribute instance-attribute

volume: int = 0

Shares traded.

initial_cash class-attribute instance-attribute

initial_cash: float = field(default=0.0, init=False)

Cash at construction: the baseline of total PnL.

on_fill

on_fill(fill: Fill, my_order_id: str | None, my_side: Side, *, is_maker: bool = False) -> None

Apply a fill of one of my orders. my_side is my order's side; is_maker selects the maker or taker fee.

unrealized_pnl

unrealized_pnl(mark: float) -> float

PnL of the open position marked at mark, against its average cost.

total_pnl

total_pnl(mark: float) -> float

Realized + unrealized PnL, net of fees, marking the position at mark.

mark_to_market

mark_to_market(lob: LimitOrderBook) -> float | None

Total PnL marked at the book's midprice (None if the book is one-sided).

ExecutionMetrics

ExecutionMetrics()

Per-strategy execution quality metrics.

  • VWAP of buys and sells, blended average price, total notional
  • slippage vs arrival (decision-time) midprice, per direction
  • spread capture per share on maker fills (vs the pre-trade mid)
  • fill ratio (filled / submitted) and participation rate (share of market volume)

Each ratio is computed only over the fills that carry the information it needs (e.g. slippage only over fills of orders with a known arrival mid), so missing data never dilutes a metric.

filled_qty property

filled_qty: int

Shares filled, buys plus sells.

buy_qty property

buy_qty: int

Shares bought.

sell_qty property

sell_qty: int

Shares sold.

maker_qty property

maker_qty: int

Shares filled as the resting order (maker).

taker_qty property

taker_qty: int

Shares filled as the incoming order (taker).

record_order

record_order(order_id: str, side: Side, qty: int, arrival_mid: float | None) -> None

Register an order at decision time. arrival_mid may be None (no two-sided market), in which case its fills are excluded from slippage.

record_market_volume

record_market_volume(fills: list[Fill] | tuple[Fill, ...]) -> None

Accumulate market-wide traded volume (called for every fill in the market).

on_fill

on_fill(fill: Fill, my_side: Side, is_maker: bool, mid: float | None = None, time: int | None = None) -> None

Record a fill of one of this strategy's orders.

mid is the midprice immediately before the trade (used for spread capture); time is the simulation time (used for markouts).

buy_vwap

buy_vwap() -> float | None

Volume-weighted average buy price, or None if nothing was bought.

sell_vwap

sell_vwap() -> float | None

Volume-weighted average sell price, or None if nothing was sold.

avg_price

avg_price() -> float | None

Volume-weighted average price over all fills, or None if there were none.

total_notional

total_notional() -> float

Sum of price times quantity over all fills.

buy_slippage

buy_slippage() -> float | None

Buy VWAP minus qty-weighted arrival mid. Positive = paid up (cost).

sell_slippage

sell_slippage() -> float | None

Qty-weighted arrival mid minus sell VWAP. Positive = sold below arrival (cost).

spread_capture_per_share

spread_capture_per_share() -> float | None

Average distance from the pre-trade mid earned per maker share (positive = earned).

fill_ratio

fill_ratio() -> float | None

Filled quantity / submitted quantity.

participation_rate

participation_rate() -> float | None

This strategy's share of total market volume.

summary

summary() -> dict[str, float | int | None]

All metrics as a flat dict.

FillRecord

Bases: NamedTuple

One fill from a strategy's point of view (kept for post-trade analysis such as markouts).

time instance-attribute

time: int | None

Simulation time of the fill; None if it was not recorded.

side instance-attribute

side: Side

This strategy's side of the trade.

price instance-attribute

price: float

Execution price.

qty instance-attribute

qty: int

Shares traded.

is_maker instance-attribute

is_maker: bool

Whether this strategy's order was resting.

mid instance-attribute

mid: float | None

Midprice just before the trade; None if the book was one-sided.

TimeSeries dataclass

TimeSeries(t: list[int] = list(), mid: list[float] = list(), spread: list[float] = list(), imbalance: list[float] = list())

Book state sampled on every SNAPSHOT: midprice, spread and top-3 imbalance.

t class-attribute instance-attribute

t: list[int] = field(default_factory=list)

Sample times.

mid class-attribute instance-attribute

mid: list[float] = field(default_factory=list)

Midprice; NaN while the book is one-sided.

spread class-attribute instance-attribute

spread: list[float] = field(default_factory=list)

Best ask minus best bid; NaN while the book is one-sided.

imbalance class-attribute instance-attribute

imbalance: list[float] = field(default_factory=list)

Top-3 depth imbalance in [-1, 1]; NaN for an empty book.

spr property

spr: list[float]

Deprecated alias of spread (removed in 2.0).

imb property

imb: list[float]

Deprecated alias of imbalance (removed in 2.0).

record

record(now: int, lob: LimitOrderBook) -> None

Append the current mid, spread and top-3 imbalance (NaN where undefined).

as_dict

as_dict() -> dict[str, list[Any]]

The recorded series as lists keyed by field name.

strategy_report

strategy_report(sim: MarketSimulator, names: Iterable[str] | None = None, *, horizons: Sequence[int] = (1, 10, 100)) -> dict[str, dict[str, Any]]

One flat dict per strategy combining PnL, inventory, execution and markout metrics.

markouts

markouts(fills: Iterable[FillRecord], mid_path: Sequence[tuple[int, float]], horizons: Sequence[int] = (1, 10, 100), *, end_time: int | None = None) -> dict[int, float | None]

Volume-weighted markout per share at each horizon, from the trader's side.

For a fill at price p and time t the markout at horizon h is side * (mid(t + h) - p): positive means the trade was profitable when marked h time units later. For a market maker, the decay of markouts with horizon measures adverse selection: spread captured at h = 0 that is given back as the price moves against the fill.

Fills whose horizon would extend past end_time are excluded.

pnl_stats

pnl_stats(pnl: Sequence[float]) -> dict[str, float]

Summary of a cumulative PnL path sampled at regular intervals.

sharpe is mean/stdev of per-sample PnL increments scaled by sqrt(number of increments): a dimensionless signal-to-noise ratio for the whole run (not annualized).

inventory_stats

inventory_stats(inventory: Sequence[int]) -> dict[str, float]

Mean and maximum absolute inventory, and the final inventory.

max_drawdown

max_drawdown(series: Sequence[float]) -> float

Largest peak-to-trough decline (a non-negative number). NaNs are skipped.

mid_at

mid_at(mid_path: Sequence[tuple[int, float]], t: int) -> float | None

Value of a step-function mid path (SimResult.mid_path) at the end of time t.

imbalance

imbalance(lob: LimitOrderBook, levels: int = 3) -> float | None

Depth imbalance over the top levels: (bid qty - ask qty) / total, in [-1, 1].

Positive means more resting size on the bid (buying pressure); None when both sides are empty.

format_table

format_table(rows: dict[str, dict[str, Any]], columns: Sequence[str] | None = None, *, precision: int = 4) -> str

Render {row_name: {col: value}} as a fixed-width text table.