Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(validation): annualise standalone revalidation with the run's bars per year (#1915)

Rudy Mizrahi Celekli2d4860285c68
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ec78e9339..7afab180a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -50,6 +50,11 @@ optional dependencies before retrying. Explicit-only sources retain their
existing currency and fallback boundaries. Missing observations are never
replaced with invented prices or financial fields.
+Standalone revalidation reuses the annualisation factor saved in the run card,
+including the runner's corrections for actual bar spacing. For older cards
+without that field, it reconstructs the factor from the saved configuration and
+equity timestamps; the original per-symbol price indexes are not available.
+
For AI-assisted or automation-assisted contributions, also see
[`AGENT_CONTRIBUTOR_GUIDE.md`](AGENT_CONTRIBUTOR_GUIDE.md). It summarizes safe
local checks, higher-risk broker/MCP/credential surfaces, and the expected PR
diff --git a/agent/backtest/run_card.py b/agent/backtest/run_card.py
index c3fed1c4b..1aa03fc79 100644
--- a/agent/backtest/run_card.py
+++ b/agent/backtest/run_card.py
@@ -219,6 +219,8 @@ def write_run_card(
"model_provenance": model_provenance,
"artifacts": _list_artifacts(run_dir),
}
+ if "_run_card_bars_per_year" in config:
+ card["annualisation"] = {"bars_per_year": config["_run_card_bars_per_year"]}
normalized_refs = _normalize_artifact_refs(artifact_refs)
if normalized_refs:
card["artifact_refs"] = normalized_refs
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index 98c79d5c9..9b29ac0bc 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -1502,6 +1502,7 @@ def main(run_dir: Path) -> None:
)
if annualisation_warnings:
config["_run_card_annualisation_warning"] = annualisation_warnings[0]
+ config["_run_card_bars_per_year"] = bars_per_year
# Every source has already been fetched, sanitized, and enriched above.
# Reuse that exact snapshot so provider costs and run-card provenance stay
diff --git a/agent/backtest/validation.py b/agent/backtest/validation.py
index 073bef8e1..d5fbfab01 100644
--- a/agent/backtest/validation.py
+++ b/agent/backtest/validation.py
@@ -520,6 +520,46 @@ def write_validation_json(path: Path, results: Dict[str, Any]) -> Dict[str, Any]
return safe_results
+def _saved_bars_per_year(config: Dict[str, Any], equity: pd.Series, run_dir: Path) -> int | None:
+ """Annualisation factor for a saved run, chosen the way the runner chose it.
+
+ The engine passes the run's ``bars_per_year`` into :func:`run_validation`;
+ Prefer the factor recorded by the runner after checking the served bars.
+ For legacy cards, apply the runner's spacing check to the saved equity
+ index. This is a reconstruction: the original per-symbol price indexes
+ are not available. A config without codes keeps the historical default.
+
+ Args:
+ config: The saved run config.
+ equity: Saved equity observations for the legacy spacing fallback.
+ run_dir: Directory containing the optional run card.
+
+ Returns:
+ Bars per year, or ``None`` for calendar-day annualisation.
+ """
+ card_path = run_dir / "run_card.json"
+ if card_path.exists():
+ card = json.loads(card_path.read_text(encoding="utf-8"))
+ if "annualisation" in card:
+ value = card["annualisation"]["bars_per_year"]
+ if value is None:
+ return None
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ raise ValueError("run-card bars_per_year must be a positive integer or null")
+ return value
+ codes = [code for code in config.get("codes") or [] if isinstance(code, str) and code]
+ if not codes:
+ return 252
+ from backtest.runner import _annualisation_bars, _detect_market, _detect_primary_source
+
+ if len({_detect_market(code) for code in codes}) > 1:
+ return None
+ source = _detect_primary_source(codes, config.get("source", "tushare"))
+ return _annualisation_bars(
+ config.get("interval", "1D"), source, {"equity": equity.to_frame()}, ["equity"]
+ )
+
+
def main(run_dir: Path) -> Dict[str, Any]:
"""Run all three validations on existing backtest artifacts.
@@ -549,7 +589,10 @@ def main(run_dir: Path) -> Dict[str, Any]:
saved_settings = config.get("validation")
if isinstance(saved_settings, dict):
settings.update(saved_settings)
- results = run_validation({"validation": settings}, equity, trades, initial_capital)
+ results = run_validation(
+ {"validation": settings}, equity, trades, initial_capital,
+ _saved_bars_per_year(config, equity, run_dir),
+ )
out = run_dir / "artifacts" / "validation.json"
safe_results = write_validation_json(out, results)
diff --git a/agent/tests/test_validation_cli_settings.py b/agent/tests/test_validation_cli_settings.py
index 10b436959..bc6334136 100644
--- a/agent/tests/test_validation_cli_settings.py
+++ b/agent/tests/test_validation_cli_settings.py
@@ -122,3 +122,67 @@ def test_invalid_saved_settings_use_existing_errors(
assert message in actual[tool]["error"]
capsys.readouterr()
+
+
+ "run_config, annualisation",
+ [
+ ({"source": "okx", "interval": "1H", "codes": ["BTC-USDT"]}, "interval"),
+ ({"source": "tushare", "interval": "1D", "codes": ["000001.SZ"]}, "interval"),
+ ({"source": "auto", "interval": "1D", "codes": ["000001.SZ", "BTC-USDT"]}, "calendar"),
+ ],
+)
+def test_main_annualises_like_the_saved_run(tmp_path: Path, capsys, run_config, annualisation) -> None:
+ from backtest.metrics import calc_bars_per_year
+
+ settings = {
+ "monte_carlo": {"n_simulations": 5, "seed": 1},
+ "bootstrap": {"n_bootstrap": 5, "seed": 2},
+ "walk_forward": {"n_windows": 2},
+ }
+ config = {"initial_cash": 1000, "validation": settings, **run_config}
+ _write_run(tmp_path, config)
+ if run_config["interval"] == "1H":
+ equity = pd.read_csv(tmp_path / "artifacts/equity.csv", index_col=0)
+ equity.index = pd.date_range("2026-01-01", periods=len(equity), freq="h")
+ equity.to_csv(tmp_path / "artifacts/equity.csv")
+ if annualisation == "calendar":
+ bars = None
+ else:
+ bars = calc_bars_per_year(run_config["interval"], run_config["source"])
+
+ actual = validation.main(tmp_path)
+ capsys.readouterr()
+
+ expected = validation.run_validation(
+ config, validation._load_equity(tmp_path), validation._load_trades(tmp_path), 1000, bars
+ )
+ assert actual["bootstrap"]["observed_sharpe"] == expected["bootstrap"]["observed_sharpe"]
+ assert actual == expected
+
+
[email protected]("factor", [52, 365, None])
+def test_recorded_annualisation_round_trips(tmp_path: Path, factor) -> None:
+ from backtest.run_card import write_run_card
+
+ config = {"codes": ["BTC-USDT"], "source": "okx", "interval": "1H"}
+ _write_run(tmp_path, config)
+ write_run_card(tmp_path, {**config, "_run_card_bars_per_year": factor}, {})
+ assert validation._saved_bars_per_year(
+ config, validation._load_equity(tmp_path), tmp_path
+ ) == factor
+
+
+def test_legacy_daily_bars_override_hourly_declaration(tmp_path: Path) -> None:
+ config = {"codes": ["BTC-USDT"], "source": "okx", "interval": "1H"}
+ _write_run(tmp_path, config)
+ assert validation._saved_bars_per_year(
+ config, validation._load_equity(tmp_path), tmp_path
+ ) == 365
+
+
[email protected]("factor", [0, -1, True, "365", float("nan")])
+def test_invalid_recorded_factor_is_not_silently_replaced(tmp_path: Path, factor) -> None:
+ (tmp_path / "run_card.json").write_text(json.dumps({"annualisation": {"bars_per_year": factor}}))
+ with pytest.raises(ValueError, match="bars_per_year"):
+ validation._saved_bars_per_year({}, pd.Series(dtype=float), tmp_path)