Backtest#
- class backtest_lib.Backtest(strategy: Strategy, market_view: MarketView, initial_portfolio: Portfolio | Cash, universe: Universe | None = None, settings: BacktestSettings = BacktestSettings(allow_short=False), *, engine: Engine | None = None, decision_schedule: str | DecisionSchedule | None = None, backend='polars')#
Runs a historical simulation of a
Strategyover aMarketViewand aUniverse.Backtestis a lightweight orchestration object that iterates through market periods, invokes the strategy on configured decision dates, and updates the simulated portfolio by applying inter-period price changes. The resulting allocation history is materialized via a configurablePastViewbackend and converted intoBacktestResults.The simulation model is intentionally simple:
Decisions are evaluated on a
DecisionSchedule. Between decision points, the portfolio weights drift only due to price movements.The backtest assumes the portfolio can be rebalanced to the strategy’s target portfolio exactly at decision times (i.e., no slippage/fees unless incorporated elsewhere).
Strategies may return an incomplete set of holdings; missing securities are padded with zero weight to match the full universe.
If
BacktestSettings.allow_shortis False and the target contains negative weights, the target is coerced into a long-only portfolio.
- Parameters:
strategy – Callable strategy that produces a
Decisiongiven the current universe, portfolio, market view, and optional context.universe – The tradable security set defining the expected holdings keys. See
Universe.market_view – Historical market data used for pricing and period iteration. See
MarketView. The decision schedule defaults tomarket_view.periodswhen not provided.initial_portfolio – Starting
WeightedPortfolioused to initialize the simulation state.settings – Controls simulation constraints (e.g., shorting). Defaults to
BacktestSettings.default.decision_schedule –
Rebalance schedule. May be:
A
DecisionScheduleinstance,A string specification consumed by
make_decision_schedule(), orNone, in which case a schedule is constructed from
market_view.periods.
backend – Backend identifier used to select the
PastViewimplementation used for data manipulation, memory allocation, and results view. Default (and currently only implemented) backend is “polars”.
- market_view#
Market data used during the run.
- Type:
- settings#
Backtest configuration settings.
- Type:
Example
>>> import backtest_lib as btl >>> from polars import read_csv >>> spot_prices = read_csv("docs/assets/data/spot_prices.csv") >>> market = btl.MarketView(spot_prices) >>> universe = market.securities >>> def hold_strategy(universe, current_portfolio, market, ctx): ... return btl.hold() >>> bt = btl.Backtest(hold_strategy, market, btl.uniform_portfolio(universe)) >>> results = bt.run() >>> results.annualized_return -0.00035649...