"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(quantlib): stabilize covariance weights and validate singleton variances
Rudy Celeklie270d0ebc9cb
diff --git a/agent/src/quantlib/portfolio.py b/agent/src/quantlib/portfolio.pyindex a53bf9d57..e346f02a0 100644--- a/agent/src/quantlib/portfolio.py+++ b/agent/src/quantlib/portfolio.py@@ -7,7 +7,6 @@ Implements Marcos López de Prado's (2016) Hierarchical Risk Parity algorithm:"""-import numpy as npimport pandas as pdfrom scipy.cluster.hierarchy import linkage@@ -83,9 +82,13 @@ def inverse_variance_weights(cov: pd.DataFrame | np.ndarray) -> np.ndarray:if c.ndim != 2 or c.shape[0] != c.shape[1]:raise ValueError("Covariance matrix must be square 2-D")variances = np.diag(c)- if np.any(variances <= 0.0):- raise ValueError("All asset variances on the diagonal must be strictly positive")- inv_var = 1.0 / variances+ if not np.isfinite(variances).all() or np.any(variances <= 0.0):+ raise ValueError(+ "All asset variances on the diagonal must be finite and strictly positive"+ )+ # Scaling by the smallest variance cancels during normalization and avoids+ # overflow in 1 / variance for valid subnormal positive variances.+ inv_var = variances.min() / variancesreturn inv_var / np.sum(inv_var)@@ -130,20 +133,21 @@ def hierarchical_risk_parity(n = cov_mat.shape[0]if n == 0:raise ValueError("Covariance matrix cannot be empty")+ diag = np.diag(cov_mat)+ if not np.isfinite(diag).all() or np.any(diag <= 0.0):+ raise ValueError("Diagonal variances must be finite and strictly positive")if n == 1:return pd.Series([1.0], index=labels) if is_df else np.array([1.0])- diag = np.diag(cov_mat)- if np.any(diag <= 0.0):- raise ValueError("Diagonal variances must be strictly positive")-if corr is None:std = np.sqrt(diag)corr_mat = cov_mat / np.outer(std, std)else:if is_df and isinstance(corr, pd.DataFrame):if set(corr.index) != set(labels) or set(corr.columns) != set(labels):- raise ValueError("Correlation matrix labels must match covariance labels")+ raise ValueError(+ "Correlation matrix labels must match covariance labels"+ )corr = corr.loc[labels, labels]corr_mat = np.asarray(corr, dtype=float)if corr_mat.shape != cov_mat.shape:diff --git a/agent/tests/quantlib/test_covariance_weight_stability.py b/agent/tests/quantlib/test_covariance_weight_stability.pynew file mode 100644index 000000000..48da97378--- /dev/null+++ b/agent/tests/quantlib/test_covariance_weight_stability.py@@ -0,0 +1,31 @@+import numpy as np+import pytest+from src.quantlib.portfolio import hierarchical_risk_parity, inverse_variance_weights+++def test_inverse_weights_remain_finite_for_small_positive_variances() -> None:+ cov = np.diag([1e-310, 2e-310])+ actual = inverse_variance_weights(cov)+ assert np.isfinite(actual).all()+ np.testing.assert_allclose(actual, [2 / 3, 1 / 3])++[email protected]("variance", [0.0, -1.0, float("nan"), float("inf")])+def test_singleton_hrp_rejects_invalid_variance_before_assigning_weight(+ variance: float,+) -> None:+ with pytest.raises(ValueError, match="strictly positive"):+ hierarchical_risk_parity(np.array([[variance]]))++[email protected]("variance", [float("nan"), float("inf")])+def test_inverse_weights_reject_nonfinite_variance(variance: float) -> None:+ with pytest.raises(ValueError, match="strictly positive"):+ inverse_variance_weights(np.diag([0.04, variance]))+++def test_valid_singleton_and_ordinary_inverse_weights_are_unchanged() -> None:+ np.testing.assert_array_equal(hierarchical_risk_parity(np.array([[0.04]])), [1.0])+ np.testing.assert_allclose(+ inverse_variance_weights(np.diag([0.04, 0.16])), [0.8, 0.2]+ )