"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Fix crash in backtest metrics on negative final equity
Santhfd59b4a2df71
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.pyindex dcfbb87a4..763bd1d6f 100644--- a/agent/backtest/metrics.py+++ b/agent/backtest/metrics.py@@ -213,7 +213,15 @@ def calc_metrics(port_ret = equity_curve.pct_change().fillna(0.0)total_ret = float(equity_curve.iloc[-1] / initial_cash - 1)- ann_ret = float((1 + total_ret) ** (bpy / max(n, 1)) - 1)+ # A leveraged/short book can end at or below zero equity (``total_ret <= -1``).+ # ``(1 + total_ret) ** fractional`` would then raise a negative base to a+ # fractional power, which Python evaluates to a ``complex`` and crashes the+ # subsequent ``float(...)``. A total wipeout annualises to -100%.+ growth = 1 + total_ret+ if growth <= 0:+ ann_ret = -1.0+ else:+ ann_ret = float(growth ** (bpy / max(n, 1)) - 1)vol = float(port_ret.std())sharpe = float(port_ret.mean() / (vol + 1e-10) * np.sqrt(bpy))diff --git a/agent/tests/test_metrics.py b/agent/tests/test_metrics.pyindex 270f8746f..5ee676e04 100644--- a/agent/tests/test_metrics.py+++ b/agent/tests/test_metrics.py@@ -289,6 +289,28 @@ class TestCalcMetrics:if m["annual_return"] > 0:assert m["calmar"] > 0+ def test_zero_final_equity(self) -> None:+ """A full wipeout (equity reaches 0) annualises to -100%, not a crash."""+ dates = pd.bdate_range("2025-01-01", periods=252)+ eq = pd.Series(np.linspace(1_000_000, 0.0, 252), index=dates)+ m = calc_metrics(eq, [], 1_000_000, 252)+ assert m["total_return"] == pytest.approx(-1.0)+ assert m["annual_return"] == pytest.approx(-1.0)++ def test_negative_final_equity_does_not_crash(self) -> None:+ """A leveraged/short book can end below zero equity (total_return < -1).++ ``(1 + total_return) ** fractional`` would raise a negative base to a+ fractional power (a ``complex``) and crash ``float(...)``; the metric+ must instead report a -100% annualised return.+ """+ dates = pd.bdate_range("2025-01-01", periods=252)+ eq = pd.Series(np.linspace(1_000_000, -500_000, 252), index=dates)+ m = calc_metrics(eq, [], 1_000_000, 252)+ assert m["total_return"] == pytest.approx(-1.5)+ assert m["annual_return"] == pytest.approx(-1.0)+ assert m["final_value"] == pytest.approx(-500_000)+# ---------------------------------------------------------------------------# turnover