Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): make open rebalances causal

YZY0108cdd231cb41f4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d966bd943..774bd5248 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,6 +52,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
@roberttidball).
- Portfolio optimizers no longer include the decision bar's close-to-close
return in weights executed at that bar's open (#487, thanks @YZY0108).
+- Open-price rebalances no longer use the decision bar's close for sizing or
+ depend on whether a replacement symbol sorts before the position it closes.
- Preflight (`vibe-trading run`) no longer resolves provider/model against a
stale `EnvConfig` snapshot cached before dotenv loads (#479, thanks
@ananaymital, closes #477).
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 87a61f7be..dae1adf45 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -516,21 +516,63 @@ class BaseEngine(ABC):
for i, ts in enumerate(dates):
self._bar_idx = i
- # a. Per-bar hooks (funding fees, liquidation checks)
+ # a. Value the book at prices observable when orders execute.
+ # Rebalances happen at the bar open, so using close_df[ts] here
+ # would let the yet-unknown decision-bar close affect order size.
+ equity = self._calc_open_equity(data_map, close_df, ts)
+ target_weights: Dict[str, Optional[float]] = {}
for c in codes:
- if ts in data_map[c].index:
- self.on_bar(c, data_map[c].loc[ts], ts)
+ try:
+ target_weights[c] = (
+ float(target_pos.at[ts, c]) if ts in target_pos.index else 0.0
+ )
+ except Exception as exc:
+ target_weights[c] = None
+ logger.warning("Target weight failed for %s at %s: %s", c, ts, exc)
- # b. Rebalance each symbol to target weight
- equity = self._calc_equity(close_df, ts)
+ # b. Release capital before opening replacement positions. A
+ # single mixed close/open pass makes rotations depend on symbol
+ # iteration order when the new name is visited before the old one.
for c in codes:
+ target_w = target_weights[c]
+ current_pos = self.positions.get(c)
+ if target_w is None or current_pos is None:
+ continue
+ target_dir = 1 if target_w > 1e-9 else (-1 if target_w < -1e-9 else 0)
+ if target_dir == 0 or target_dir != current_pos.direction:
+ try:
+ self._rebalance(c, 0.0, data_map.get(c), ts, equity)
+ except Exception as exc:
+ logger.warning(
+ "Rebalance close failed for %s at %s: %s", c, ts, exc
+ )
+
+ # c. Open target positions only after the close pass. If a close
+ # was blocked by market rules, do not open the opposite side.
+ for c in codes:
+ target_w = target_weights[c]
+ if target_w is None:
+ continue
+ target_dir = 1 if target_w > 1e-9 else (-1 if target_w < -1e-9 else 0)
+ current_pos = self.positions.get(c)
+ if current_pos is not None and (
+ target_dir == 0 or target_dir != current_pos.direction
+ ):
+ continue
try:
- target_w = float(target_pos.at[ts, c]) if ts in target_pos.index else 0.0
self._rebalance(c, target_w, data_map.get(c), ts, equity)
except Exception as exc:
- logger.warning("Rebalance failed for %s at %s: %s", c, ts, exc)
+ logger.warning("Rebalance open failed for %s at %s: %s", c, ts, exc)
+
+ # d. Apply close/within-bar hooks after open execution. Hooks use
+ # the current bar's close for funding, swaps, and liquidation, so
+ # running them first could liquidate a position that was scheduled
+ # to exit at the open (or charge a position before it was opened).
+ for c in codes:
+ if ts in data_map[c].index:
+ self.on_bar(c, data_map[c].loc[ts], ts)
- # c. Record equity snapshot
+ # e. Record equity snapshot
snap_equity = self._calc_equity(close_df, ts)
if self.positions and type(self)._calc_pnl is BaseEngine._calc_pnl:
_syms = list(self.positions.keys())
@@ -554,13 +596,49 @@ class BaseEngine(ABC):
positions=len(self.positions),
))
- # d. Force close all remaining positions
+ # f. Force close all remaining positions
if len(dates) > 0:
last_ts = dates[-1]
for c in list(self.positions.keys()):
price = self._safe_price(close_df, last_ts, c, self.positions[c].entry_price)
self._close_position(c, price, last_ts, "end_of_backtest")
+ def _calc_open_equity(
+ self,
+ data_map: Dict[str, pd.DataFrame],
+ close_df: pd.DataFrame,
+ ts: pd.Timestamp,
+ ) -> float:
+ """Value current positions at the execution bar's observable open.
+
+ For a symbol that has a bar at ``ts``, its open is the mark available
+ when next-bar-open orders execute. Symbols without a bar on the
+ unified calendar retain the aligned close fallback, which is the most
+ recent price carried by ``_align``.
+ """
+ if not self.positions:
+ return self.capital
+
+ equity = self.capital
+ for sym, pos in self.positions.items():
+ current_price = self._safe_price(close_df, ts, sym, pos.entry_price)
+ frame = data_map.get(sym)
+ if frame is not None and ts in frame.index:
+ open_price = frame.loc[ts].get("open")
+ if (
+ open_price is not None
+ and pd.notna(open_price)
+ and float(open_price) > 0
+ ):
+ current_price = float(open_price)
+
+ margin = self._calc_margin(sym, pos.size, pos.entry_price, pos.leverage)
+ unrealized = self._calc_pnl(
+ sym, pos.direction, pos.size, pos.entry_price, current_price
+ )
+ equity += margin + unrealized
+ return equity
+
def _calc_equity(self, close_df: pd.DataFrame, ts: pd.Timestamp) -> float:
"""Total equity = free cash + sum(margin + unrealised) per position.
diff --git a/agent/tests/test_execution_causality.py b/agent/tests/test_execution_causality.py
new file mode 100644
index 000000000..6db362502
--- /dev/null
+++ b/agent/tests/test_execution_causality.py
@@ -0,0 +1,113 @@
+"""Causality and ordering regressions for the shared execution loop."""
+
+from __future__ import annotations
+
+import pandas as pd
+
+from backtest.engines.base import BaseEngine
+from backtest.engines.crypto import CryptoEngine
+
+
+class _FrictionlessEngine(BaseEngine):
+ def can_execute(self, symbol, direction, bar):
+ return True
+
+ def round_size(self, raw_size, price):
+ return raw_size
+
+ def calc_commission(self, size, price, direction, is_open):
+ return 0.0
+
+ def apply_slippage(self, price, direction):
+ return price
+
+
+def _rotation_run(*, last_close_a: float = 100.0, code_order=None):
+ dates = pd.bdate_range("2026-01-05", periods=2)
+ bars_a = pd.DataFrame(
+ {"open": [100.0, 100.0], "close": [100.0, last_close_a]},
+ index=dates,
+ )
+ bars_b = pd.DataFrame(
+ {"open": [100.0, 100.0], "close": [100.0, 100.0]},
+ index=dates,
+ )
+ data_map = {"A": bars_a, "B": bars_b}
+ close_df = pd.DataFrame(
+ {"A": bars_a["close"], "B": bars_b["close"]},
+ index=dates,
+ )
+ target_pos = pd.DataFrame(
+ {"A": [0.5, 0.0], "B": [0.0, 0.5]},
+ index=dates,
+ )
+ engine = _FrictionlessEngine({"initial_cash": 100_000.0})
+ engine._execute_bars(
+ dates,
+ data_map,
+ close_df,
+ target_pos,
+ code_order or ["A", "B"],
+ )
+ return engine
+
+
+def test_decision_bar_close_cannot_change_open_position_size() -> None:
+ baseline = _rotation_run(last_close_a=100.0)
+ shocked = _rotation_run(last_close_a=200.0)
+
+ baseline_b = next(t for t in baseline.trades if t.symbol == "B")
+ shocked_b = next(t for t in shocked.trades if t.symbol == "B")
+
+ assert baseline_b.size == 500.0
+ assert shocked_b.size == baseline_b.size
+
+
+def test_rotation_is_independent_of_close_open_symbol_order() -> None:
+ a_first = _rotation_run(code_order=["A", "B"])
+ b_first = _rotation_run(code_order=["B", "A"])
+
+ a_first_trades = [(t.symbol, t.size, t.exit_reason) for t in a_first.trades]
+ b_first_trades = [(t.symbol, t.size, t.exit_reason) for t in b_first.trades]
+
+ assert a_first_trades == b_first_trades
+ assert [symbol for symbol, _, _ in a_first_trades] == ["A", "B"]
+
+
+def test_open_signal_exit_precedes_close_based_liquidation() -> None:
+ dates = pd.date_range("2026-01-05", periods=2, freq="D")
+ bars = pd.DataFrame(
+ {
+ "open": [100.0, 100.0],
+ "high": [100.0, 100.0],
+ "low": [100.0, 10.0],
+ "close": [100.0, 10.0],
+ },
+ index=dates,
+ )
+ symbol = "BTC-USDT"
+ close_df = pd.DataFrame({symbol: bars["close"]}, index=dates)
+ target_pos = pd.DataFrame({symbol: [1.0, 0.0]}, index=dates)
+ engine = CryptoEngine(
+ {
+ "initial_cash": 1_000.0,
+ "leverage": 10.0,
+ "maker_rate": 0.0,
+ "taker_rate": 0.0,
+ "slippage": 0.0,
+ "funding_rate": 0.0,
+ }
+ )
+
+ engine._execute_bars(
+ dates,
+ {symbol: bars},
+ close_df,
+ target_pos,
+ [symbol],
+ )
+
+ assert len(engine.trades) == 1
+ assert engine.trades[0].exit_reason == "signal"
+ assert engine.trades[0].exit_price == 100.0
+ assert engine.capital == 1_000.0