Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): make the Frank copula stable at both ends of theta

Haozhe Wu97c5afcdcc10
diff --git a/agent/src/quantlib/copula.py b/agent/src/quantlib/copula.py
index f57368847..095a364cf 100644
--- a/agent/src/quantlib/copula.py
+++ b/agent/src/quantlib/copula.py
@@ -134,22 +134,43 @@ def frank_copula_cdf(u: float | np.ndarray, v: float | np.ndarray, theta: float)
if np.any((u_arr <= 0.0) | (u_arr > 1.0) | (v_arr <= 0.0) | (v_arr > 1.0)):
raise ValueError("u and v marginals must be in (0, 1]")
- # The naive form cancels catastrophically for large theta (num/den -> -1,
- # log(0) -> -inf). For theta > 0, factor e^{-theta*s} out of the numerator
- # and compute in log space; each correction term underflows to 0.0
- # harmlessly. For theta < 0 the direct form is stable over any realistic
- # parameter, so it is kept unchanged.
+ # The naive form breaks at both ends of the parameter range, so neither
+ # sign keeps it. For theta > 0 it cancels catastrophically (num/den -> -1,
+ # log(0) -> -inf); for theta < 0 every factor is positive but
+ # (e^{|theta|u} - 1)(e^{|theta|v} - 1) overflows to inf from
+ # |theta| ~ 355, which is the same failure the positive branch was fixed
+ # for and just as reachable (Kendall tau -> -1 is a real regime).
if theta > 0:
s = np.minimum(u_arr, v_arr)
t = np.maximum(u_arr, v_arr)
- inner = 1.0 + np.exp(-theta * (t - s)) - np.exp(-theta * t) - np.exp(-theta * (1.0 - s))
+ # inner = 1 + e^{-th(t-s)} - e^{-th t} - e^{-th(1-s)} written as a sum
+ # of two POSITIVE terms via expm1. Spelled with plain exp it is a
+ # 1+1-1-1 cancellation as theta -> 0: at theta=1e-6 it kept ~6 digits,
+ # and the 1/theta factor below multiplied that error by 1e6 (C(0.3,0.7)
+ # came out 0.20974 against the independence limit 0.21, breaking the
+ # Frechet lower bound).
+ inner = -(
+ np.expm1(-theta * t)
+ + np.exp(-theta * (t - s)) * np.expm1(-theta * (1.0 - t))
+ )
log_num = -theta * s + np.log(inner)
- log_den = np.log1p(-np.exp(-theta))
+ log_den = np.log(-np.expm1(-theta))
val = -(1.0 / theta) * (log_num - log_den)
else:
- num = (np.exp(-theta * u_arr) - 1.0) * (np.exp(-theta * v_arr) - 1.0)
- den = np.exp(-theta) - 1.0
- val = -1.0 / theta * np.log(1.0 + num / den)
+ # phi = -theta > 0. Every term is positive here, so the ratio needs no
+ # cancellation guard — only its logarithm, computed with
+ # log(e^{phi x} - 1) = phi x + log1p(-e^{-phi x}):
+ # log r = log(e^{phi u} - 1) + log(e^{phi v} - 1) - log(e^{phi} - 1)
+ # C = log(1 + r) / phi = logaddexp(0, log r) / phi
+ phi = -theta
+ log_num = (
+ phi * u_arr
+ + np.log(-np.expm1(-phi * u_arr))
+ + phi * v_arr
+ + np.log(-np.expm1(-phi * v_arr))
+ )
+ log_den = phi + np.log(-np.expm1(-phi))
+ val = np.logaddexp(0.0, log_num - log_den) / phi
return float(val) if np.ndim(val) == 0 else val
diff --git a/agent/tests/quantlib/test_copula.py b/agent/tests/quantlib/test_copula.py
index 52616dc87..ce1421c51 100644
--- a/agent/tests/quantlib/test_copula.py
+++ b/agent/tests/quantlib/test_copula.py
@@ -95,3 +95,52 @@ class TestCopulaAnalytics:
assert frank_copula_cdf(0.3, 0.7, 200.0) == pytest.approx(0.3, abs=1e-6)
assert clayton_copula_cdf(0.3, 0.7, 10000.0) == pytest.approx(0.3, abs=1e-6)
assert gumbel_copula_cdf(0.3, 0.7, 3000.0) == pytest.approx(0.3, abs=1e-6)
+
+ def test_frank_copula_is_stable_for_large_negative_theta(self) -> None:
+ # Strong NEGATIVE dependence is the mirror of the large-theta case and
+ # was left broken: (e^{|theta|u} - 1)(e^{|theta|v} - 1) overflows to
+ # inf from |theta| ~ 355, so the CDF returned inf and then nan.
+ # References computed at 2500-digit precision.
+ assert frank_copula_cdf(0.5, 0.5, -700.0) == pytest.approx(
+ 0.000990210257942779, abs=1e-12
+ )
+ assert frank_copula_cdf(0.99, 0.99, -700.0) == pytest.approx(0.98, abs=1e-12)
+ assert frank_copula_cdf(0.5, 0.5, -5000.0) == pytest.approx(
+ 0.00013862943611198905, abs=1e-12
+ )
+
+ def test_frank_copula_approaches_independence_for_tiny_theta(self) -> None:
+ # theta -> 0 is the independence copula (C = u*v). The log-space form
+ # spelled with plain exp cancelled to ~6 digits there and the 1/theta
+ # factor blew that up: C(0.3, 0.7) came out 0.20974, below the Frechet
+ # lower bound. Exact value at 400-digit precision: 0.2100000220499994.
+ # 1e-8 is the float64 floor here: the 1/theta factor is 1e6, so a
+ # last-bit error in the logs lands at ~1e-9. The pre-fix error was
+ # 2.6e-4, five orders coarser.
+ assert frank_copula_cdf(0.3, 0.7, 1e-6) == pytest.approx(
+ 0.2100000220499994, abs=1e-8
+ )
+ assert frank_copula_cdf(0.3, 0.7, -1e-6) == pytest.approx(0.21, abs=1e-6)
+
+ def test_archimedean_cdfs_respect_frechet_bounds(self) -> None:
+ # max(u+v-1, 0) <= C(u, v) <= min(u, v) for every copula, at every
+ # parameter — the property each numerical failure above violated.
+ grid = np.linspace(0.02, 1.0, 15)
+ cases = (
+ (frank_copula_cdf, [-5000.0, -700.0, -1.0, 1e-6, 5.0, 700.0, 5000.0]),
+ (clayton_copula_cdf, [1e-3, 5.0, 1e4, 1e6]),
+ (gumbel_copula_cdf, [1.0, 5.0, 3000.0, 1e5]),
+ )
+ for fn, thetas in cases:
+ for theta in thetas:
+ for u in grid:
+ for v in grid:
+ val = fn(float(u), float(v), theta)
+ assert np.isfinite(val), (fn.__name__, theta, u, v)
+ assert max(u + v - 1.0, 0.0) - 1e-9 <= val <= min(u, v) + 1e-9, (
+ fn.__name__,
+ theta,
+ u,
+ v,
+ val,
+ )