Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(portfolio): constrain risk-parity weights

xkam7arb0793637fe9f
diff --git a/agent/backtest/optimizers/risk_parity.py b/agent/backtest/optimizers/risk_parity.py
index 0cf584755..59755527d 100644
--- a/agent/backtest/optimizers/risk_parity.py
+++ b/agent/backtest/optimizers/risk_parity.py
@@ -1,7 +1,4 @@
-"""Risk parity: equalize marginal risk contributions.
-
-Iterative refinement so w_i * MRC_i is approximately equal across assets.
-"""
+"""Long-only risk parity: equalize marginal risk contributions."""
from typing import Any, Dict
@@ -12,33 +9,44 @@ from backtest.optimizers.base import BaseOptimizer
class RiskParityOptimizer(BaseOptimizer):
- """Spinu (2013)-style inverse-vol seed + Newton-style refinement."""
+ """Equal-risk-contribution weights on the long-only simplex."""
def _calc_weights(self, ctx: Dict[str, Any]) -> np.ndarray:
"""Equal risk contribution weights."""
+ from scipy.optimize import minimize
+
cov = ctx["cov"]
n = cov.shape[0]
if n == 0:
return self._equal_weight(0)
vols = np.sqrt(np.diag(cov))
- if np.any(vols < 1e-12):
+ if not np.isfinite(cov).all() or np.any(vols < 1e-12):
return self._equal_weight(n)
inv_vol = 1.0 / vols
- w = inv_vol / inv_vol.sum()
-
- for _ in range(5):
- port_vol = np.sqrt(w @ cov @ w)
- if port_vol < 1e-12:
- break
- mrc = (cov @ w) / port_vol
- rc = w * mrc
- target = port_vol / n
- w = w * (target / (rc + 1e-12))
- w = w / w.sum()
-
- return w
+ seed = inv_vol / inv_vol.sum()
+
+ def contribution_error(w: np.ndarray) -> float:
+ variance = float(w @ cov @ w)
+ if not np.isfinite(variance) or variance <= 1e-18:
+ return 1e12
+ contributions = w * (cov @ w)
+ target = variance / n
+ return float(np.sum((contributions - target) ** 2) / variance**2)
+
+ result = minimize(
+ contribution_error,
+ seed,
+ method="SLSQP",
+ bounds=[(0.0, 1.0)] * n,
+ constraints={"type": "eq", "fun": lambda w: w.sum() - 1.0},
+ options={"maxiter": 200, "ftol": 1e-12},
+ )
+
+ if result.success and np.isfinite(result.x).all():
+ return self._normalize(result.x)
+ return self._normalize(seed)
def optimize(
diff --git a/agent/tests/test_risk_parity.py b/agent/tests/test_risk_parity.py
index 7427839b8..5587d2409 100644
--- a/agent/tests/test_risk_parity.py
+++ b/agent/tests/test_risk_parity.py
@@ -39,6 +39,27 @@ class TestRiskParityCalcWeights:
w = opt._calc_weights({"cov": cov})
assert np.all(w >= -1e-12)
+ def test_adverse_correlations_stay_on_long_only_simplex(self) -> None:
+ cov = np.array(
+ [
+ [0.0010518800707314143, -0.0008119306399469742, 0.0023898297080854735],
+ [-0.0008119306399469742, 0.0023829313617781014, -0.003778154624351108],
+ [0.002389829708085474, -0.003778154624351108, 0.00782499043215542],
+ ]
+ )
+
+ weights = RiskParityOptimizer()._calc_weights({"cov": cov})
+
+ assert np.isfinite(weights).all()
+ assert (weights >= 0.0).all()
+ assert weights.sum() == pytest.approx(1.0)
+ contributions = weights * (cov @ weights)
+ np.testing.assert_allclose(
+ contributions,
+ np.full(3, contributions.mean()),
+ rtol=1e-5,
+ )
+
def test_higher_vol_gets_lower_weight(self) -> None:
"""Asset with higher volatility should get lower weight."""
cov = np.diag([0.01, 0.04]) # vol = 0.1 vs 0.2