"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(metrics): anchor drawdown to initial equity
warren618125d88ee8744
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.pyindex bbd78dfcb..e6ea5d500 100644--- a/agent/backtest/metrics.py+++ b/agent/backtest/metrics.py@@ -531,8 +531,12 @@ def calc_metrics(sharpe = 0.0# Drawdown- peak = equity_curve.cummax()- dd = (equity_curve - peak) / peak.abs().replace(0, 1)+ # The account starts at ``initial_cash`` before the first recorded bar, so+ # that value is the initial high-water mark. Using only observed equity+ # understates a first-bar loss and makes drawdown nonsensical after equity+ # crosses zero.+ peak = equity_curve.cummax().clip(lower=float(initial_cash))+ dd = (equity_curve - peak) / peak.replace(0, 1)max_dd = float(dd.min())calmar = ann_ret / abs(max_dd) if abs(max_dd) > 1e-10 else 0.0diff --git a/agent/backtest/risk_xray.py b/agent/backtest/risk_xray.pyindex 18189859d..7526e3c43 100644--- a/agent/backtest/risk_xray.py+++ b/agent/backtest/risk_xray.py@@ -204,10 +204,14 @@ def _drawdown(port: pd.Series) -> dict[str, Any]:if port.empty:return {"max_drawdown": None, "max_drawdown_start": None, "max_drawdown_trough": None}equity = (1.0 + port).cumprod()- peak = equity.cummax()- dd = equity / peak - 1.0+ # The portfolio starts at wealth 1 before the first return observation.+ # Keeping that initial high-water mark also preserves the drawdown sign+ # after a sub -100% return sends compounded wealth through zero.+ peak = equity.cummax().clip(lower=1.0)+ dd = (equity - peak) / peaktrough_idx = dd.idxmin()- start_idx = equity.loc[:trough_idx].idxmax()+ pre_trough = equity.loc[:trough_idx]+ start_idx = port.index[0] if float(pre_trough.max()) < 1.0 else pre_trough.idxmax()return {"max_drawdown": _finite(float(dd.loc[trough_idx])),"max_drawdown_start": str(start_idx),diff --git a/agent/tests/test_metrics.py b/agent/tests/test_metrics.pyindex b21101e70..7733eb6cf 100644--- a/agent/tests/test_metrics.py+++ b/agent/tests/test_metrics.py@@ -428,13 +428,31 @@ class TestCalcMetrics:assert m["calmar"] > 0def test_calmar_and_drawdown_negative_equity(self) -> None:- """Negative equity curves must compute negative drawdown and non-zero Calmar, not zero."""+ """An all-negative curve uses initial cash as its high-water mark."""dates = pd.bdate_range("2025-01-01", periods=3)eq = pd.Series([-20.0, -50.0, -100.0], index=dates)m = calc_metrics(eq, [], 100.0, 252)- assert m["max_drawdown"] == pytest.approx(-4.0)+ assert m["max_drawdown"] == pytest.approx(-2.0)assert m["calmar"] < 0+ def test_drawdown_includes_first_bar_loss_from_initial_cash(self) -> None:+ """The first observed equity point is not automatically a new peak."""+ dates = pd.bdate_range("2025-01-01", periods=2)+ eq = pd.Series([80.0, 90.0], index=dates)++ m = calc_metrics(eq, [], 100.0, 252)++ assert m["max_drawdown"] == pytest.approx(-0.2)++ def test_drawdown_remains_defined_after_equity_crosses_zero(self) -> None:+ """A positive high-water mark keeps zero-crossing losses meaningful."""+ dates = pd.bdate_range("2025-01-01", periods=3)+ eq = pd.Series([120.0, 0.0, -20.0], index=dates)++ m = calc_metrics(eq, [], 100.0, 252)++ assert m["max_drawdown"] == pytest.approx(-140.0 / 120.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)diff --git a/agent/tests/test_risk_xray.py b/agent/tests/test_risk_xray.pyindex 73d63b0cd..12636dd86 100644--- a/agent/tests/test_risk_xray.py+++ b/agent/tests/test_risk_xray.py@@ -9,6 +9,7 @@ import pandas as pdimport pytestfrom backtest.risk_xray import (+ _drawdown,average_invested_weights,compute_risk_xray,render_risk_xray_markdown,@@ -119,6 +120,24 @@ def test_max_drawdown_on_hand_built_curve():_assert_strict_json(result)+def test_drawdown_uses_initial_wealth_before_first_return():+ dates = pd.date_range("2026-01-02", periods=2, freq="D")++ result = _drawdown(pd.Series([-0.2, 0.125], index=dates))++ assert result["max_drawdown"] == pytest.approx(-0.2)+ assert result["max_drawdown_start"] == str(dates[0])+++def test_drawdown_remains_negative_after_wealth_crosses_zero():+ dates = pd.date_range("2026-01-02", periods=3, freq="D")++ result = _drawdown(pd.Series([-1.2, 1.5, 1.0], index=dates))++ assert result["max_drawdown"] == pytest.approx(-2.0)+ assert result["max_drawdown_trough"] == str(dates[-1])++def test_expected_shortfall_on_known_tail():returns_closes = [100.0]for ret in [0.01] * 19 + [-0.10]: