Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(metrics): surface realized portfolio turnover in backtest metrics (#478)

卫斯李43f803dee2f9
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index ba0ab1d03..87a61f7be 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -462,7 +462,7 @@ 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)
+ m = calc_metrics(equity_series, self.trades, self.initial_capital, bars_per_year, bench_ret, target_pos)
m.update(benchmark_metadata)
m["by_symbol"] = by_symbol_stats(self.trades)
m["by_exit_reason"] = by_exit_reason_stats(self.trades)
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index e1cdb7caf..dcfbb87a4 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -148,12 +148,38 @@ def by_exit_reason_stats(trades: List[TradeRecord]) -> Dict[str, Dict[str, Any]]
return result
+def calc_turnover_series(positions: pd.DataFrame) -> pd.Series:
+ """Per-bar realized portfolio turnover from a position-weight 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.
+
+ Args:
+ positions: Position-weight matrix (index=timestamp, columns=codes).
+
+ Returns:
+ Per-bar turnover series indexed like ``positions``; empty when the
+ input is empty.
+ """
+ if positions is None or positions.empty:
+ return pd.Series(dtype=float)
+ filled = positions.fillna(0.0)
+ prev = filled.shift(1).fillna(0.0)
+ return 0.5 * (filled - prev).abs().sum(axis=1)
+
+
def calc_metrics(
equity_curve: pd.Series,
trades: List[TradeRecord],
initial_cash: float,
bars_per_year: Optional[int] = 252,
bench_ret: Optional[pd.Series] = None,
+ positions: Optional[pd.DataFrame] = None,
) -> Dict[str, Any]:
"""Full set of performance metrics.
@@ -164,6 +190,8 @@ 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.
Returns:
Metrics dictionary (compatible with daily_portfolio format).
@@ -203,6 +231,11 @@ 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
+
# Benchmark comparison
bench_return = 0.0
excess = 0.0
@@ -231,6 +264,8 @@ def calc_metrics(
"benchmark_return": round(bench_return, 6),
"excess_return": round(excess, 6),
"information_ratio": round(ir, 4),
+ "avg_turnover": round(avg_turnover, 6),
+ "total_turnover": round(total_turnover, 6),
}
@@ -243,4 +278,5 @@ def _empty_metrics(initial_cash: float) -> Dict[str, Any]:
"win_rate": 0, "profit_loss_ratio": 0, "profit_factor": 0,
"max_consecutive_loss": 0, "avg_holding_days": 0, "trade_count": 0,
"benchmark_return": 0, "excess_return": 0, "information_ratio": 0,
+ "avg_turnover": 0.0, "total_turnover": 0.0,
}
diff --git a/agent/tests/test_metrics.py b/agent/tests/test_metrics.py
index df32cc169..270f8746f 100644
--- a/agent/tests/test_metrics.py
+++ b/agent/tests/test_metrics.py
@@ -18,6 +18,7 @@ from backtest.metrics import (
by_symbol_stats,
calc_bars_per_year,
calc_metrics,
+ calc_turnover_series,
win_rate_and_stats,
)
from backtest.models import TradeRecord
@@ -287,3 +288,84 @@ class TestCalcMetrics:
# Calmar = annual_return / |max_drawdown|
if m["annual_return"] > 0:
assert m["calmar"] > 0
+
+
+# ---------------------------------------------------------------------------
+# turnover
+# ---------------------------------------------------------------------------
+
+
+class TestCalcTurnoverSeries:
+ def test_full_rotation_is_unit_turnover(self) -> None:
+ dates = pd.bdate_range("2025-01-01", periods=2)
+ pos = pd.DataFrame({"A": [1.0, 0.0], "B": [0.0, 1.0]}, index=dates)
+ s = calc_turnover_series(pos)
+ assert s.iloc[1] == pytest.approx(1.0)
+
+ def test_constant_weights_zero_after_entry(self) -> None:
+ dates = pd.bdate_range("2025-01-01", periods=4)
+ pos = pd.DataFrame({"A": [0.5] * 4, "B": [0.5] * 4}, index=dates)
+ s = calc_turnover_series(pos)
+ assert s.iloc[0] == pytest.approx(0.5) # entry from cash: 0.5*(0.5+0.5)
+ assert s.iloc[1:].abs().max() == pytest.approx(0.0)
+
+ def test_first_bar_is_entry_from_cash(self) -> None:
+ dates = pd.bdate_range("2025-01-01", periods=1)
+ pos = pd.DataFrame({"A": [0.6], "B": [0.4]}, index=dates)
+ s = calc_turnover_series(pos)
+ assert s.iloc[0] == pytest.approx(0.5)
+
+ def test_empty_frame_returns_empty(self) -> None:
+ s = calc_turnover_series(pd.DataFrame())
+ assert s.empty
+
+ def test_nan_treated_as_zero(self) -> None:
+ dates = pd.bdate_range("2025-01-01", periods=2)
+ pos = pd.DataFrame({"A": [1.0, np.nan], "B": [0.0, 1.0]}, index=dates)
+ s = calc_turnover_series(pos)
+ assert s.iloc[1] == pytest.approx(1.0)
+
+
+class TestTurnoverMetrics:
+ def _equity(self) -> pd.Series:
+ dates = pd.bdate_range("2025-01-01", periods=4)
+ return pd.Series(np.linspace(1_000_000, 1_100_000, 4), index=dates)
+
+ def _positions(self) -> pd.DataFrame:
+ dates = pd.bdate_range("2025-01-01", periods=4)
+ return pd.DataFrame(
+ {"A": [1.0, 0.0, 1.0, 0.0], "B": [0.0, 1.0, 0.0, 1.0]}, index=dates
+ )
+
+ def test_turnover_keys_present(self) -> None:
+ m = calc_metrics(self._equity(), [], 1_000_000, 252, positions=self._positions())
+ assert "avg_turnover" in m and "total_turnover" in m
+
+ def test_total_equals_avg_times_bars(self) -> None:
+ pos = self._positions()
+ m = calc_metrics(self._equity(), [], 1_000_000, 252, positions=pos)
+ assert m["total_turnover"] == pytest.approx(m["avg_turnover"] * len(pos), rel=1e-6)
+
+ def test_positions_do_not_change_existing_metrics(self) -> None:
+ eq = self._equity()
+ without = calc_metrics(eq, [], 1_000_000, 252)
+ with_pos = calc_metrics(eq, [], 1_000_000, 252, positions=self._positions())
+ for key in without:
+ if key in ("avg_turnover", "total_turnover"):
+ continue
+ assert without[key] == with_pos[key]
+
+ def test_no_positions_zero_turnover(self) -> None:
+ m = calc_metrics(self._equity(), [], 1_000_000, 252)
+ assert m["avg_turnover"] == 0.0
+ assert m["total_turnover"] == 0.0
+
+ def test_empty_positions_zero_turnover(self) -> None:
+ m = calc_metrics(self._equity(), [], 1_000_000, 252, positions=pd.DataFrame())
+ assert m["avg_turnover"] == 0.0
+ assert m["total_turnover"] == 0.0
+
+ def test_empty_metrics_has_turnover_keys(self) -> None:
+ m = calc_metrics(pd.Series(dtype=float), [], 1_000_000, 252)
+ assert m["avg_turnover"] == 0.0
+ assert m["total_turnover"] == 0.0