Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): account for terminal close costs

YZY010846e2e6cd7f29
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d966bd943..0d4183e32 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).
+- End-of-backtest liquidations now apply exit slippage and include their
+ commission in the final reported equity.
- 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..7856ca109 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -558,8 +558,23 @@ class BaseEngine(ABC):
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")
+ pos = self.positions[c]
+ mark_price = self._safe_price(close_df, last_ts, c, pos.entry_price)
+ self._active_symbol = c
+ exit_price = self.apply_slippage(mark_price, -pos.direction)
+ self._close_position(c, exit_price, last_ts, "end_of_backtest")
+
+ # The final snapshot feeds metrics and artifacts. Replace its
+ # pre-liquidation mark with post-liquidation cash so terminal
+ # slippage and exit commission are reflected in reported equity.
+ if self.equity_snapshots:
+ self.equity_snapshots[-1] = EquitySnapshot(
+ timestamp=last_ts,
+ capital=self.capital,
+ unrealized=0.0,
+ equity=self.capital,
+ positions=0,
+ )
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_terminal_close_accounting.py b/agent/tests/test_terminal_close_accounting.py
new file mode 100644
index 000000000..72cb51edb
--- /dev/null
+++ b/agent/tests/test_terminal_close_accounting.py
@@ -0,0 +1,58 @@
+"""Regression tests for end-of-backtest liquidation accounting."""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from backtest.engines.base import BaseEngine
+
+
+class _TerminalCostEngine(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 if is_open else 7.0
+
+ def apply_slippage(self, price, direction):
+ return price + direction if self.positions else price
+
+
+ ("target_weight", "expected_exit"),
+ [(0.5, 99.0), (-0.5, 101.0)],
+)
+def test_terminal_close_costs_reach_final_equity(
+ target_weight: float,
+ expected_exit: float,
+) -> None:
+ dates = pd.DatetimeIndex(["2026-01-05"])
+ bars = pd.DataFrame({"open": [100.0], "close": [100.0]}, index=dates)
+ close_df = pd.DataFrame({"TEST": bars["close"]}, index=dates)
+ target_pos = pd.DataFrame({"TEST": [target_weight]}, index=dates)
+ engine = _TerminalCostEngine({"initial_cash": 1_000.0})
+
+ engine._execute_bars(
+ dates,
+ {"TEST": bars},
+ close_df,
+ target_pos,
+ ["TEST"],
+ )
+
+ assert len(engine.trades) == 1
+ trade = engine.trades[0]
+ assert trade.exit_reason == "end_of_backtest"
+ assert trade.exit_price == expected_exit
+ assert trade.commission == 7.0
+ assert engine.capital == pytest.approx(988.0)
+
+ final_snapshot = engine.equity_snapshots[-1]
+ assert final_snapshot.capital == pytest.approx(engine.capital)
+ assert final_snapshot.equity == pytest.approx(engine.capital)
+ assert final_snapshot.unrealized == 0.0
+ assert final_snapshot.positions == 0