Full Code
How It Works
The backtest engine replays your data through the same pipeline thathz.run() uses in live trading:
-
Data normalization: Your input (dicts, CSV, or DataFrame) is converted into a chronological timeline of
Tickobjects withtimestamp,price,bid,ask, andvolumefields. - Timeline construction: All ticks across all feeds are merged into a single sorted timeline. Each timestamp carries forward the latest state of every feed (carry-forward interpolation).
-
Pipeline execution: At each tick, the engine builds a
Contextwith current feed data and inventory, then runs your pipeline functions in order. The output quotes are submitted to the internal paper exchange. - Paper matching: The paper exchange matches resting orders against the current feed price. Fills update positions and P&L.
-
Metrics computation: After all ticks are processed,
BacktestResultlazily computes Sharpe, Sortino, Calmar, drawdown, win rate, profit factor, and prediction-market-specific metrics like Brier score.
Rate limits and dedup windows are automatically relaxed during backtests for maximum throughput. The risk pipeline (position limits, drawdown, etc.) still runs normally.
Data Formats
hz.backtest() accepts four input formats for the data parameter:
list[dict]
The simplest format. Each dict must have atimestamp field and at least one of price or bid:
price is provided, bid and ask are set equal to price. If only bid and ask are provided, price is derived as the midpoint.
CSV file path
Pass a string path to a CSV file with a header row:timestamp, price, and optionally bid, ask, volume.
pandas DataFrame
Pass a DataFrame directly, no conversion needed:dict[str, data] for multi-feed
Map feed names to their data sources for strategies that consume multiple feeds:Interpreting Results
Theresult.summary() output contains three sections:
Returns
Risk
Trades
Prediction Market Metrics
Multi-Feed Backtesting
Test strategies that consume multiple data sources, such as a BTC-priced prediction market:btc feed updates even when book has no new data at that timestamp and vice versa.