recall_guard.portfolio.backtest
recall_guard.portfolio.backtest
Long-short cross-sectional backtest engine for the cmmd backtest.
This module takes a stream of harness-style records plus a (date x ticker)
close-price matrix, builds a daily-rebalanced target-weight matrix where
weight[d, t] = direction[d, t] * confidence[d, t], and runs two backtests
through vectorbt:
raw_alpha: every surviving parse-OK rowcmmd: rows above the chosenp_memorizedthreshold removed
The two variants share one price matrix; the difference is the surviving record
stream. This file owns the BacktestMetrics and BacktestResult dataclasses,
plus both the compute path (run_backtest) and the artifact writer.
Layer rules and design deviation
The portfolio layer is order=1 in .sentrux/rules.toml and the harness
layer is order=0. Order=1 cannot import from order=0, so this module never
imports harness.evaluator.Record. Instead run_backtest accepts any
record-shaped object exposing parse_ok, predicted_direction,
raw_confidence, p_memorized, and prompt_hash.
The Record dataclass produced by harness.evaluator does not carry
metadata.date or metadata.ticker. To build a (date x ticker) weight
matrix, the caller passes prompt_metadata, mapping each record's
prompt_hash to {"ticker": str, "date": str}. The orchestrator builds that
mapping from the eval set; the engine stays pure compute.
Determinism
The engine is deterministic given identical records, prices,
prompt_metadata, and seed. Vectorbt's portfolio construction is
deterministic; the only stochastic step is the bootstrap CI on Sharpe and mean
daily return, which threads seed through core.bootstrap.bootstrap_ci.
Key contracts
BacktestResult.equity_curveshas columns["raw_alpha", "cmmd", "buy_and_hold_swda"]in that exact order. The raw/cmmd curves arecumprod(1 + daily_returns), so day 0 shows the entry fee (slightly below 1.0) and the terminal value equals1 + total_return; the fee-free buy-and-hold benchmark starts at exactly 1.0.BacktestResult.daily_returns_bpshas columns["raw_alpha", "cmmd"]and is denominated in basis points (x10^4).BacktestMetrics.max_drawdown_pctis signed: a negative number reports a drawdown (for example, -3.4 means -3.4%).
vectorbt 0.28 conventions
size_type='targetpercent'rebalances to the target weight on every bar. Combined withcash_sharing=True, group_by=Truethis gives one portfolio across all tickers; vectorbt deducts trading fees on the trade notional, which equals|Δw_t| x portfolio valueat the rebalance bar.freq='1D'sets the annualization factor (252 trading days/year) forPortfolio.sharpe_ratio().- The
sizematrix passed tofrom_ordersalready contains BIL's residual allocation, so vectorbt charges the BIL purchase as a real trade.
BacktestArtifactError
Bases: RuntimeError
Raised when writing the backtest artifacts to disk fails.
The writer builds every artifact in memory before touching disk and rolls back any partially-written files on failure (Req 7.6), so by the time this exception surfaces the run directory is in the same state it was in before the call.
Source code in recall_guard/portfolio/backtest.py
94 95 96 97 98 99 100 101 | |
BacktestMetrics
dataclass
Per-variant summary statistics for one backtest run.
All fields are JSON-friendly so downstream artifact writers (task
2.5) can dump the dataclass directly. The sharpe_annualised and
mean_daily_return_bps tuples are (point, lo, hi) from
core.bootstrap.bootstrap_ci: point estimate first, then the
95% percentile bounds.
Source code in recall_guard/portfolio/backtest.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | |
BacktestResult
dataclass
Bundle of both variants and the curves needed for plotting.
equity_curves is cumprod(1 + daily_returns) per variant, so
it is exactly reconstructable from daily_returns_bps (basis
points, ×10⁴) and its terminal value matches total_return_pct.
Source code in recall_guard/portfolio/backtest.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
run_backtest
run_backtest(
records,
prices,
prompt_metadata,
*,
cmmd_quantile=0.8,
fees_one_way=0.00075,
init_cash=1.0,
seed=0,
bootstrap_n=1000,
)
Run the long-short backtest twice (raw + cmmd) on one price matrix.
Args:
records: List of record-shaped objects (see :class:_RecordLike).
Records with parse_ok=False, predicted_direction is
None, raw_confidence is None, or no entry in
prompt_metadata are dropped from BOTH variants
(Req 9.1).
prices: (date × ticker) close-price matrix. Must contain the
BIL column plus at least one risk asset. The DataFrame's
index is treated as the trading-day calendar; signals dated
outside the index are dropped (Req 9.2).
prompt_metadata: Maps each prompt_hash to a dict with
"ticker" and "date" (ISO-8601) keys. Required because
the harness Record schema does not carry date/ticker
inline; the orchestrator builds this dict from the eval-set
rows.
cmmd_quantile: Quantile cut for the cmmd filter (default 0.80,
i.e., drop top quintile by p_memorized).
fees_one_way: One-way trading cost in fractional notional
(default 0.00075 = 7.5 bps; round-trip = 15 bps per the
paper).
init_cash: Initial portfolio value passed to vectorbt (default
1.0 so equity curves start at 1.0).
seed: Threaded through bootstrap CIs for determinism.
bootstrap_n: Resamples for bootstrap_ci (default 1000).
Returns:
A :class:BacktestResult with both variants populated.
Raises:
ValueError: prices is empty or missing the BIL column.
ValueError: cmmd_quantile outside (0, 1).
Source code in recall_guard/portfolio/backtest.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | |
write_backtest_artifacts
write_backtest_artifacts(result, run_dir)
Write the five backtest artifacts to run_dir atomically.
Builds every artifact in memory first, stages each payload to a
temporary sibling file, and only after every temp file is safely on
disk renames them over their targets (os.replace). If anything
raises OSError (disk full, permission denied, etc.) before the
publish phase, the temp files are unlinked and the pre-existing
artifacts in run_dir — including those from an earlier run —
are left byte-for-byte untouched (Req 7.6). The function re-raises
as :class:BacktestArtifactError.
Args:
result: The :class:BacktestResult to serialise.
run_dir: Directory the artifacts should land in. Must exist.
Returns:
{artifact_name: Path} for the five files written. Keys:
backtest_summary_csv, backtest_summary_md,
equity_curves_csv, equity_curves_png,
daily_returns_csv, matching the manifest's
backtest.artifacts block in design.md.
Raises: BacktestArtifactError: any IO failure during the write phase. The run directory is rolled back to its pre-call state.
Source code in recall_guard/portfolio/backtest.py
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 | |