"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): keep Sharpe and information ratio finite for single-bar runs
Santh960f186c0453
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.pyindex 763bd1d6f..ee8cc8df3 100644--- a/agent/backtest/metrics.py+++ b/agent/backtest/metrics.py@@ -222,7 +222,10 @@ def calc_metrics(ann_ret = -1.0else:ann_ret = float(growth ** (bpy / max(n, 1)) - 1)- vol = float(port_ret.std())+ # ``Series.std()`` uses ddof=1, so a single-observation return series+ # (e.g. a one-bar backtest) yields NaN and poisons the Sharpe ratio.+ # Guard the small sample the same way ``downside_std`` is guarded below.+ vol = float(port_ret.std()) if len(port_ret) > 1 else 0.0sharpe = float(port_ret.mean() / (vol + 1e-10) * np.sqrt(bpy))# Drawdown@@ -252,7 +255,9 @@ def calc_metrics(bench_return = float((1 + bench_ret).prod() - 1)excess = total_ret - bench_returnactive_ret = port_ret - bench_ret.reindex(port_ret.index).fillna(0.0)- active_std = float(active_ret.std())+ # Same ddof=1 small-sample guard as ``vol`` / ``downside_std`` so the+ # information ratio stays finite for a single-observation series.+ active_std = float(active_ret.std()) if len(active_ret) > 1 else 0.0ir = float(active_ret.mean() / (active_std + 1e-10) * np.sqrt(bpy))return {diff --git a/agent/tests/test_metrics.py b/agent/tests/test_metrics.pyindex 5ee676e04..9a75922bb 100644--- a/agent/tests/test_metrics.py+++ b/agent/tests/test_metrics.py@@ -9,6 +9,8 @@ Validates:from __future__ import annotations+import math+import numpy as npimport pandas as pdimport pytest@@ -265,6 +267,20 @@ class TestCalcMetrics:assert m["final_value"] == 1_000_000assert m["total_return"] == 0+ def test_single_bar_equity_metrics_finite(self) -> None:+ # A one-bar backtest yields a single-observation return series.+ # ``Series.std()`` (ddof=1) is NaN for a single element, which used+ # to poison Sharpe and the information ratio (Sortino was already+ # guarded). Every risk metric must stay finite.+ eq = pd.Series([1_000_000.0], index=pd.bdate_range("2025-01-01", periods=1))+ bench_ret = pd.Series([0.0], index=eq.index)+ m = calc_metrics(eq, [], 1_000_000, 252, bench_ret=bench_ret)+ for key in ("sharpe", "sortino", "information_ratio",+ "annual_return", "max_drawdown", "calmar"):+ assert math.isfinite(m[key]), f"{key} is not finite: {m[key]!r}"+ assert m["sharpe"] == 0.0+ assert m["information_ratio"] == 0.0+def test_final_value(self) -> None:eq = self._growing_equity()m = calc_metrics(eq, [], 1_000_000, 252)