"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(metrics): guard calendar_days calculation when equity_curve has non-datetime index (#927)
Santhcd0fd87b6886
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.pyindex ba4e0cf43..336359aaf 100644--- a/agent/backtest/metrics.py+++ b/agent/backtest/metrics.py@@ -464,7 +464,8 @@ def calc_metrics(# Calendar-day annualization for cross-market (bars_per_year=None)if bars_per_year is None:first, last = equity_curve.index[0], equity_curve.index[-1]- calendar_days = (last - first).days+ diff = last - first+ calendar_days = diff.days if hasattr(diff, "days") else 0years = calendar_days / 365.25 if calendar_days > 0 else 1.0bpy = int(n / years) if years > 0 else 252else:diff --git a/agent/tests/test_metrics_calc_integer_index.py b/agent/tests/test_metrics_calc_integer_index.pynew file mode 100644index 000000000..c1f9b7023--- /dev/null+++ b/agent/tests/test_metrics_calc_integer_index.py@@ -0,0 +1,23 @@+"""Regression test for calc_metrics on equity curves with integer or non-datetime index.++Locks out a bug where calc_metrics raised AttributeError: 'int' object has no+attribute 'days' when bars_per_year=None (auto-detect mode) and equity_curve's+index was non-datetime (e.g. RangeIndex or Int64Index).+"""++import pandas as pd+from backtest.metrics import calc_metrics+++def test_calc_metrics_auto_detect_bars_per_year_with_integer_index():+ """Prove calc_metrics auto-detect mode handles integer-indexed equity curves without crashing."""+ # Equity curve with RangeIndex(0, 5)+ equity_curve = pd.Series([100.0, 102.0, 105.0, 103.0, 108.0])++ # On un-fixed code, bars_per_year=None raises AttributeError: 'int' object has no attribute 'days'.+ # On fixed code, it returns a valid metrics dictionary.+ metrics = calc_metrics(equity_curve, trades=[], initial_cash=100.0, bars_per_year=None)++ assert isinstance(metrics, dict)+ assert "total_return" in metrics+ assert round(metrics["total_return"], 2) == 0.08