Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(optimizers): exclude decision-bar returns (#487)

Yuan Zhiyi9daccb427fe7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4fce69445..def28f2b0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
### Fixed
- FastMCP transport imports work across both module layouts (#469, thanks
@roberttidball).
+- Portfolio optimizers no longer include the decision bar's close-to-close
+ return in weights executed at that bar's open.
## [0.1.11] — 2026-07-11
diff --git a/agent/backtest/optimizers/base.py b/agent/backtest/optimizers/base.py
index bc2e5cbfe..5c76e05a2 100644
--- a/agent/backtest/optimizers/base.py
+++ b/agent/backtest/optimizers/base.py
@@ -16,7 +16,7 @@ class BaseOptimizer(ABC):
Subclasses implement ``_calc_weights``; the base handles:
- active asset selection
- - rolling window slicing and sanity checks
+ - causal rolling window slicing and sanity checks
- covariance matrix + NaN checks
- applying weights while preserving signal sign
@@ -42,7 +42,9 @@ class BaseOptimizer(ABC):
"""Apply optimizer to position weights.
Args:
- ret: Return matrix (dates x codes).
+ ret: Return matrix (dates x codes). For a decision at ``dt``,
+ only rows strictly earlier than ``dt`` are visible to the
+ optimizer because execution occurs at the decision bar's open.
pos: Raw signal positions.
dates: Date index aligned with ``pos``.
@@ -59,7 +61,12 @@ class BaseOptimizer(ABC):
if not active or i < self.lookback:
continue
- window = ret.loc[:dt, active].tail(self.lookback)
+ # Signals are executed at the decision bar's open. ``ret[dt]``
+ # is a close-to-close return that is not observable until that
+ # bar closes, so including it here would leak future information
+ # into the weights applied at the open.
+ history = ret.loc[ret.index < dt, active]
+ window = history.tail(self.lookback)
if len(window) < max(self.lookback // 2, 5):
continue
diff --git a/agent/tests/test_optimizer_causality.py b/agent/tests/test_optimizer_causality.py
new file mode 100644
index 000000000..2100bf269
--- /dev/null
+++ b/agent/tests/test_optimizer_causality.py
@@ -0,0 +1,65 @@
+"""Causality regression tests for portfolio optimizer lookback windows."""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+
+from backtest.optimizers.base import BaseOptimizer
+
+
+class _LastObservationOptimizer(BaseOptimizer):
+ """Allocate fully to the asset with the best last visible return."""
+
+ def __init__(self, lookback: int = 5) -> None:
+ super().__init__(lookback=lookback)
+ self.windows: list[pd.DatetimeIndex] = []
+
+ def _build_context(
+ self,
+ window: pd.DataFrame,
+ active: list[str],
+ ) -> dict[str, np.ndarray]:
+ self.windows.append(window.index.copy())
+ return {"last_return": window.iloc[-1].to_numpy(dtype=float)}
+
+ def _calc_weights(self, ctx: dict[str, np.ndarray]) -> np.ndarray:
+ weights = np.zeros(len(ctx["last_return"]), dtype=float)
+ weights[int(np.argmax(ctx["last_return"]))] = 1.0
+ return weights
+
+
+def _inputs() -> tuple[pd.DatetimeIndex, pd.DataFrame, pd.DataFrame]:
+ dates = pd.bdate_range("2026-01-05", periods=6)
+ returns = pd.DataFrame(
+ {
+ "A": [0.00, 0.01, 0.02, 0.03, 0.80, 0.00],
+ "B": [0.00, 0.00, 0.01, 0.02, -0.80, 0.00],
+ },
+ index=dates,
+ )
+ positions = pd.DataFrame(1.0, index=dates, columns=["A", "B"])
+ return dates, returns, positions
+
+
+def test_optimizer_window_excludes_decision_bar() -> None:
+ dates, returns, positions = _inputs()
+ optimizer = _LastObservationOptimizer(lookback=5)
+
+ optimizer.optimize(returns, positions, dates)
+
+ assert len(optimizer.windows) == 1
+ assert optimizer.windows[0].max() < dates[-1]
+ assert optimizer.windows[0].max() == dates[-2]
+
+
+def test_decision_bar_return_cannot_change_decision_bar_weights() -> None:
+ dates, returns, positions = _inputs()
+ altered = returns.copy()
+ altered.loc[dates[-1], ["A", "B"]] = [-100.0, 100.0]
+
+ baseline = _LastObservationOptimizer(lookback=5).optimize(returns, positions, dates)
+ shocked = _LastObservationOptimizer(lookback=5).optimize(altered, positions, dates)
+
+ pd.testing.assert_series_equal(baseline.loc[dates[-1]], shocked.loc[dates[-1]])
+ assert baseline.loc[dates[-1]].to_dict() == {"A": 1.0, "B": 0.0}