Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): handle unnamed DatetimeIndex in correlation matrix

santhrealf684178dd230
diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.py
index 24db8d9a1..fce037177 100644
--- a/agent/backtest/correlation.py
+++ b/agent/backtest/correlation.py
@@ -113,11 +113,18 @@ def _rolling_correlation_matrix(
raise ValueError(f"Price series for '{code}' is empty")
if "close" not in df.columns and "close" not in df.index.names:
raise ValueError(f"No 'close' column in price series for '{code}'")
- # Support both column-based and index-based trade_date
- if "trade_date" in df.index.names and "trade_date" not in df.columns:
+ # Support trade_date as index name, column, or a plain DatetimeIndex.
+ if "trade_date" in df.columns:
+ ts = df.set_index("trade_date")["close"]
+ elif "close" in df.columns and (
+ "trade_date" in df.index.names
+ or isinstance(df.index, pd.DatetimeIndex)
+ ):
ts = df["close"]
else:
- ts = df.set_index("trade_date")["close"]
+ raise ValueError(
+ f"No trade_date index/column for price series '{code}'"
+ )
closes[code] = ts.sort_index()
for code in codes:
diff --git a/agent/tests/test_correlation.py b/agent/tests/test_correlation.py
index 4b7b0f99b..bba3fd77b 100644
--- a/agent/tests/test_correlation.py
+++ b/agent/tests/test_correlation.py
@@ -239,4 +239,20 @@ class TestRollingCorrelationMatrix:
def test_missing_close_column_raises(self):
df = pd.DataFrame({"open": [1, 2, 3]})
with pytest.raises(ValueError, match="No 'close' column"):
- _rolling_correlation_matrix({"X": df}, window=30, method="pearson")
\ No newline at end of file
+ _rolling_correlation_matrix({"X": df}, window=30, method="pearson")
+
+
+def test_rolling_correlation_unnamed_datetime_index() -> None:
+ """OHLCV frames with an unnamed DatetimeIndex must not KeyError on trade_date."""
+ import numpy as np
+ import pandas as pd
+ from backtest.correlation import _rolling_correlation_matrix
+
+ idx = pd.date_range("2020-01-01", periods=40, freq="B")
+ series = {
+ "A": pd.DataFrame({"close": np.linspace(100, 110, 40)}, index=idx),
+ "B": pd.DataFrame({"close": np.linspace(50, 60, 40)}, index=idx),
+ }
+ labels, matrix = _rolling_correlation_matrix(series, window=20, method="pearson")
+ assert labels == ["A", "B"]
+ assert len(matrix) == 2