Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(metrics): replace inf from pct_change on zero equity

santhreal1993fd3a8472
diff --git a/agent/backtest/validation.py b/agent/backtest/validation.py
index c7694b249..34fcaa42a 100644
--- a/agent/backtest/validation.py
+++ b/agent/backtest/validation.py
@@ -116,7 +116,12 @@ def monte_carlo_test(
def _path_metrics(pnls: np.ndarray, initial_capital: float) -> Dict[str, float]:
"""Compute Sharpe and max drawdown from a PnL sequence."""
equity = initial_capital + np.cumsum(pnls)
- returns = np.diff(equity) / equity[:-1] if len(equity) > 1 else np.array([0.0])
+ if len(equity) > 1:
+ prev = equity[:-1]
+ diff = np.diff(equity)
+ returns = np.where(prev != 0, diff / np.where(prev != 0, prev, 1.0), 0.0)
+ else:
+ returns = np.array([0.0])
std = returns.std()
sharpe = float(returns.mean() / (std + 1e-10) * np.sqrt(252))
peak = np.maximum.accumulate(equity)
@@ -160,7 +165,7 @@ 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}"}
- returns = equity_curve.pct_change().dropna().values
+ returns = equity_curve.pct_change().replace([np.inf, -np.inf], 0.0).dropna().values
if len(returns) < 5:
return {"error": "need at least 5 return observations"}
@@ -240,7 +245,7 @@ def walk_forward_analysis(
# Per-window metrics
ret = float(win_eq.iloc[-1] / win_eq.iloc[0] - 1) if win_eq.iloc[0] > 0 else 0.0
- win_returns = win_eq.pct_change().dropna().values
+ win_returns = win_eq.pct_change().replace([np.inf, -np.inf], 0.0).dropna().values
sharpe = _sharpe(win_returns, bars_per_year) if len(win_returns) > 1 else 0.0
peak = win_eq.cummax()
diff --git a/agent/tests/test_metrics_inf_zero_equity.py b/agent/tests/test_metrics_inf_zero_equity.py
new file mode 100644
index 000000000..cdde1ce55
--- /dev/null
+++ b/agent/tests/test_metrics_inf_zero_equity.py
@@ -0,0 +1,140 @@
+"""Regression: metrics and validation must not produce inf from zero equity.
+
+pct_change() divides by the previous value. When an equity curve hits
+zero (a blown-up account, a liquidation event), pct_change() produces
+inf or -inf. fillna(0.0) only handles NaN, not inf, so the inf
+propagates into std(), mean(), and every downstream metric (Sharpe,
+Sortino, IR), producing NaN or inf results that are silently wrong.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+
+from backtest.metrics import calc_metrics
+from backtest.models import TradeRecord
+from backtest.validation import (
+ _path_metrics,
+ bootstrap_sharpe_ci,
+ monte_carlo_test,
+ walk_forward_analysis,
+)
+
+
+def _trade(pnl: float = 100.0) -> TradeRecord:
+ return TradeRecord(
+ symbol="X",
+ direction=1,
+ entry_price=100.0,
+ exit_price=101.0,
+ entry_time=pd.Timestamp("2025-01-01"),
+ exit_time=pd.Timestamp("2025-01-06"),
+ size=100.0,
+ leverage=1.0,
+ pnl=pnl,
+ pnl_pct=pnl / 100,
+ exit_reason="signal",
+ holding_bars=5,
+ commission=1.0,
+ )
+
+
+def _equity_curve_with_zero(*, initial: float = 10000.0) -> pd.Series:
+ """An equity curve that hits zero then recovers (e.g. a margin call + reset)."""
+ return pd.Series(
+ [initial, initial * 1.01, 0.0, 5000.0, 5050.0, 5100.0],
+ index=pd.date_range("2025-01-01", periods=6, freq="D"),
+ )
+
+
+# --------------------------------------------------------------------------- #
+# calc_metrics
+# --------------------------------------------------------------------------- #
+
+
+def test_calc_metrics_no_inf_on_zero_equity() -> None:
+ """A zero in the equity curve must not produce inf/NaN in any metric."""
+ eq = _equity_curve_with_zero()
+ m = calc_metrics(eq, [], initial_cash=10000.0)
+ for key in ("sharpe", "sortino", "calmar", "annual_return", "max_drawdown"):
+ val = m[key]
+ assert np.isfinite(val), f"{key} is not finite: {val}"
+
+
+def test_calc_metrics_no_inf_on_all_zero_equity() -> None:
+ """An equity curve that is entirely zero must not crash or produce inf."""
+ eq = pd.Series(
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ index=pd.date_range("2025-01-01", periods=5, freq="D"),
+ )
+ m = calc_metrics(eq, [], initial_cash=10000.0)
+ for key in ("sharpe", "sortino", "calmar", "annual_return"):
+ assert np.isfinite(m[key]), f"{key} is not finite: {m[key]}"
+
+
+# --------------------------------------------------------------------------- #
+# validation._path_metrics
+# --------------------------------------------------------------------------- #
+
+
+def test_path_metrics_no_inf_on_zero_equity() -> None:
+ """_path_metrics must not produce inf when equity crosses zero."""
+ pnls = np.array([100.0, -200.0, 50.0]) # equity: 10000, 10100, 9900, 9950
+ 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']}"
+
+
+def test_path_metrics_no_inf_when_equity_hits_zero() -> None:
+ """Equity hitting exactly zero must not produce inf returns."""
+ 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']}"
+
+
+# --------------------------------------------------------------------------- #
+# validation.bootstrap_sharpe_ci
+# --------------------------------------------------------------------------- #
+
+
+def test_bootstrap_sharpe_ci_no_inf_on_zero_equity() -> None:
+ """bootstrap_sharpe_ci must not produce inf when equity hits zero."""
+ eq = _equity_curve_with_zero()
+ result = bootstrap_sharpe_ci(eq, n_bootstrap=50, seed=42)
+ if "error" in result:
+ # Not enough returns is acceptable; the point is no crash/inf.
+ return
+ for key in ("observed_sharpe", "ci_lower", "ci_upper", "median_sharpe"):
+ assert np.isfinite(result[key]), f"{key} is not finite: {result[key]}"
+
+
+# --------------------------------------------------------------------------- #
+# validation.walk_forward_analysis
+# --------------------------------------------------------------------------- #
+
+
+def test_walk_forward_no_inf_on_zero_equity() -> None:
+ """walk_forward_analysis must not produce inf when equity hits zero."""
+ eq = _equity_curve_with_zero()
+ result = walk_forward_analysis(eq, [], n_windows=2)
+ if "error" in result:
+ return
+ for w in result.get("windows", []):
+ assert np.isfinite(w["sharpe"]), f"window sharpe is not finite: {w['sharpe']}"
+ assert np.isfinite(w["max_dd"]), f"window max_dd is not finite: {w['max_dd']}"
+
+
+# --------------------------------------------------------------------------- #
+# monte_carlo_test (uses _path_metrics internally)
+# --------------------------------------------------------------------------- #
+
+
+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']}"