Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(validation): leave undefined statistical results absent

Haozhe Wud5a0c4753876
diff --git a/agent/backtest/validation.py b/agent/backtest/validation.py
index d5fbfab01..2fc8f061c 100644
--- a/agent/backtest/validation.py
+++ b/agent/backtest/validation.py
@@ -7,6 +7,9 @@ Three independent tools:
Usage: called automatically by BaseEngine.run_backtest when config[\"validation\"]
is present, or invoked directly on backtest outputs.
+
+Percentage-based validation requires positive, finite observed equity.
+An undefined calculation returns only an error, never a numeric placeholder.
"""
from __future__ import annotations
@@ -54,15 +57,16 @@ def monte_carlo_test(
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 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}
+ return {"error": f"seed must be >= 0, got {seed}"}
if len(trades) < 3:
- return {"error": "need at least 3 trades", "p_value_sharpe": 1.0}
+ return {"error": "need at least 3 trades"}
pnls = np.array([t.pnl for t in trades])
actual = _path_metrics(pnls, initial_capital, bars_per_year)
+ if actual is None:
+ return {"error": "Monte Carlo requires positive finite equity at every observed trade step"}
rng = np.random.default_rng(seed)
sharpe_count = 0
@@ -78,6 +82,8 @@ def monte_carlo_test(
if sim_equities is not None:
sim_equities[i] = initial_capital + np.cumsum(shuffled)
sim = _path_metrics(shuffled, initial_capital, bars_per_year)
+ if sim is None:
+ return {"error": f"Monte Carlo requires positive finite equity at every simulated trade step (simulation {i + 1})"}
sim_sharpes.append(sim["sharpe"])
if sim["sharpe"] >= actual["sharpe"]:
sharpe_count += 1
@@ -119,11 +125,13 @@ def monte_carlo_test(
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."""
+) -> Dict[str, float] | None:
+ """Compute path metrics, or return None when percentage returns are undefined."""
# Include starting cash so the first trade contributes to returns and
# drawdown in both the observed path and every shuffled path.
equity = np.concatenate(([initial_capital], initial_capital + np.cumsum(pnls)))
+ if not np.isfinite(equity).all() or (equity <= 0).any():
+ return None
if len(equity) > 1:
prev = equity[:-1]
diff = np.diff(equity)
@@ -179,6 +187,12 @@ def bootstrap_sharpe_ci(
if isinstance(seed, bool) or not isinstance(seed, Integral) or seed < 0:
return {"error": f"seed must be >= 0, got {seed}"}
+ observed = equity_curve.dropna()
+ if not np.isfinite(observed).all() or (observed <= 0).any():
+ return {"error": "Bootstrap Sharpe CI requires positive finite observed equity"}
+ if initial_capital is not None and (not math.isfinite(initial_capital) or initial_capital <= 0):
+ return {"error": "Bootstrap Sharpe CI requires positive finite initial capital"}
+
if initial_capital is not None:
series = period_returns(equity_curve, initial_capital)
else:
@@ -265,6 +279,9 @@ def walk_forward_analysis(
win_end = indices[end_idx - 1]
if not np.isfinite(win_eq.iloc[[0, -1]]).all():
return {"error": f"window {i + 1} requires observed start and end equity"}
+ observed = win_eq.dropna()
+ if not np.isfinite(observed).all() or (observed <= 0).any():
+ return {"error": f"window {i + 1} requires positive finite observed equity"}
# Per-window trades
win_trades = [t for t in trades if win_start <= t.entry_time <= win_end]
diff --git a/agent/tests/test_metrics_inf_zero_equity.py b/agent/tests/test_metrics_inf_zero_equity.py
index cdde1ce55..6e98b098e 100644
--- a/agent/tests/test_metrics_inf_zero_equity.py
+++ b/agent/tests/test_metrics_inf_zero_equity.py
@@ -87,11 +87,10 @@ def test_path_metrics_no_inf_on_zero_equity() -> None:
def test_path_metrics_no_inf_when_equity_hits_zero() -> None:
- """Equity hitting exactly zero must not produce inf returns."""
+ """Equity hitting zero has no defined percentage path metrics."""
pnls = np.array([100.0, -10100.0, 5000.0]) # equity: 10000, 10100, 0, 5000
m = _path_metrics(pnls, initial_capital=10000.0)
- assert np.isfinite(m["sharpe"]), f"sharpe is not finite: {m['sharpe']}"
- assert np.isfinite(m["max_dd"]), f"max_dd is not finite: {m['max_dd']}"
+ assert m is None
# --------------------------------------------------------------------------- #
@@ -135,6 +134,4 @@ def test_monte_carlo_no_inf_when_trades_blow_up_account() -> None:
"""Monte Carlo must not produce inf when trades push equity through zero."""
trades = [_trade(100.0), _trade(-10100.0), _trade(5000.0), _trade(50.0)]
result = monte_carlo_test(trades, initial_capital=10000.0, n_simulations=50, seed=42)
- assert np.isfinite(result["actual_sharpe"]), f"actual_sharpe not finite: {result['actual_sharpe']}"
- assert np.isfinite(result["actual_max_dd"]), f"actual_max_dd not finite: {result['actual_max_dd']}"
- assert np.isfinite(result["p_value_sharpe"]), f"p_value_sharpe not finite: {result['p_value_sharpe']}"
+ assert set(result) == {"error"}
diff --git a/agent/tests/test_validation.py b/agent/tests/test_validation.py
index 154c7dfc5..fcfabc8bf 100644
--- a/agent/tests/test_validation.py
+++ b/agent/tests/test_validation.py
@@ -106,7 +106,7 @@ class TestMonteCarlo:
trades = _make_trades([100, -50, 200, -30, 150])
result = monte_carlo_test(trades, 1_000_000, n_simulations=n_simulations)
assert "error" in result
- assert result["p_value_sharpe"] == 1.0
+ assert "p_value_sharpe" not in result
@pytest.mark.parametrize("seed", [-1, 1.5, "42", True])
def test_invalid_seed_errors(self, seed: object) -> None:
@@ -482,3 +482,36 @@ class TestBarsPerYearNone:
bars_per_year=None,
)
assert "bootstrap" in result
+
+
[email protected]("pnls", [[-150, -25, -25], [100, -150, 100], [float('nan'), 10, 20]])
+def test_unmeasurable_monte_carlo_has_no_numeric_result(tmp_path, pnls):
+ from src.agent.grounding.evidence import _summary_scalars
+
+ result = monte_carlo_test(_make_trades(pnls), 100, n_simulations=50, seed=42)
+ assert set(result) == {"error"}
+ path = tmp_path / "validation.json"
+ write_validation_json(path, {"monte_carlo": result})
+ assert _summary_scalars(path) == []
+
+
[email protected]("kwargs", [{"n_simulations": 0}, {"seed": -1}, {}])
+def test_invalid_monte_carlo_request_has_no_p_value(kwargs):
+ result = monte_carlo_test(_make_trades([10, -5]), 100, **kwargs)
+ assert set(result) == {"error"}
+
+
[email protected]("bad", [0.0, -50.0, float("inf"), -float("inf")])
+def test_validation_rejects_nonpositive_or_infinite_observed_equity(bad):
+ equity = pd.Series([100, 110, 105, bad, 115, 120, 125, 130],
+ index=pd.bdate_range("2026-01-01", periods=8))
+ for result in (bootstrap_sharpe_ci(equity, n_bootstrap=20),
+ walk_forward_analysis(equity, [], n_windows=2)):
+ assert set(result) == {"error"}
+
+
[email protected]("initial", [0, -1, float("nan"), float("inf")])
+def test_validation_requires_positive_finite_starting_capital(initial):
+ equity = _make_equity(20)
+ assert set(bootstrap_sharpe_ci(equity, n_bootstrap=20, initial_capital=initial)) == {"error"}
+ assert set(monte_carlo_test(_make_trades([10, 20, 30]), initial, n_simulations=20)) == {"error"}
diff --git a/frontend/src/components/charts/ValidationPanel.tsx b/frontend/src/components/charts/ValidationPanel.tsx
index 4a5ae8a21..01e4f4f8f 100644
--- a/frontend/src/components/charts/ValidationPanel.tsx
+++ b/frontend/src/components/charts/ValidationPanel.tsx
@@ -41,7 +41,7 @@ function pctFmt(v: number): string {
}
function MonteCarloSection({ mc }: { mc: NonNullable<ValidationData["monte_carlo"]> }) {
- if (mc.error) return <p className="text-sm text-muted-foreground">{mc.error}</p>;
+ if ("error" in mc) return <p className="text-sm text-muted-foreground">{mc.error}</p>;
const sig = mc.p_value_sharpe < 0.05;
return (
<div className="space-y-3">
diff --git a/frontend/src/components/charts/__tests__/ValidationPanel.test.tsx b/frontend/src/components/charts/__tests__/ValidationPanel.test.tsx
new file mode 100644
index 000000000..d3e5167a6
--- /dev/null
+++ b/frontend/src/components/charts/__tests__/ValidationPanel.test.tsx
@@ -0,0 +1,11 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { ValidationPanel } from "../ValidationPanel";
+
+describe("undefined validation results", () => {
+ it("renders an error-only Monte Carlo result without inventing a p-value", () => {
+ render(<ValidationPanel data={{ monte_carlo: { error: "Equity must remain positive" } }} />);
+ expect(screen.getByText("Equity must remain positive")).toBeInTheDocument();
+ expect(screen.queryByText("1.0000")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 9c839da20..4f6e6b1c9 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1310,8 +1310,7 @@ export interface ValidationData {
n_trades: number;
sharpe_samples?: number[];
equity_paths?: MonteCarloEquityPaths;
- error?: string;
- };
+ } | { error: string };
bootstrap?: {
observed_sharpe: number;
ci_lower: number;