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
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.
maker_fee
class-attribute
instance-attribute
¶
maker_fee: float = 0.0
Fee per share on maker fills; negative for a rebate.
initial_cash
class-attribute
instance-attribute
¶
Cash at construction: the baseline of total PnL.
on_fill
¶
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
¶
PnL of the open position marked at mark, against its average cost.
total_pnl
¶
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
¶
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.
record_order
¶
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
¶
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.
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).
FillRecord
¶
Bases: NamedTuple
One fill from a strategy's point of view (kept for post-trade analysis such as markouts).
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.
mid
class-attribute
instance-attribute
¶
Midprice; NaN while the book is one-sided.
spread
class-attribute
instance-attribute
¶
Best ask minus best bid; NaN while the book is one-sided.
imbalance
class-attribute
instance-attribute
¶
Top-3 depth imbalance in [-1, 1]; NaN for an empty book.
record
¶
record(now: int, lob: LimitOrderBook) -> None
Append the current mid, spread and top-3 imbalance (NaN where undefined).
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
¶
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
¶
Mean and maximum absolute inventory, and the final inventory.
max_drawdown
¶
Largest peak-to-trough decline (a non-negative number). NaNs are skipped.
mid_at
¶
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.