"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(factormodel): reject negative specific variances instead of clipping them to zero
Rudy Celeklia1c848fb960c
diff --git a/agent/src/quantlib/factormodel.py b/agent/src/quantlib/factormodel.pyindex 675c9d368..2f0d39eb3 100644--- a/agent/src/quantlib/factormodel.py+++ b/agent/src/quantlib/factormodel.py@@ -631,7 +631,8 @@ def factor_risk_decomposition(Raises:ValueError: If weights or matrices are empty, contain non-finite values,- or share no common assets or factors.+ share no common assets or factors, or a specific variance is+ negative."""w_series = pd.Series(portfolio_weights, dtype=float)if w_series.empty:@@ -681,6 +682,13 @@ def factor_risk_decomposition(spec_var_s = pd.Series(specific_variances, dtype=float)if not np.isfinite(spec_var_s.values).all():raise ValueError("specific_variances contains non-finite values")+ # Same tolerance as the factor_cov PSD check: clip rounding noise, but a+ # genuinely negative variance is bad input, not zero idiosyncratic risk.+ negative = spec_var_s[spec_var_s < -1e-8]+ if not negative.empty:+ raise ValueError(+ f"specific_variances must be non-negative, got {negative.to_dict()}"+ )d = spec_var_s.reindex(assets, fill_value=0.0).clip(lower=0.0)else:d = pd.Series(0.0, index=assets, dtype=float)diff --git a/agent/tests/quantlib/test_factormodel_negative_specific_variance.py b/agent/tests/quantlib/test_factormodel_negative_specific_variance.pynew file mode 100644index 000000000..f3a0f62d5--- /dev/null+++ b/agent/tests/quantlib/test_factormodel_negative_specific_variance.py@@ -0,0 +1,34 @@+"""A negative specific variance must raise, not be read as zero idiosyncratic risk."""++from __future__ import annotations++import pandas as pd+import pytest++from src.quantlib.factormodel import factor_risk_decomposition+++def _inputs():+ weights = {"A": 0.5, "B": 0.5}+ exposures = pd.DataFrame({"value": [1.0, 0.5]}, index=["A", "B"])+ factor_cov = pd.DataFrame({"value": [0.0625]}, index=["value"])+ return weights, exposures, factor_cov+++def test_negative_specific_variance_raises() -> None:+ weights, exposures, factor_cov = _inputs()+ with pytest.raises(ValueError, match="specific_variances must be non-negative"):+ factor_risk_decomposition(weights, exposures, factor_cov, {"A": 0.04, "B": -0.04})+++def test_rounding_noise_is_still_clipped() -> None:+ weights, exposures, factor_cov = _inputs()+ noisy = factor_risk_decomposition(weights, exposures, factor_cov, {"A": 0.04, "B": -1e-12})+ clean = factor_risk_decomposition(weights, exposures, factor_cov, {"A": 0.04, "B": 0.0})+ assert noisy.total_variance == pytest.approx(clean.total_variance)+++def test_valid_specific_variances_add_their_risk() -> None:+ weights, exposures, factor_cov = _inputs()+ result = factor_risk_decomposition(weights, exposures, factor_cov, {"A": 0.04, "B": 0.04})+ assert result.specific_variance == pytest.approx(0.25 * 0.04 + 0.25 * 0.04)