Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): handle Gaussian copula correlations near their limits

Rudy Celekli9e3d7c1a4146
diff --git a/agent/src/quantlib/copula.py b/agent/src/quantlib/copula.py
index 2dfa4c140..22b285233 100644
--- a/agent/src/quantlib/copula.py
+++ b/agent/src/quantlib/copula.py
@@ -200,7 +200,11 @@ def gaussian_copula_cdf(u: float, v: float, rho: float) -> float:
z1 = float(norm.ppf(u))
z2 = float(norm.ppf(v))
cov = [[1.0, rho], [rho, 1.0]]
- val = multivariate_normal.cdf([z1, z2], mean=[0.0, 0.0], cov=cov)
+ # Near-perfect valid correlations can be numerically rank deficient under
+ # SciPy's tolerance. This covariance remains positive semidefinite.
+ val = multivariate_normal.cdf(
+ [z1, z2], mean=[0.0, 0.0], cov=cov, allow_singular=True
+ )
return float(val)
@@ -235,6 +239,10 @@ def fit_copula_from_tau(tau: float, family: Literal["clayton", "gumbel", "gaussi
raise ValueError("Gaussian copula requires tau in (-1, 1)")
# Greiner's relation: rho = sin(pi/2 * tau)
rho = float(math.sin(math.pi * 0.5 * tau))
+ # sin rounds to an exact endpoint for some valid interior tau values.
+ # Preserve the strict open interval required by gaussian_copula_cdf.
+ if abs(rho) == 1.0:
+ rho = math.nextafter(rho, 0.0)
return {"family": "gaussian", "rho": rho, "tau": tau, "lambda_lower": 0.0, "lambda_upper": 0.0}
else:
raise ValueError(f"Unsupported family: {family}")
diff --git a/agent/tests/quantlib/test_gaussian_copula_boundary.py b/agent/tests/quantlib/test_gaussian_copula_boundary.py
new file mode 100644
index 000000000..ef5ba6117
--- /dev/null
+++ b/agent/tests/quantlib/test_gaussian_copula_boundary.py
@@ -0,0 +1,25 @@
+import numpy as np
+import pytest
+
+from src.quantlib.copula import fit_copula_from_tau, gaussian_copula_cdf
+
+
[email protected]("rho,expected", [(0.9999999999, 0.3), (-0.9999999999, 0.1)])
+def test_near_perfect_valid_correlation_has_a_finite_cdf(rho, expected):
+ value = gaussian_copula_cdf(0.3, 0.8, rho)
+ assert np.isfinite(value)
+ assert value == pytest.approx(expected, abs=2e-5)
+
+
[email protected]("tau,expected", [(0.9999999999, 0.3), (-0.9999999999, 0.1)])
+def test_valid_tau_calibration_can_be_consumed_by_the_cdf(tau, expected):
+ result = fit_copula_from_tau(tau, "gaussian")
+ assert -1.0 < result["rho"] < 1.0
+ value = gaussian_copula_cdf(0.3, 0.8, result["rho"])
+ assert value == pytest.approx(expected, abs=2e-5)
+
+
[email protected]("rho", [-1.0, 1.0])
+def test_exact_correlation_endpoints_still_fail_validation(rho):
+ with pytest.raises(ValueError, match="rho must be"):
+ gaussian_copula_cdf(0.3, 0.8, rho)