"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(optimizers): price turnover from signed position changes
Rudy Celekliae09bb9308a7
diff --git a/README.md b/README.mdindex a8eebe9b7..8bd985794 100644--- a/README.md+++ b/README.md@@ -820,6 +820,10 @@ When the opt-in market-data cache is enabled, local-source cache entries arescoped to the configured file, query, and column mapping. Changing a symbol'ssource declaration does not reuse bars from its previous source. The settled-datacache policy for an unchanged declaration remains the same.+The turnover-aware optimizer measures allocation changes in signed position+space: reversing a 50% long to a 50% short contributes 0.5 turnover, including+both the close and the reopen. Its penalty and recorded allocation turnover+include these reversals; execution-derived turnover remains a separate metric.</details>diff --git a/agent/backtest/optimizers/base.py b/agent/backtest/optimizers/base.pyindex de1c353a8..3a04cd636 100644--- a/agent/backtest/optimizers/base.py+++ b/agent/backtest/optimizers/base.py@@ -85,6 +85,9 @@ class BaseOptimizer(ABC):if ctx is None:continue+ # Stateful optimizers need the direction as well as the signed+ # return window to measure changes between actual allocations.+ ctx["position_signs"] = signsweights = self._calc_weights(ctx)if weights is None or len(weights) != len(active):continuediff --git a/agent/backtest/optimizers/turnover_aware.py b/agent/backtest/optimizers/turnover_aware.pyindex 42ec0f3bc..d5b82418f 100644--- a/agent/backtest/optimizers/turnover_aware.py+++ b/agent/backtest/optimizers/turnover_aware.py@@ -7,8 +7,8 @@ Solves, per rebalance date::w_i <= max_per_name (per-name cap)sum_{i in group_g} w_i <= max_per_group[g] (per-group cap)-where ``w_prev`` is the weight vector applied at the previous rebalance,-restricted to the current active set (assets absent last time have prior+where ``w_prev`` is the previous signed allocation expressed in the current+position directions, restricted to the current active set (assets absent last time have priorweight 0, so entries and exits both count as turnover). With ``gamma == 0``the objective reduces to the mean-variance utility baseline.@@ -160,7 +160,14 @@ class TurnoverAwareOptimizer(BaseOptimizer):if n == 0:return self._equal_weight(0)- w_prev = np.array([self._prev.get(code, 0.0) for code in active], dtype=float)+ signs = np.asarray(ctx.get("position_signs", np.ones(n)), dtype=float)+ # Express the prior signed holdings in today's position directions:+ # a prior long is negative when today's proposed holding is short.+ # Then |w - w_prev| prices the full close-and-reopen reversal.+ w_prev = (+ np.array([self._prev.get(code, 0.0) for code in active], dtype=float)+ * signs+ )lam = self.risk_aversiongamma = self.turnover_penalty@@ -207,7 +214,14 @@ class TurnoverAwareOptimizer(BaseOptimizer):has_effective_caps = upper < 1.0 or any(cap < 1.0 for cap in group_caps)if not has_effective_caps:- x0 = w_prev if w_prev.sum() > 1e-12 else self._equal_weight(n)+ # Opposite-direction prior holdings cannot seed this nonnegative+ # simplex. Retain only same-direction holdings and normalize them.+ same_direction = np.maximum(w_prev, 0.0)+ x0 = (+ same_direction / same_direction.sum()+ if same_direction.sum() > 1e-12+ else self._equal_weight(n)+ )elif (np.isfinite(w_prev).all()and (w_prev >= 0.0).all()@@ -261,11 +275,11 @@ class TurnoverAwareOptimizer(BaseOptimizer):or any(row @ weights > cap + 1e-7 for row, cap in zip(group_rows, group_caps))):raise RuntimeError("optimizer returned weights that violate exposure caps")- self._record_turnover(active, weights)+ self._record_turnover(active, weights * signs)return weightsdef _record_turnover(self, active: List[str], weights: np.ndarray) -> None:- """Accumulate realized turnover and roll prior weights forward."""+ """Accumulate signed allocation turnover and roll prior holdings forward."""codes = set(active) | set(self._prev)new_map = {code: float(weights[i]) for i, code in enumerate(active)}turnover = 0.5 * sum(diff --git a/agent/tests/test_turnover_direction_changes.py b/agent/tests/test_turnover_direction_changes.pynew file mode 100644index 000000000..ae11030b2--- /dev/null+++ b/agent/tests/test_turnover_direction_changes.py@@ -0,0 +1,63 @@+"""Turnover penalties and reported changes operate on signed positions."""++import numpy as np+import pandas as pd+import pytest++from backtest.metrics import calc_turnover_series+from backtest.optimizers.turnover_aware import TurnoverAwareOptimizer+++def _inputs(flip: bool) -> tuple[pd.DataFrame, pd.DataFrame, pd.DatetimeIndex]:+ dates = pd.bdate_range("2025-01-01", periods=8)+ values = np.array([-0.01, 0.01, -0.02, 0.02, 0.01, 0.01, 0.02, -0.02])+ returns = pd.DataFrame({"A": values, "B": values}, index=dates)+ positions = pd.DataFrame(0.0, index=dates, columns=["A", "B"])+ positions.iloc[5:] = 1.0+ if flip:+ positions.iloc[6:, 0] = -1.0+ return returns, positions, dates++[email protected]("flip", [False, True])[email protected]("initial_sign", [-1.0, 1.0])+def test_reported_turnover_matches_signed_optimized_allocations(+ flip: bool, initial_sign: float+) -> None:+ """A 50% long becoming a 50% short trades 100%, giving turnover 0.5."""+ returns, positions, dates = _inputs(flip)+ positions *= initial_sign+ optimizer = TurnoverAwareOptimizer(lookback=5, max_per_name=0.5)+ result = optimizer.optimize(returns, positions, dates)++ actual = calc_turnover_series(result).iloc[5:].tolist()+ np.testing.assert_allclose(optimizer.realized_turnover, actual, atol=1e-7)+ assert actual[1] == pytest.approx(0.5 if flip else 0.0)+ assert actual[2] == pytest.approx(0.0)+++def test_reversal_penalty_can_reallocate_to_unchanged_direction() -> None:+ """Once reversing is correctly priced, holding the unflipped asset is cheaper."""+ returns, positions, dates = _inputs(True)+ optimizer = TurnoverAwareOptimizer(lookback=5, turnover_penalty=1.0)+ result = optimizer.optimize(returns, positions, dates)++ assert result.iloc[5]["A"] > 0.4+ assert abs(result.iloc[6]["A"]) < 0.01+ assert result.iloc[6]["B"] > 0.99+++def test_all_positions_can_reverse_without_an_invalid_solver_seed() -> None:+ returns, positions, dates = _inputs(False)+ positions.iloc[6:] = -1.0+ optimizer = TurnoverAwareOptimizer(lookback=5, turnover_penalty=1.0)+ result = optimizer.optimize(returns, positions, dates)++ np.testing.assert_allclose(result.iloc[5:].abs().sum(axis=1), 1.0)+ assert (result.iloc[6:] <= 0.0).all().all()+ np.testing.assert_allclose(+ optimizer.realized_turnover,+ calc_turnover_series(result).iloc[5:].tolist(),+ atol=1e-7,+ )+ assert optimizer.realized_turnover[1] == pytest.approx(1.0)