"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): validate validation parameter types
Haozhe Wu1b8f843505ef
diff --git a/agent/backtest/validation.py b/agent/backtest/validation.pyindex 33a69b3ba..3473e8ffb 100644--- a/agent/backtest/validation.py+++ b/agent/backtest/validation.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport jsonimport math+from numbers import Integral, Realfrom pathlib import Pathfrom typing import Any, Dict, List@@ -46,12 +47,12 @@ def monte_carlo_test(Dict with actual_sharpe, p_value_sharpe, actual_max_dd,p_value_max_dd, simulated_sharpes (percentiles)."""- if n_simulations < 1:+ if isinstance(n_simulations, bool) or not isinstance(n_simulations, Integral) or n_simulations < 1:return {"error": f"n_simulations must be >= 1, got {n_simulations}","p_value_sharpe": 1.0,}- if seed < 0:+ if isinstance(seed, bool) or not isinstance(seed, Integral) or seed < 0:return {"error": f"seed must be >= 0, got {seed}", "p_value_sharpe": 1.0}if len(trades) < 3:return {"error": "need at least 3 trades", "p_value_sharpe": 1.0}@@ -123,11 +124,16 @@ def bootstrap_sharpe_ci(Dict with observed_sharpe, ci_lower, ci_upper, median_sharpe,prob_positive (fraction of samples with Sharpe > 0)."""- if n_bootstrap < 1:+ if isinstance(n_bootstrap, bool) or not isinstance(n_bootstrap, Integral) or n_bootstrap < 1:return {"error": f"n_bootstrap must be >= 1, got {n_bootstrap}"}- if not 0.0 < confidence < 1.0:+ if (+ isinstance(confidence, bool)+ or not isinstance(confidence, Real)+ or not math.isfinite(float(confidence))+ or not 0.0 < confidence < 1.0+ ):return {"error": f"confidence must be in (0, 1), got {confidence}"}- if seed < 0:+ if isinstance(seed, bool) or not isinstance(seed, Integral) or seed < 0:return {"error": f"seed must be >= 0, got {seed}"}returns = equity_curve.pct_change().dropna().values@@ -186,7 +192,7 @@ def walk_forward_analysis(Returns:Dict with per_window stats, consistency metrics."""- if n_windows < 1:+ if isinstance(n_windows, bool) or not isinstance(n_windows, Integral) or n_windows < 1:return {"error": f"n_windows must be >= 1, got {n_windows}"}if len(equity_curve) < n_windows * 2:return {"error": f"need at least {n_windows * 2} bars for {n_windows} windows"}diff --git a/agent/tests/test_validation.py b/agent/tests/test_validation.pyindex 340ca2a64..d04d1d02c 100644--- a/agent/tests/test_validation.py+++ b/agent/tests/test_validation.py@@ -96,18 +96,19 @@ class TestMonteCarlo:result = monte_carlo_test(trades, 1_000_000)assert "error" in result- @pytest.mark.parametrize("n_simulations", [0, -1, -100])- def test_non_positive_simulations_errors(self, n_simulations: int) -> None:+ @pytest.mark.parametrize("n_simulations", [0, -1, -100, 1.5, "10", True])+ def test_invalid_simulations_errors(self, n_simulations: object) -> None:"""A non-positive n_simulations must not raise (was ZeroDivisionError)."""trades = _make_trades([100, -50, 200, -30, 150])result = monte_carlo_test(trades, 1_000_000, n_simulations=n_simulations)assert "error" in resultassert result["p_value_sharpe"] == 1.0- def test_negative_seed_errors(self) -> None:- """A negative seed must not raise (default_rng rejects it)."""+ @pytest.mark.parametrize("seed", [-1, 1.5, "42", True])+ def test_invalid_seed_errors(self, seed: object) -> None:+ """An invalid seed must not escape as an opaque numpy error."""trades = _make_trades([100, -50, 200, -30, 150])- result = monte_carlo_test(trades, 1_000_000, n_simulations=10, seed=-1)+ result = monte_carlo_test(trades, 1_000_000, n_simulations=10, seed=seed)assert "error" in resultdef test_reproducibility(self) -> None:@@ -151,24 +152,25 @@ class TestBootstrapSharpe:result = bootstrap_sharpe_ci(eq, n_bootstrap=100)assert "error" in result- @pytest.mark.parametrize("n_bootstrap", [0, -1, -50])- def test_non_positive_bootstrap_errors(self, n_bootstrap: int) -> None:+ @pytest.mark.parametrize("n_bootstrap", [0, -1, -50, 1.5, "10", True])+ def test_invalid_bootstrap_errors(self, n_bootstrap: object) -> None:"""A non-positive n_bootstrap must not raise (was IndexError from percentile)."""eq = _make_equity(100)result = bootstrap_sharpe_ci(eq, n_bootstrap=n_bootstrap)assert "error" in result- @pytest.mark.parametrize("confidence", [0.0, 1.0, 1.5, -0.2])- def test_confidence_out_of_range_errors(self, confidence: float) -> None:+ @pytest.mark.parametrize("confidence", [0.0, 1.0, 1.5, -0.2, float("inf"), float("nan"), "0.95", True])+ def test_invalid_confidence_errors(self, confidence: object) -> None:"""A confidence outside (0, 1) must not raise (was percentile ValueError)."""eq = _make_equity(100)result = bootstrap_sharpe_ci(eq, confidence=confidence, n_bootstrap=100)assert "error" in result- def test_negative_seed_errors(self) -> None:- """A negative seed must not raise (default_rng rejects it)."""+ @pytest.mark.parametrize("seed", [-1, 1.5, "42", True])+ def test_invalid_seed_errors(self, seed: object) -> None:+ """An invalid seed must not escape as an opaque numpy error."""eq = _make_equity(100)- result = bootstrap_sharpe_ci(eq, n_bootstrap=10, seed=-1)+ result = bootstrap_sharpe_ci(eq, n_bootstrap=10, seed=seed)assert "error" in resultdef test_reproducibility(self) -> None:@@ -238,8 +240,8 @@ class TestWalkForward:result = walk_forward_analysis(eq, [], n_windows=5)assert "error" in result- @pytest.mark.parametrize("n_windows", [0, -1, -3])- def test_non_positive_windows_errors(self, n_windows: int) -> None:+ @pytest.mark.parametrize("n_windows", [0, -1, -3, 1.5, "5", True])+ def test_invalid_windows_errors(self, n_windows: object) -> None:"""A non-positive n_windows must not raise or silently return garbage.n_windows=0 raised ZeroDivisionError; a negative value silently returned@@ -284,3 +286,25 @@ class TestRunValidation:result = run_validation(config, eq, trades, 1_000_000)assert "bootstrap" in resultassert "monte_carlo" not in result++ @pytest.mark.parametrize(+ ("section", "field", "value"),+ [+ ("monte_carlo", "n_simulations", "10"),+ ("monte_carlo", "seed", 1.5),+ ("bootstrap", "n_bootstrap", True),+ ("bootstrap", "confidence", float("inf")),+ ("walk_forward", "n_windows", "5"),+ ],+ )+ def test_malformed_nested_config_returns_error(+ self, section: str, field: str, value: object+ ) -> None:+ """Raw nested config values fail visibly instead of raising."""+ result = run_validation(+ {"validation": {section: {field: value}}},+ _make_equity(100),+ _make_trades([100, -50, 200]),+ 1_000_000,+ )+ assert "error" in result[section]