Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(quantlib): add Archimedean and Gaussian copula analytics

santhreal40b662780379
diff --git a/README.md b/README.md
index c1a96567d..0167e4db3 100644
--- a/README.md
+++ b/README.md
@@ -614,7 +614,7 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
</details>
<details>
-<summary><b>Quant Library</b> <sub>286 tested functions across 19 modules, callable from every transport</sub></summary>
+<summary><b>Quant Library</b> <sub>294 tested functions across 19 modules, callable from every transport</sub></summary>
`src/quantlib` holds one tested implementation of each piece of finance math the
agent needs. Skills **import** these rather than carrying formulas inside
diff --git a/README_ar.md b/README_ar.md
index 48bae5d04..e4c7feb15 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -610,7 +610,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>Quant Library</b> <sub>286 دالة مختبَرة عبر 19 وحدة، قابلة للاستدعاء من كل المسارات</sub></summary>
+<summary><b>Quant Library</b> <sub>294 دالة مختبَرة عبر 19 وحدة، قابلة للاستدعاء من كل المسارات</sub></summary>
يحتفظ `src/quantlib` بتنفيذ مختبَر **واحد فقط** لكل قطعة من الرياضيات المالية التي
يحتاجها الـ agent. صارت الـ skills **تستورد** هذه الدوال بدلاً من حمل الصيغ داخل كتل
diff --git a/README_es.md b/README_es.md
index ab9c70de6..647f355a0 100644
--- a/README_es.md
+++ b/README_es.md
@@ -615,7 +615,7 @@ Barras intradía: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 métricas + comparació
</details>
<details>
-<summary><b>Quant Library</b> <sub>286 funciones probadas en 19 módulos, invocables desde cualquier transporte</sub></summary>
+<summary><b>Quant Library</b> <sub>294 funciones probadas en 19 módulos, invocables desde cualquier transporte</sub></summary>
`src/quantlib` contiene una implementación probada de cada pieza de matemática
financiera que el agente necesita. Las skills **importan** estas funciones en
diff --git a/README_ja.md b/README_ja.md
index 494a2ca08..b177107e1 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -610,7 +610,7 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
</details>
<details>
-<summary><b>Quant Library</b> <sub>19 モジュール・286 個のテスト済み関数、すべての経路から呼び出し可能</sub></summary>
+<summary><b>Quant Library</b> <sub>19 モジュール・294 個のテスト済み関数、すべての経路から呼び出し可能</sub></summary>
`src/quantlib` は、agent が必要とする金融数学のそれぞれについて、テスト済みの実装を
**1 つだけ**保持します。skill はこれらを **import** するようになり、markdown コード
diff --git a/README_ko.md b/README_ko.md
index 092f4db1d..573f88614 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -610,7 +610,7 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
</details>
<details>
-<summary><b>Quant Library</b> <sub>19개 모듈 286개의 테스트된 함수, 모든 경로에서 호출 가능</sub></summary>
+<summary><b>Quant Library</b> <sub>19개 모듈 294개의 테스트된 함수, 모든 경로에서 호출 가능</sub></summary>
`src/quantlib`는 agent가 필요로 하는 각 금융 수학에 대해 테스트된 구현을 **하나씩만**
보유합니다. skill은 이제 이 함수들을 **import**하며, markdown 코드 블록 안에 수식을
diff --git a/README_zh.md b/README_zh.md
index 61a55db26..c1b29b63a 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -607,7 +607,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>Quant Library</b> <sub>19 个模块 286 个经测试的函数,四条通路皆可调用</sub></summary>
+<summary><b>Quant Library</b> <sub>19 个模块 294 个经测试的函数,四条通路皆可调用</sub></summary>
`src/quantlib` 为 agent 需要的每一块金融数学各提供**一份**经测试的实现。skill 现在是
**import** 这些函数,而不再把公式抄在 markdown 代码块里——如果你在某个 `SKILL.md`
diff --git a/agent/src/quantlib/copula.py b/agent/src/quantlib/copula.py
new file mode 100644
index 000000000..8dcf57571
--- /dev/null
+++ b/agent/src/quantlib/copula.py
@@ -0,0 +1,180 @@
+"""Copula models for non-linear dependency and tail risk analysis.
+
+Implements bivariate Archimedean copulas (Clayton, Gumbel, Frank) and Gaussian copula,
+with Kendall's tau calibration and tail dependence coefficients.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Literal
+
+import numpy as np
+from scipy.stats import norm
+
+__all__ = [
+ "clayton_copula_cdf",
+ "clayton_tail_dependence",
+ "fit_copula_from_tau",
+ "frank_copula_cdf",
+ "gaussian_copula_cdf",
+ "gumbel_copula_cdf",
+ "gumbel_tail_dependence",
+ "pseudo_observations",
+]
+
+
+def pseudo_observations(data: np.ndarray) -> np.ndarray:
+ """Transform empirical data to uniform [0, 1] pseudo-observations via rank transformation.
+
+ Args:
+ data: 1-D or 2-D array of observations.
+
+ Returns:
+ Array of normalized ranks in (0, 1), shape matching ``data``.
+ """
+ arr = np.asarray(data, dtype=float)
+ if arr.ndim == 1:
+ n = len(arr)
+ ranks = np.argsort(np.argsort(arr)) + 1
+ return ranks / (n + 1.0)
+ elif arr.ndim == 2:
+ n = arr.shape[0]
+ ranks = np.argsort(np.argsort(arr, axis=0), axis=0) + 1
+ return ranks / (n + 1.0)
+ raise ValueError("data must be 1-D or 2-D")
+
+
+def clayton_copula_cdf(u: float | np.ndarray, v: float | np.ndarray, theta: float) -> float | np.ndarray:
+ """Evaluate bivariate Clayton copula CDF: C(u, v) = (u^{-theta} + v^{-theta} - 1)^{-1/theta}.
+
+ Args:
+ u: Uniform marginal in (0, 1].
+ v: Uniform marginal in (0, 1].
+ theta: Parameter > 0 (models lower tail dependence).
+
+ Returns:
+ Copula CDF value in [0, 1].
+ """
+ if theta <= 0.0:
+ raise ValueError(f"Clayton parameter theta must be strictly positive, got {theta}")
+ u_arr = np.asarray(u, dtype=float)
+ v_arr = np.asarray(v, dtype=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]")
+
+ val = np.maximum(0.0, u_arr ** (-theta) + v_arr ** (-theta) - 1.0) ** (-1.0 / theta)
+ return float(val) if np.ndim(val) == 0 else val
+
+
+def clayton_tail_dependence(theta: float) -> dict[str, float]:
+ """Calculate upper and lower tail dependence coefficients for Clayton copula.
+
+ Lower: lambda_L = 2^{-1/theta}, Upper: lambda_U = 0.
+ """
+ if theta <= 0.0:
+ raise ValueError(f"theta must be positive, got {theta}")
+ return {
+ "lambda_lower": float(2.0 ** (-1.0 / theta)),
+ "lambda_upper": 0.0,
+ }
+
+
+def gumbel_copula_cdf(u: float | np.ndarray, v: float | np.ndarray, theta: float) -> float | np.ndarray:
+ """Evaluate bivariate Gumbel copula CDF: C(u, v) = exp(-((-ln u)^theta + (-ln v)^theta)^{1/theta}).
+
+ Args:
+ u: Uniform marginal in (0, 1].
+ v: Uniform marginal in (0, 1].
+ theta: Parameter >= 1.0 (models upper tail dependence).
+ """
+ if theta < 1.0:
+ raise ValueError(f"Gumbel parameter theta must be >= 1.0, got {theta}")
+ u_arr = np.asarray(u, dtype=float)
+ v_arr = np.asarray(v, dtype=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]")
+
+ term = (-np.log(u_arr)) ** theta + (-np.log(v_arr)) ** theta
+ val = np.exp(-(term ** (1.0 / theta)))
+ return float(val) if np.ndim(val) == 0 else val
+
+
+def gumbel_tail_dependence(theta: float) -> dict[str, float]:
+ """Calculate upper and lower tail dependence coefficients for Gumbel copula.
+
+ Upper: lambda_U = 2 - 2^{1/theta}, Lower: lambda_L = 0.
+ """
+ if theta < 1.0:
+ raise ValueError(f"theta must be >= 1.0, got {theta}")
+ return {
+ "lambda_lower": 0.0,
+ "lambda_upper": float(2.0 - 2.0 ** (1.0 / theta)),
+ }
+
+
+def frank_copula_cdf(u: float | np.ndarray, v: float | np.ndarray, theta: float) -> float | np.ndarray:
+ """Evaluate bivariate Frank copula CDF: C(u, v) = -1/theta * ln(1 + (exp(-theta*u) - 1)*(exp(-theta*v) - 1)/(exp(-theta) - 1))."""
+ if theta == 0.0:
+ raise ValueError("Frank parameter theta must be non-zero (theta=0 is independence)")
+ u_arr = np.asarray(u, dtype=float)
+ v_arr = np.asarray(v, dtype=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]")
+
+ 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)
+ return float(val) if np.ndim(val) == 0 else val
+
+
+def gaussian_copula_cdf(u: float, v: float, rho: float) -> float:
+ """Evaluate bivariate Gaussian copula CDF."""
+ if not (-1.0 < rho < 1.0):
+ raise ValueError(f"rho must be strictly in (-1.0, 1.0), got {rho}")
+ if not (0.0 < u <= 1.0 and 0.0 < v <= 1.0):
+ raise ValueError("u and v must be in (0, 1]")
+
+ from scipy.stats import multivariate_normal
+
+ 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)
+ return float(val)
+
+
+def fit_copula_from_tau(tau: float, family: Literal["clayton", "gumbel", "gaussian"]) -> dict[str, float]:
+ """Calibrate copula parameter from Kendall's rank correlation tau.
+
+ Args:
+ tau: Kendall's tau in (-1.0, 1.0).
+ family: 'clayton', 'gumbel', or 'gaussian'.
+
+ Returns:
+ dict with keys:
+ * ``family`` (str)
+ * ``theta`` or ``rho`` (float)
+ * ``tau`` (float)
+ """
+ fam = family.strip().lower()
+ if fam == "clayton":
+ if tau <= 0.0 or tau >= 1.0:
+ raise ValueError("Clayton copula requires tau in (0, 1)")
+ theta = float(2.0 * tau / (1.0 - tau))
+ tail = clayton_tail_dependence(theta)
+ return {"family": "clayton", "theta": theta, "tau": tau, **tail}
+ elif fam == "gumbel":
+ if tau < 0.0 or tau >= 1.0:
+ raise ValueError("Gumbel copula requires tau in [0, 1)")
+ theta = float(1.0 / (1.0 - tau)) if tau < 1.0 else 1.0
+ tail = gumbel_tail_dependence(theta)
+ return {"family": "gumbel", "theta": theta, "tau": tau, **tail}
+ elif fam == "gaussian":
+ if not (-1.0 < tau < 1.0):
+ 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))
+ 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/src/tools/quantlib_tool.py b/agent/src/tools/quantlib_tool.py
index cdcff3638..60cdab4b4 100644
--- a/agent/src/tools/quantlib_tool.py
+++ b/agent/src/tools/quantlib_tool.py
@@ -82,6 +82,7 @@ ALLOWED_MODULES: dict[str, str] = {
"valuation.threestatement": "src.quantlib.valuation.threestatement",
"valuation.artifact": "src.quantlib.valuation.artifact",
"valuation.contracts": "src.quantlib.valuation.contracts",
+ "copula": "src.quantlib.copula",
}
#: Exported names refused because they write to a caller-supplied path. This
diff --git a/agent/tests/quantlib/test_copula.py b/agent/tests/quantlib/test_copula.py
new file mode 100644
index 000000000..992d971c8
--- /dev/null
+++ b/agent/tests/quantlib/test_copula.py
@@ -0,0 +1,73 @@
+"""Tests for Copula models and tail dependence analytics."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+from src.quantlib.copula import (
+ clayton_copula_cdf,
+ clayton_tail_dependence,
+ fit_copula_from_tau,
+ frank_copula_cdf,
+ gaussian_copula_cdf,
+ gumbel_copula_cdf,
+ gumbel_tail_dependence,
+ pseudo_observations,
+)
+
+
+class TestCopulaAnalytics:
+ """Validate copula CDF properties, tail dependencies, and tau calibration."""
+
+ def test_pseudo_observations(self) -> None:
+ data = np.array([10.0, 50.0, 20.0, 40.0])
+ u = pseudo_observations(data)
+ # ranks: 10->1, 20->2, 40->3, 50->4. divided by (4+1=5) -> [0.2, 0.8, 0.4, 0.6]
+ assert np.allclose(u, [0.2, 0.8, 0.4, 0.6])
+
+ def test_clayton_copula_properties(self) -> None:
+ # C(u, 1) = u, C(1, v) = v
+ u = 0.4
+ theta = 2.0
+ assert clayton_copula_cdf(u, 1.0, theta) == pytest.approx(u)
+ assert clayton_copula_cdf(1.0, u, theta) == pytest.approx(u)
+
+ # Tail dependence for theta=2.0 -> 2^{-1/2} = 1/sqrt(2) ~ 0.7071
+ tail = clayton_tail_dependence(2.0)
+ assert tail["lambda_lower"] == pytest.approx(np.sqrt(0.5))
+ assert tail["lambda_upper"] == 0.0
+
+ def test_gumbel_copula_properties(self) -> None:
+ u = 0.6
+ theta = 1.5
+ assert gumbel_copula_cdf(u, 1.0, theta) == pytest.approx(u)
+
+ tail = gumbel_tail_dependence(2.0)
+ # lambda_U = 2 - 2^{1/2} = 2 - sqrt(2) ~ 0.5858
+ assert tail["lambda_upper"] == pytest.approx(2.0 - np.sqrt(2.0))
+ assert tail["lambda_lower"] == 0.0
+
+ def test_frank_copula_properties(self) -> None:
+ u = 0.5
+ theta = 3.0
+ assert frank_copula_cdf(u, 1.0, theta) == pytest.approx(u)
+
+ def test_gaussian_copula_properties(self) -> None:
+ u, v = 0.5, 0.5
+ # For rho=0, independent copula C(0.5, 0.5) = 0.25
+ val = gaussian_copula_cdf(u, v, rho=0.0)
+ assert val == pytest.approx(0.25, abs=1e-4)
+
+ def test_fit_copula_from_tau(self) -> None:
+ # Clayton: tau = 0.5 -> theta = 2*0.5/(1-0.5) = 2.0
+ res_clay = fit_copula_from_tau(0.5, family="clayton")
+ assert res_clay["theta"] == pytest.approx(2.0)
+
+ # Gumbel: tau = 0.5 -> theta = 1/(1-0.5) = 2.0
+ res_gum = fit_copula_from_tau(0.5, family="gumbel")
+ assert res_gum["theta"] == pytest.approx(2.0)
+
+ # Gaussian: tau = 0.5 -> rho = sin(pi/4) ~ 0.7071
+ res_gauss = fit_copula_from_tau(0.5, family="gaussian")
+ assert res_gauss["rho"] == pytest.approx(np.sin(np.pi / 4))