Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): report turnover from executed trades

YZY01086b26f6bb0ee0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d966bd943..83cfb7c47 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).
+- Backtest turnover metrics now use actual filled and rounded position sizes;
+ targets rejected by market rules no longer inflate reported turnover.
- 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..7e03c5dbd 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -35,6 +35,7 @@ from backtest.metrics import (
by_exit_reason_stats,
by_symbol_stats,
calc_metrics,
+ calc_trade_turnover_series,
)
from backtest.models import EquitySnapshot, Position, TradeRecord
@@ -462,7 +463,16 @@ class BaseEngine(ABC):
bench_equity = self.initial_capital * (1 + bench_ret).cumprod()
# 6. Metrics
- m = calc_metrics(equity_series, self.trades, self.initial_capital, bars_per_year, bench_ret, target_pos)
+ realized_turnover = calc_trade_turnover_series(self.trades, equity_series)
+ m = calc_metrics(
+ equity_series,
+ self.trades,
+ self.initial_capital,
+ bars_per_year,
+ bench_ret,
+ target_pos,
+ turnover_series=realized_turnover,
+ )
m.update(benchmark_metadata)
m["by_symbol"] = by_symbol_stats(self.trades)
m["by_exit_reason"] = by_exit_reason_stats(self.trades)
@@ -688,6 +698,7 @@ class BaseEngine(ABC):
pnl = self._calc_pnl(symbol, pos.direction, pos.size, pos.entry_price, exit_price)
margin = self._calc_margin(symbol, pos.size, pos.entry_price, pos.leverage)
+ exit_margin = self._calc_margin(symbol, pos.size, exit_price, pos.leverage)
pnl_pct = pnl / margin * 100 if margin > 1e-9 else 0.0
exit_comm = self.calc_commission(pos.size, exit_price, pos.direction, is_open=False)
@@ -709,6 +720,8 @@ class BaseEngine(ABC):
exit_reason=reason,
holding_bars=holding_bars,
commission=pos.entry_commission + exit_comm,
+ entry_margin=margin,
+ exit_margin=exit_margin,
))
# ── Artifacts ──
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index dcfbb87a4..9d27f741f 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -149,15 +149,15 @@ def by_exit_reason_stats(trades: List[TradeRecord]) -> Dict[str, Dict[str, Any]]
def calc_turnover_series(positions: pd.DataFrame) -> pd.Series:
- """Per-bar realized portfolio turnover from a position-weight frame.
+ """Per-bar weight-implied portfolio turnover from a position frame.
Turnover for a bar is ``0.5 * sum_i |w_{t,i} - w_{t-1,i}|``, so a full
rotation from one asset to another counts as 1.0 (matching the
``turnover_aware`` optimizer's convention). The first bar's turnover is
``0.5 * sum_i |w_{0,i}|``, treating the initial allocation as entry from
- cash. Turnover is measured on the executed (post-normalization) frame the
- engine holds, which may differ slightly from an optimizer's own internal
- pre-normalization figure.
+ cash. Turnover is measured on the weight frame the caller supplies. It
+ does not know whether the execution engine filled, rounded, or rejected
+ those target positions.
Args:
positions: Position-weight matrix (index=timestamp, columns=codes).
@@ -173,6 +173,48 @@ def calc_turnover_series(positions: pd.DataFrame) -> pd.Series:
return 0.5 * (filled - prev).abs().sum(axis=1)
+def calc_trade_turnover_series(
+ trades: List[TradeRecord],
+ equity_curve: pd.Series,
+) -> pd.Series:
+ """Per-bar turnover from actual entry and exit allocations.
+
+ Each filled leg contributes its margin-equivalent traded value. Dividing
+ gross traded value by twice the portfolio equity preserves the existing
+ convention: entering a 100% allocation counts as 0.5 and rotating a 100%
+ allocation between two assets counts as 1.0.
+
+ Args:
+ trades: Completed trades carrying actual entry/exit margin values.
+ equity_curve: Portfolio equity used to normalize traded values.
+
+ Returns:
+ Per-bar realized turnover aligned to ``equity_curve``.
+ """
+ if equity_curve is None or equity_curve.empty:
+ return pd.Series(dtype=float)
+
+ traded_margin = pd.Series(0.0, index=equity_curve.index, dtype=float)
+ for trade in trades:
+ for timestamp, margin in (
+ (trade.entry_time, trade.entry_margin),
+ (trade.exit_time, trade.exit_margin),
+ ):
+ try:
+ margin_value = float(margin)
+ except (TypeError, ValueError):
+ continue
+ if (
+ timestamp in traded_margin.index
+ and np.isfinite(margin_value)
+ and margin_value > 0
+ ):
+ traded_margin.loc[timestamp] += margin_value
+
+ denominator = 2.0 * equity_curve.abs().replace(0.0, np.nan)
+ return (traded_margin / denominator).replace([np.inf, -np.inf], np.nan).fillna(0.0)
+
+
def calc_metrics(
equity_curve: pd.Series,
trades: List[TradeRecord],
@@ -180,6 +222,7 @@ def calc_metrics(
bars_per_year: Optional[int] = 252,
bench_ret: Optional[pd.Series] = None,
positions: Optional[pd.DataFrame] = None,
+ turnover_series: Optional[pd.Series] = None,
) -> Dict[str, Any]:
"""Full set of performance metrics.
@@ -190,8 +233,10 @@ def calc_metrics(
bars_per_year: Bars per year for annualisation. None = auto-detect
from equity curve dates (calendar-day method, for cross-market).
bench_ret: Benchmark per-bar return series (optional).
- positions: Executed position-weight frame (optional). When provided,
- realized turnover metrics are added; absent/empty yields zeros.
+ positions: Position-weight frame used as a backward-compatible
+ turnover fallback when ``turnover_series`` is not supplied.
+ turnover_series: Actual per-bar execution turnover (optional). When
+ supplied, it takes precedence over position-implied turnover.
Returns:
Metrics dictionary (compatible with daily_portfolio format).
@@ -231,10 +276,17 @@ def calc_metrics(
trade_stats = win_rate_and_stats(trades)
- # Realized portfolio turnover from the executed position frame
- turnover_series = calc_turnover_series(positions) if positions is not None else pd.Series(dtype=float)
- avg_turnover = float(turnover_series.mean()) if len(turnover_series) > 0 else 0.0
- total_turnover = float(turnover_series.sum()) if len(turnover_series) > 0 else 0.0
+ # Prefer execution-derived turnover; retain the position-frame fallback
+ # for external callers of calc_metrics that do not have fill records.
+ turnover_values = (
+ turnover_series.reindex(equity_curve.index).fillna(0.0).clip(lower=0.0)
+ if turnover_series is not None
+ else calc_turnover_series(positions)
+ if positions is not None
+ else pd.Series(dtype=float)
+ )
+ avg_turnover = float(turnover_values.mean()) if len(turnover_values) > 0 else 0.0
+ total_turnover = float(turnover_values.sum()) if len(turnover_values) > 0 else 0.0
# Benchmark comparison
bench_return = 0.0
diff --git a/agent/backtest/models.py b/agent/backtest/models.py
index 9ff03e584..c00364884 100644
--- a/agent/backtest/models.py
+++ b/agent/backtest/models.py
@@ -53,6 +53,8 @@ class TradeRecord:
exit_reason: Why closed (signal / liquidation / end_of_backtest).
holding_bars: Number of bars held.
commission: Total commission (entry + exit).
+ entry_margin: Actual margin allocated at entry, after size rounding.
+ exit_margin: Margin-equivalent value traded at the exit price.
"""
symbol: str
@@ -68,6 +70,8 @@ class TradeRecord:
exit_reason: str
holding_bars: int
commission: float
+ entry_margin: float = 0.0
+ exit_margin: float = 0.0
@dataclass(frozen=True)
diff --git a/agent/tests/test_realized_turnover.py b/agent/tests/test_realized_turnover.py
new file mode 100644
index 000000000..5ba6c9da2
--- /dev/null
+++ b/agent/tests/test_realized_turnover.py
@@ -0,0 +1,95 @@
+"""Regression tests for execution-derived turnover metrics."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from backtest.engines.base import BaseEngine
+from backtest.engines.china_a import ChinaAEngine
+from backtest.metrics import calc_metrics, calc_trade_turnover_series
+
+
+class _RoundedEngine(BaseEngine):
+ def can_execute(self, symbol, direction, bar):
+ return True
+
+ def round_size(self, raw_size, price):
+ return float(int(raw_size))
+
+ def calc_commission(self, size, price, direction, is_open):
+ return 0.0
+
+ def apply_slippage(self, price, direction):
+ return price
+
+
+def test_turnover_uses_rounded_fills_instead_of_targets() -> None:
+ dates = pd.bdate_range("2026-01-05", periods=2)
+ bars = pd.DataFrame({"open": [60.0, 60.0], "close": [60.0, 60.0]}, index=dates)
+ close_df = pd.DataFrame({"TEST": bars["close"]}, index=dates)
+ targets = pd.DataFrame({"TEST": [0.55, 0.0]}, index=dates)
+ engine = _RoundedEngine({"initial_cash": 1_000.0})
+
+ engine._execute_bars(dates, {"TEST": bars}, close_df, targets, ["TEST"])
+ equity = pd.Series(
+ [snapshot.equity for snapshot in engine.equity_snapshots],
+ index=dates,
+ )
+ turnover = calc_trade_turnover_series(engine.trades, equity)
+
+ # The target asks for 550, but integer sizing fills 9 * 60 = 540.
+ assert turnover.tolist() == pytest.approx([0.27, 0.27])
+ metrics = calc_metrics(
+ equity,
+ engine.trades,
+ 1_000.0,
+ positions=targets,
+ turnover_series=turnover,
+ )
+ assert metrics["total_turnover"] == pytest.approx(0.54)
+ assert metrics["avg_turnover"] == pytest.approx(0.27)
+
+
+def test_rejected_target_has_zero_reported_turnover(tmp_path: Path) -> None:
+ dates = pd.bdate_range("2026-01-05", periods=3)
+ bars = pd.DataFrame(
+ {
+ "open": [10.0, 10.0, 10.0],
+ "high": [10.0, 10.0, 10.0],
+ "low": [10.0, 10.0, 10.0],
+ "close": [10.0, 10.0, 10.0],
+ "volume": [1_000, 1_000, 1_000],
+ },
+ index=dates,
+ )
+
+ class FakeLoader:
+ def fetch(self, *args, **kwargs):
+ return {"000001.SZ": bars.copy()}
+
+ class ShortSignal:
+ def generate(self, data_map):
+ return {"000001.SZ": pd.Series(-1.0, index=dates)}
+
+ engine = ChinaAEngine({"initial_cash": 1_000_000.0})
+ metrics = engine.run_backtest(
+ {
+ "codes": ["000001.SZ"],
+ "start_date": "2026-01-05",
+ "end_date": "2026-01-07",
+ "source": "tushare",
+ "initial_cash": 1_000_000.0,
+ },
+ FakeLoader(),
+ ShortSignal(),
+ tmp_path,
+ )
+
+ # China A-shares reject short opens. The target frame changes, but no fill
+ # occurs, so execution-derived turnover must remain zero.
+ assert engine.trades == []
+ assert metrics["total_turnover"] == 0.0
+ assert metrics["avg_turnover"] == 0.0