"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): measure an explicit benchmark over the evaluated window
Haozhe Wu7af8c2ea6a73
diff --git a/agent/backtest/benchmark.py b/agent/backtest/benchmark.pyindex e9cc8da75..dd236f88d 100644--- a/agent/backtest/benchmark.py+++ b/agent/backtest/benchmark.py@@ -34,7 +34,33 @@ MARKET_BENCHMARKS: dict[str, Optional[str]] = {class BenchmarkResult:ticker: strret_series: pd.Series # per-bar returns, index = timestamps- total_ret: float # total return over the period+ total_ret: float # total return over the FETCHED period+ close: pd.Series # benchmark closes, index = timestamps++ def total_return_over(self, dates: pd.DatetimeIndex) -> Optional[float]:+ """Return the buy-and-hold return restricted to ``dates``.++ ``total_ret`` spans everything that was fetched, which is the requested+ ``start_date``..``end_date``. When the run declares a warm-up boundary+ the evaluated window is shorter than that, and grading a strategy over+ the short window against a benchmark measured over the long one is the+ mismatched-window error the warm-up boundary exists to prevent (#1240).++ Computed as a price relative rather than the compounded product of+ ``ret_series``, which is the only form that stays honest once a price+ series contains a non-positive prior close (#872).++ Args:+ dates: The evaluated bar index.++ Returns:+ The buy-and-hold return over the overlap, or ``None`` when fewer+ than two benchmark closes fall inside it.+ """+ window = self.close.reindex(dates).dropna()+ if len(window) < 2:+ return None+ return buy_and_hold_return(window)def resolve_benchmark(@@ -99,7 +125,9 @@ def resolve_benchmark(if total is None:return None- return BenchmarkResult(ticker=ticker, ret_series=ret_series, total_ret=total)+ return BenchmarkResult(+ ticker=ticker, ret_series=ret_series, total_ret=total, close=close+ )# -------------------------------------------------------------------diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex c7f5db20c..218f1be4d 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -912,9 +912,20 @@ class BaseEngine(ABC):)if bench_result is not None:bench_ret = bench_result.ret_series.reindex(dates).fillna(0.0)+ # The benchmark is fetched over the requested start_date..+ # end_date, but a declared warm-up boundary makes the EVALUATED+ # window shorter than that (`dates` is already clipped above).+ # Grading total_return over the short window against a+ # benchmark measured over the long one is the mismatched-window+ # error the warm-up boundary exists to prevent, so re-measure+ # the benchmark over the same bars. Falls back to the fetched+ # total only when the overlap is too short to measure.+ window_ret = bench_result.total_return_over(dates)benchmark_metadata = {"benchmark_ticker": bench_result.ticker,- "benchmark_return": bench_result.total_ret,+ "benchmark_return": (+ window_ret if window_ret is not None else bench_result.total_ret+ ),}# ── External benchmark fetch ──────────────────────────────────────────diff --git a/agent/tests/test_benchmark_excess_return_consistency.py b/agent/tests/test_benchmark_excess_return_consistency.pyindex 41d34b54a..864dadee0 100644--- a/agent/tests/test_benchmark_excess_return_consistency.py+++ b/agent/tests/test_benchmark_excess_return_consistency.py@@ -67,6 +67,7 @@ def test_excess_return_matches_corrected_benchmark_return(monkeypatch, tmp_path)ticker="BENCH",ret_series=bar_returns(bench_close, label="test-benchmark"),total_ret=buy_and_hold_return(bench_close),+ close=bench_close,)assert fake_result.total_ret == pytest.approx(-0.5)diff --git a/agent/tests/test_engine_robustness.py b/agent/tests/test_engine_robustness.pyindex 26cee5535..da6626144 100644--- a/agent/tests/test_engine_robustness.py+++ b/agent/tests/test_engine_robustness.py@@ -216,10 +216,17 @@ class TestSymbolIsolation:return {"000001.SZ": pd.Series(0.0, index=data_map["000001.SZ"].index)}def fake_resolve_benchmark(**kwargs):- return SimpleNamespace(+ # The real result type, not a namespace: the engine re-measures the+ # benchmark over the evaluated window via BenchmarkResult's own+ # method, so a stub that only carries attributes would not exercise+ # the path under test.+ from backtest.benchmark import BenchmarkResult++ return BenchmarkResult(ticker="000300.SH",ret_series=pd.Series([0.0, 0.01, -0.005], index=dates),total_ret=0.00495,+ close=pd.Series([100.0, 101.0, 100.495], index=dates),)monkeypatch.setattr("backtest.benchmark.resolve_benchmark", fake_resolve_benchmark)diff --git a/agent/tests/test_warmup_window.py b/agent/tests/test_warmup_window.pyindex 6f3d88716..c42fefcb7 100644--- a/agent/tests/test_warmup_window.py+++ b/agent/tests/test_warmup_window.py@@ -239,3 +239,101 @@ class TestOptionsEngineHonoursTheBoundary:after_warmup = self._run(tmp_path / "b", {"warmup_bars": 3}) / "trades.csv"assert pd.read_csv(after_warmup).empty+++class TestExplicitBenchmarkIsMeasuredOverTheEvaluatedWindow:+ """The explicit-benchmark path measured the benchmark over the FETCHED window.++ ``resolve_benchmark`` fetches ``start_date``..``end_date`` and reports the+ buy-and-hold return over all of it. The per-bar ``ret_series`` was reindexed+ onto the clipped evaluation dates, but ``benchmark_return`` — and therefore+ the ``excess_return`` derived from it — kept the full-window number. A run+ that declared a warm-up then compared its own short-window total_return+ against a benchmark measured over the longer window: the same+ mismatched-window error #1240 exists to prevent, surviving inside the fix+ for it. Only ``benchmark="auto"`` (the mean of the already-clipped return+ frame) was correct.+ """++ boundary = 60++ @staticmethod+ def _frame(n=260):+ idx = pd.bdate_range("2024-01-01", periods=n)+ # Strategy prices: a clean uptrend so the run trades and is gradeable.+ price = pd.Series(np.linspace(100.0, 160.0, n), index=idx)+ return pd.DataFrame(+ {+ "open": price,+ "high": price * 1.001,+ "low": price * 0.999,+ "close": price,+ "volume": 1_000.0,+ },+ index=idx,+ )++ def _run(self, tmp_path, extra, bench_close):+ from backtest import benchmark as bench_mod+ from backtest.benchmark import BenchmarkResult+ from backtest.metrics import bar_returns, buy_and_hold_return++ frame = self._frame()+ engine = _Engine({"initial_cash": 100_000.0})+ result = BenchmarkResult(+ ticker="SPY",+ ret_series=bar_returns(bench_close, label="bench"),+ total_ret=buy_and_hold_return(bench_close),+ close=bench_close,+ )+ original = bench_mod.resolve_benchmark+ bench_mod.resolve_benchmark = lambda **kwargs: result+ try:+ metrics = engine.run_backtest(+ {+ "codes": ["AAA"],+ "start_date": str(frame.index[0].date()),+ "end_date": str(frame.index[-1].date()),+ "benchmark": "SPY",+ **extra,+ },+ _Loader({"AAA": frame}),+ _MovingAverageCross(30),+ tmp_path,+ )+ finally:+ bench_mod.resolve_benchmark = original+ return metrics, frame++ def test_benchmark_return_excludes_the_warmup_window(self, tmp_path):+ frame = self._frame()+ # The benchmark doubles inside the warm-up and is flat afterwards, so+ # the full-window and evaluated-window numbers cannot be confused.+ bench = pd.Series(100.0, index=frame.index)+ bench.iloc[: self.boundary] = np.linspace(100.0, 200.0, self.boundary)+ bench.iloc[self.boundary :] = 200.0++ graded_all, _ = self._run(tmp_path / "a", {}, bench)+ graded_after, _ = self._run(+ tmp_path / "b", {"warmup_bars": self.boundary}, bench+ )++ # Full window: 100 -> 200 = +100%.+ assert graded_all["benchmark_return"] == pytest.approx(1.0, abs=1e-6)+ # Evaluated window: the benchmark is flat at 200 throughout = 0%.+ assert graded_after["benchmark_return"] == pytest.approx(0.0, abs=1e-6)++ def test_excess_return_uses_the_same_window_as_total_return(self, tmp_path):+ frame = self._frame()+ bench = pd.Series(100.0, index=frame.index)+ bench.iloc[: self.boundary] = np.linspace(100.0, 200.0, self.boundary)+ bench.iloc[self.boundary :] = 200.0++ metrics, _ = self._run(tmp_path, {"warmup_bars": self.boundary}, bench)++ assert metrics["excess_return"] == pytest.approx(+ round(metrics["total_return"] - metrics["benchmark_return"], 6), abs=1e-6+ )+ # And the strategy's own window really is the short one, or the+ # assertion above would hold trivially for the full window too.+ assert metrics["benchmark_return"] == pytest.approx(0.0, abs=1e-6)