"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): monte carlo validation respects venue bars per year
Lanre Shittue0c3d6d2d47c
diff --git a/agent/backtest/validation.py b/agent/backtest/validation.pyindex 729fd5728..574672d44 100644--- a/agent/backtest/validation.py+++ b/agent/backtest/validation.py@@ -32,6 +32,7 @@ def monte_carlo_test(initial_capital: float,n_simulations: int = 1000,seed: int = 42,+ bars_per_year: int = 252,) -> Dict[str, Any]:"""Shuffle trade PnL order to test path significance.@@ -43,6 +44,8 @@ def monte_carlo_test(initial_capital: Starting capital.n_simulations: Number of random permutations.seed: Random seed for reproducibility.+ bars_per_year: Annualisation factor (must match bootstrap_sharpe_ci+ and walk_forward_analysis so the report's Sharpe figures agree).Returns:Dict with actual_sharpe, p_value_sharpe, actual_max_dd,@@ -59,7 +62,7 @@ def monte_carlo_test(return {"error": "need at least 3 trades", "p_value_sharpe": 1.0}pnls = np.array([t.pnl for t in trades])- actual = _path_metrics(pnls, initial_capital)+ actual = _path_metrics(pnls, initial_capital, bars_per_year)rng = np.random.default_rng(seed)sharpe_count = 0@@ -74,7 +77,7 @@ def monte_carlo_test(shuffled = rng.permutation(pnls)if sim_equities is not None:sim_equities[i] = initial_capital + np.cumsum(shuffled)- sim = _path_metrics(shuffled, initial_capital)+ sim = _path_metrics(shuffled, initial_capital, bars_per_year)sim_sharpes.append(sim["sharpe"])if sim["sharpe"] >= actual["sharpe"]:sharpe_count += 1@@ -114,7 +117,9 @@ def monte_carlo_test(return result-def _path_metrics(pnls: np.ndarray, initial_capital: float) -> Dict[str, float]:+def _path_metrics(+ pnls: np.ndarray, initial_capital: float, bars_per_year: int = 252+) -> Dict[str, float]:"""Compute Sharpe and max drawdown from a PnL sequence."""equity = initial_capital + np.cumsum(pnls)if len(equity) > 1:@@ -124,7 +129,7 @@ def _path_metrics(pnls: np.ndarray, initial_capital: float) -> Dict[str, float]:else:returns = np.array([0.0])std = returns.std()- sharpe = float(returns.mean() / (std + 1e-10) * np.sqrt(252))+ sharpe = float(returns.mean() / (std + 1e-10) * np.sqrt(bars_per_year))peak = np.maximum.accumulate(equity)dd = (equity - peak) / np.where(peak > 0, peak, 1.0)max_dd = float(dd.min())@@ -330,6 +335,7 @@ def run_validation(initial_capital,n_simulations=mc_cfg.get("n_simulations", 1000),seed=mc_cfg.get("seed", 42),+ bars_per_year=bars_per_year,)if "bootstrap" in v_cfg:diff --git a/agent/tests/test_validation.py b/agent/tests/test_validation.pyindex 8ce2feabc..154c7dfc5 100644--- a/agent/tests/test_validation.py+++ b/agent/tests/test_validation.py@@ -121,6 +121,22 @@ class TestMonteCarlo:r2 = monte_carlo_test(trades, 1_000_000, n_simulations=100, seed=42)assert r1["p_value_sharpe"] == r2["p_value_sharpe"]+ def test_actual_sharpe_respects_bars_per_year(self) -> None:+ # actual_sharpe must annualise with the caller's bars_per_year, not a+ # hardcoded 252 -- otherwise it silently disagrees with+ # bootstrap_sharpe_ci's Sharpe on a crypto (365) or forex (260) run+ # in the same validation report.+ trades = _make_trades([100, -50, 200, -30, 150, -80, 120, -40, 90, -20])+ default = monte_carlo_test(trades, 1_000_000, n_simulations=50, seed=1)+ crypto = monte_carlo_test(+ trades, 1_000_000, n_simulations=50, seed=1, bars_per_year=365+ )+ assert default["actual_sharpe"] != crypto["actual_sharpe"]+ expected_ratio = (365 / 252) ** 0.5+ assert crypto["actual_sharpe"] == pytest.approx(+ default["actual_sharpe"] * expected_ratio, abs=1e-3+ )+# ---------------------------------------------------------------------------# Bootstrap Sharpe CI@@ -291,6 +307,20 @@ class TestRunValidation:assert "bootstrap" in resultassert "monte_carlo" not in result+ def test_monte_carlo_respects_run_validations_bars_per_year(self) -> None:+ # run_validation resolves bars_per_year once and threads it into+ # bootstrap/walk_forward already; monte_carlo must receive the same+ # value instead of silently annualising at a hardcoded 252.+ eq = _make_equity(100)+ trades = _make_trades([100, -50, 200, -30, 150, -80, 120, -40, 90, -20])+ config = {"validation": {"monte_carlo": {"n_simulations": 50, "seed": 1}}}+ default = run_validation(config, eq, trades, 1_000_000, bars_per_year=252)+ crypto = run_validation(config, eq, trades, 1_000_000, bars_per_year=365)+ expected_ratio = (365 / 252) ** 0.5+ assert crypto["monte_carlo"]["actual_sharpe"] == pytest.approx(+ default["monte_carlo"]["actual_sharpe"] * expected_ratio, abs=1e-3+ )+@pytest.mark.parametrize(("section", "field", "value"),[