Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(correlation): align closes before taking returns across calendars

Rudy Celeklic55cbd334311
diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.py
index 1a3acfb2d..d35a5f1ec 100644
--- a/agent/backtest/correlation.py
+++ b/agent/backtest/correlation.py
@@ -195,7 +195,7 @@ def _rolling_correlation_matrix(
codes = sorted(price_series.keys())
# Build a aligned returns DataFrame (row index = date)
- returns_frames = []
+ close_frames = []
closes = {}
for code, df in price_series.items():
closes[code] = _close_series(code, df)
@@ -206,15 +206,19 @@ def _rolling_correlation_matrix(
# (e.g. crypto via OKX/CCXT at UTC midnight vs US equity via
# yfinance at EDT midnight = 04:00 UTC) align correctly.
ts.index = ts.index.tz_localize(None).normalize()
- # ``fill_method=None`` is explicit because under the project's
- # pandas>=2,<3 pin the ``pct_change`` default forward-fills missing
- # prices, silently manufacturing 0% returns on halted sessions.
- rets = ts.pct_change(fill_method=None).dropna()
- rets.name = code
- returns_frames.append(rets)
-
- # Align all series to a common index (inner join)
- aligned = pd.concat(returns_frames, axis=1).dropna()
+ ts.name = code
+ close_frames.append(ts)
+
+ # Align closes on common dates before differencing, so every column's
+ # return spans the same interval (a crypto Sun->Mon return must not be
+ # paired with an equity Fri->Mon return). ``fill_method=None`` is
+ # explicit because under the project's pandas>=2,<3 pin the
+ # ``pct_change`` default forward-fills missing prices.
+ aligned = (
+ pd.concat(close_frames, axis=1, join="inner")
+ .pct_change(fill_method=None)
+ .dropna()
+ )
if aligned.empty:
ranges = {
code: f"{closes[code].index.min()} .. {closes[code].index.max()}"
diff --git a/agent/backtest/regime.py b/agent/backtest/regime.py
index 0929a78be..9cecb8c9f 100644
--- a/agent/backtest/regime.py
+++ b/agent/backtest/regime.py
@@ -112,15 +112,18 @@ def _aligned_returns(price_series: Dict[str, pd.DataFrame]) -> pd.DataFrame:
pandas>=2,<3 pin the ``pct_change`` default forward-fills missing
prices, silently manufacturing 0% returns.
"""
- returns_frames = []
+ close_frames = []
for code in sorted(price_series):
ts = _close_series(code, price_series[code])
ts.index = ts.index.tz_localize(None).normalize()
- rets = ts.pct_change(fill_method=None).dropna()
- rets.name = code
- returns_frames.append(rets)
+ ts.name = code
+ close_frames.append(ts)
- aligned = pd.concat(returns_frames, axis=1).dropna()
+ aligned = (
+ pd.concat(close_frames, axis=1, join="inner")
+ .pct_change(fill_method=None)
+ .dropna()
+ )
if aligned.empty:
raise ValueError("No overlapping return data between assets")
return aligned
diff --git a/agent/tests/test_correlation.py b/agent/tests/test_correlation.py
index 13e78e621..3fd6bf6d8 100644
--- a/agent/tests/test_correlation.py
+++ b/agent/tests/test_correlation.py
@@ -316,6 +316,26 @@ class TestRollingCorrelationMatrix:
i, j = labels.index("GAP"), labels.index("PEER")
assert matrix[i][j] == pytest.approx(1.0)
+ def test_weekend_bars_do_not_shift_the_return_interval(self):
+ # A 7-day crypto series paired with a weekday equity series: the
+ # equity Monday return spans Fri->Mon, so the crypto return paired
+ # with it must too. COIN closes at twice EQ on every shared date and
+ # wanders only on weekends, so on shared dates they are identical.
+ days = pd.date_range("2024-01-01", periods=56, freq="D")
+ rng = np.random.default_rng(3)
+ eq = pd.Series(100.0 * np.cumprod(1.0 + rng.normal(0, 0.01, len(days))), index=days)
+ coin = 2.0 * eq
+ coin[days.dayofweek == 5] *= 1.08
+ coin[days.dayofweek == 6] *= 0.93
+ weekdays = days[days.dayofweek < 5]
+ price_series = {
+ "COIN": pd.DataFrame({"close": coin.to_numpy()}, index=pd.Index(days, name="trade_date")),
+ "EQ": pd.DataFrame({"close": eq[weekdays].to_numpy()}, index=pd.Index(weekdays, name="trade_date")),
+ }
+ labels, matrix = _rolling_correlation_matrix(price_series, window=100, method="pearson")
+ i, j = labels.index("COIN"), labels.index("EQ")
+ assert matrix[i][j] == pytest.approx(1.0)
+
def test_empty_dict_returns_empty(self):
labels, matrix = _rolling_correlation_matrix({}, window=30, method="pearson")
assert labels == []
diff --git a/agent/tests/test_regime.py b/agent/tests/test_regime.py
index b0f6b1deb..056ddc1f8 100644
--- a/agent/tests/test_regime.py
+++ b/agent/tests/test_regime.py
@@ -149,6 +149,20 @@ class TestAlignedReturns:
assert len(aligned) == 3
assert not (aligned["GAP"] == 0.0).any()
+ def test_weekend_bars_do_not_shift_the_return_interval(self):
+ # Mon 2024-01-01 .. Mon 2024-01-15. The crypto Monday return must span
+ # Fri->Mon like the equity one, not Sun->Mon.
+ days = pd.date_range("2024-01-01", periods=15, freq="D")
+ coin = pd.Series(np.arange(100.0, 115.0), index=days)
+ weekdays = days[days.dayofweek < 5]
+ aligned = _aligned_returns({
+ "COIN": pd.DataFrame({"close": coin.to_numpy()}, index=pd.Index(days, name="trade_date")),
+ "EQ": pd.DataFrame({"close": coin[weekdays].to_numpy()}, index=pd.Index(weekdays, name="trade_date")),
+ })
+ monday = pd.Timestamp("2024-01-08")
+ assert aligned.loc[monday, "COIN"] == pytest.approx(107.0 / 104.0 - 1.0)
+ assert aligned["COIN"].to_numpy() == pytest.approx(aligned["EQ"].to_numpy())
+
class _ServesPanelLoader:
"""Fake loader serving a prebuilt panel, keyed by normalized symbol."""