Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(optimizers): validate caps on single-asset allocations

Rudy Celekli20c06d096725
diff --git a/README.md b/README.md
index b5f588622..f3016b82a 100644
--- a/README.md
+++ b/README.md
@@ -798,6 +798,10 @@ Run `vibe-trading alpha list` to browse, `vibe-trading alpha show <id>` for form
Bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D, plus weekly / monthly (1W / 1M, built from daily bars). 15 metrics + benchmark comparison, **5 portfolio optimizers** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware), and 3 validation tools (Monte Carlo / Bootstrap / Walk-Forward).
+The turnover-aware optimizer validates per-name and group caps for single-asset
+allocations too. It preserves feasible supplied allocations (including cash),
+and raises an error when the singleton allocation exceeds a cap.
+
</details>
<details>
diff --git a/agent/backtest/optimizers/turnover_aware.py b/agent/backtest/optimizers/turnover_aware.py
index 1646edb0c..b3866fcdc 100644
--- a/agent/backtest/optimizers/turnover_aware.py
+++ b/agent/backtest/optimizers/turnover_aware.py
@@ -92,6 +92,43 @@ class TurnoverAwareOptimizer(BaseOptimizer):
self._prev: Dict[str, float] = {}
self.realized_turnover: List[float] = []
+ def optimize(
+ self,
+ ret: pd.DataFrame,
+ pos: pd.DataFrame,
+ dates: pd.DatetimeIndex,
+ ) -> pd.DataFrame:
+ """Validate caps even when a singleton needs no weight optimization.
+
+ The base singleton path preserves the supplied allocation, including
+ cash exposure. Reject violations rather than silently ignoring caps or
+ inventing a different cash/allocation policy.
+
+ Args:
+ ret: Historical returns aligned with positions.
+ pos: Signed signal allocations.
+ dates: Decision dates aligned with positions.
+
+ Returns:
+ Allocations adjusted by the optimizer, or the validated singleton.
+
+ Raises:
+ ValueError: A supplied singleton allocation violates an explicit cap.
+ """
+ if len(pos.columns) == 1:
+ code = pos.columns[0]
+ cap = self.max_per_name
+ group = self.groups.get(code)
+ if group in self.max_per_group:
+ group_cap = self.max_per_group[group]
+ cap = min(cap, group_cap) if cap is not None else group_cap
+ if cap is not None and (pos[code].abs() > cap + 1e-7).any():
+ raise ValueError(
+ "single-asset allocation exceeds exposure caps "
+ f"for {code}: maximum permitted weight is {cap:.6g}"
+ )
+ return super().optimize(ret, pos, dates)
+
def _build_context(
self, window: pd.DataFrame, active: List[str]
) -> "Dict[str, Any] | None":
diff --git a/agent/tests/test_turnover_single_asset_caps.py b/agent/tests/test_turnover_single_asset_caps.py
new file mode 100644
index 000000000..e1e2043fc
--- /dev/null
+++ b/agent/tests/test_turnover_single_asset_caps.py
@@ -0,0 +1,75 @@
+"""A single-asset fast path must not silently bypass exposure caps."""
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.optimizers.turnover_aware import TurnoverAwareOptimizer
+
+
[email protected]("direction", [1.0, -1.0])
+ "caps",
+ [
+ {"max_per_name": 0.4},
+ {"groups": {"A": "tech"}, "max_per_group": {"tech": 0.6}},
+ ],
+)
+def test_single_asset_infeasible_caps_fail_closed(caps: dict, direction: float) -> None:
+ """A fully invested singleton cannot fit below a sub-unit exposure cap."""
+ dates = pd.bdate_range("2025-01-01", periods=8)
+ returns = pd.DataFrame({"A": np.linspace(-0.01, 0.02, 8)}, index=dates)
+ positions = pd.DataFrame({"A": direction}, index=dates)
+ optimizer = TurnoverAwareOptimizer(lookback=5, **caps)
+
+ with pytest.raises(
+ ValueError, match="single-asset allocation exceeds exposure caps"
+ ):
+ optimizer.optimize(returns, positions, dates)
+
+
+ "caps",
+ [
+ {},
+ {"max_per_name": 1.0},
+ {"max_per_name": 0.4},
+ {"groups": {"A": "tech"}, "max_per_group": {"tech": 1.0}},
+ {"groups": {"OTHER": "tech"}, "max_per_group": {"tech": 0.4}},
+ ],
+)
+def test_feasible_single_asset_fast_path_is_unchanged(caps: dict) -> None:
+ dates = pd.bdate_range("2025-01-01", periods=8)
+ returns = pd.DataFrame({"A": np.linspace(-0.01, 0.02, 8)}, index=dates)
+ positions = pd.DataFrame({"A": -0.25}, index=dates)
+ optimizer = TurnoverAwareOptimizer(lookback=5, **caps)
+
+ pd.testing.assert_frame_equal(
+ optimizer.optimize(returns, positions, dates), positions
+ )
+
+
+def test_all_cash_single_asset_has_no_infeasible_allocation() -> None:
+ dates = pd.bdate_range("2025-01-01", periods=8)
+ returns = pd.DataFrame({"A": np.linspace(-0.01, 0.02, 8)}, index=dates)
+ positions = pd.DataFrame({"A": 0.0}, index=dates)
+ optimizer = TurnoverAwareOptimizer(lookback=5, max_per_name=0.4)
+
+ pd.testing.assert_frame_equal(
+ optimizer.optimize(returns, positions, dates), positions
+ )
+
+
+ "caps",
+ [{}, {"groups": {"OTHER": "tech"}, "max_per_group": {"tech": 0.4}}],
+)
+def test_uncapped_leveraged_singleton_retains_the_fast_path(caps: dict) -> None:
+ dates = pd.bdate_range("2025-01-01", periods=8)
+ returns = pd.DataFrame({"A": np.linspace(-0.01, 0.02, 8)}, index=dates)
+ positions = pd.DataFrame({"A": -2.0}, index=dates)
+ optimizer = TurnoverAwareOptimizer(lookback=5, **caps)
+
+ pd.testing.assert_frame_equal(
+ optimizer.optimize(returns, positions, dates), positions
+ )