Skip to main content

Crate quantwave_backtest

Crate quantwave_backtest 

Source
Expand description

Core vectorized portfolio simulation engine (Rust + Polars long format).

This crate provides the foundation for QuantWave’s backtesting capabilities under epic quantwave-gwx / task quantwave-1hr + quantwave-ug9t (streaming simulation + full batch-vs-streaming parity verification).

§Batch vs Streaming Parity (quantwave-ug9t)

  • BacktestEngine::run / backtest_simple_bool_signal: pure vectorized batch path (pre-computed signals in DF column; fast for research sweeps). Signal f64 value now interpreted as desired exposure (0=flat, >0=long units) enabling sizing.
  • run_streaming_simulation: streaming path driven by any Next<&Bar, Output=StrategySignal> generator (closer to live trading loop, supports rich metadata from features/PA/regimes).
  • Shared internal run_simulation core guarantees identical execution semantics (costs, fills, equity, trade recording) when fed equivalent signals.
  • Mandatory parity tests (in this file) enforce equity curves, trade counts/pnls/stats match within documented tolerance for strategies using regime filters + feature thresholds + rich PA structs (pole height sizing).

Design principles (per project AGENTS.md):

  • Long-format multi-symbol first-class (symbol, timestamp, ohlcv, signals).
  • Ready for rich Struct signals (e.g. from future PA detectors containing pole_height, strength, etc. for dynamic sizing/conviction).
  • Basic realistic execution: commission + slippage.
  • Vectorized foundation now; streaming parity (Next from quantwave-core) and full rich PA/ML integration in sibling tasks (ug9t, 06sz).
  • All new code will eventually carry batch-vs-streaming proptests.

Sources (recorded per AGENTS + 366 research):

  • Primary alignment: Yvictor/polars-backtest (native Polars long-format multi-symbol with realistic costs/execution model).
  • Vectorized portfolio concepts (clean-room): vectorbt (Apache-2 + Commons Clause) patterns for signal->position->pnl vectorization; RaptorBT analogs.
  • Rich signal metadata readiness: MQL5 PA series (Parts 69-70, 67) via quantwave-366 notes — structured outputs (pole_height etc.) for backtester consumption, not just viz. quantwave-06sz complete for integration (batch exposure + streaming StrategySignal.metadata + verified parity with pole sizing + regime/feature filters; batch native Struct col is extension point).
  • Current thin steel-thread: docs/examples/notebooks/strategy_backtest.py (synthetic + SuperTrend struct only; no PnL/costs/trades yet).
  • Parity framework pattern: modeled on quantwave-core/src/test_utils.rs check_batch_streaming_parity + indicator proptests (e.g. kinematic_kalman.rs).
  • Regime: quantwave-core/src/regimes/tar.rs (TAR for simple filter in parity test).
  • Features: quantwave-core/src/features/cyber_cycle.rs (CyberCycleFeatureExtractor).
  • Synthetic PA pole for test (non-production): concept from MQL5 PA + Ehlers turning points (see artifacts/anticipating_turning_points*.txt); recorded here per AGENTS “if no source validate”.

Universal Indicator / Next relevance: The engine itself is vectorized (batch) for v0.1. Streaming simulation mode (feeding signals from Next strategy state machines) + full parity proptests implemented in quantwave-ug9t. The crate re-exports core traits for future hybrid use.

Tolerance policy (documented for ug9t verification):

  • Equity curve values: relative + abs epsilon 1e-8 (float accum).
  • Trade count: exact.
  • PnL / final equity / stats: 1e-6 tolerance (costs/rounding).
  • Prices in trades: 1e-8.
  • Failure modes: unsorted data, NaNs in prices, generator state drift, mismatched exposure semantics, open position at end handling, regime/feature init bias on first bars (warmup NaNs tolerated in features).

NO root-level tests/ dirs created. Tests live inside this crate (#[cfg(test)]). Respects quantwave-core/tests/ rule for gold-standard indicator work.

Structs§

BacktestConfig
Configuration for a backtest run.
BacktestEngine
Core vectorized engine (MVP).
BacktestResult
Rich result bundle returned by the engine (Polars DataFrames + summary stats).
Bar
A minimal bar struct for driving streaming simulation (timestamp + close sufficient for price-action + feature driven strategies in MVP).
CostModel
Basic execution cost model.
EquityPoint
Per-bar equity snapshot (for the equity curve DF).
PAEvent
Simple struct for rich PA detector outputs (placeholder/stub for integration; full detectors in future PA work). Can be turned into StrategySignal or serialized into Polars Struct column for batch runs. Per quantwave-06sz.
StrategySignal
Rich signal output produced by a Next<&Bar, Output = StrategySignal> generator. Enables the streaming simulation mode (quantwave-ug9t) while carrying rich metadata (pole height sizing, regime, features) into Trade records.
Trade
A completed (or open) trade record. Rich enough for later PA metadata.

Enums§

BacktestError
Errors from the simulation engine.

Functions§

backtest_simple_bool_signal
Convenience function for the most common “simple boolean signal” use case on synthetic or small data (exactly as required for quantwave-1hr MVP).
run_streaming_simulation
Run simulation in streaming mode driven by a Next signal generator. The generator receives &Bar each step (price + ts) and returns StrategySignal (exposure for sizing + rich metadata e.g. pole_height).