Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): validate factor covariance matrix symmetry and positive semi-definiteness

santhreal6f1e563f7021
diff --git a/agent/src/quantlib/factormodel.py b/agent/src/quantlib/factormodel.py
index 7eac99a52..293f38030 100644
--- a/agent/src/quantlib/factormodel.py
+++ b/agent/src/quantlib/factormodel.py
@@ -180,7 +180,7 @@ class FactorRiskDecomposition:
factor_pcr: Percentage contribution to risk (PCR) per factor.
asset_marginal_contributions: Marginal contribution to risk (MCR) per asset.
asset_risk_contributions: Absolute risk contribution per asset (sums to total volatility).
- asset_pcr: Percentage contribution to risk (PCR) per asset (sums to 1.0).
+ asset_pcr: Percentage contribution to risk (PCR) per asset (sums to 1.0 when total_volatility > 0, otherwise zero).
specific_risk_contributions: Specific risk contribution per asset.
specific_pcr: Percentage contribution from specific risk per asset.
"""
@@ -630,6 +630,12 @@ def factor_risk_decomposition(
X = X[factors]
F = factor_cov.loc[factors, factors]
+ F_mat = F.to_numpy(dtype=float)
+ if not np.allclose(F_mat, F_mat.T, atol=1e-8):
+ raise ValueError("factor_cov matrix must be symmetric")
+ eigvals = np.linalg.eigvalsh(F_mat)
+ if np.min(eigvals) < -1e-8:
+ raise ValueError("factor_cov matrix must be positive semi-definite")
# Align specific variances
if specific_variances is not None:
diff --git a/agent/tests/quantlib/test_factormodel.py b/agent/tests/quantlib/test_factormodel.py
index 228caadf2..74124c745 100644
--- a/agent/tests/quantlib/test_factormodel.py
+++ b/agent/tests/quantlib/test_factormodel.py
@@ -548,3 +548,17 @@ def test_factor_risk_decomposition_input_validation():
factor_risk_decomposition(
weights, exposures, pd.DataFrame([[0.04]], index=["other"], columns=["other"])
)
+
+ with pytest.raises(ValueError, match="symmetric"):
+ factor_risk_decomposition(
+ pd.Series([0.5, 0.5], index=["A", "B"]),
+ pd.DataFrame([[1.0, 0.5], [0.5, 1.0]], index=["A", "B"], columns=["F1", "F2"]),
+ pd.DataFrame([[0.04, 0.01], [0.03, 0.04]], index=["F1", "F2"], columns=["F1", "F2"]),
+ )
+
+ with pytest.raises(ValueError, match="positive semi-definite"):
+ factor_risk_decomposition(
+ pd.Series([0.5, 0.5], index=["A", "B"]),
+ pd.DataFrame([[1.0], [1.0]], index=["A", "B"], columns=["F1"]),
+ pd.DataFrame([[-0.04]], index=["F1"], columns=["F1"]),
+ )