Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): correct the Heston skew sign; reconcile the badge after five merges

Haozhe Wud62244c28753
diff --git a/README.md b/README.md
index 715c3187b..fbb271a1d 100644
--- a/README.md
+++ b/README.md
@@ -619,7 +619,7 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
</details>
<details>
-<summary><b>Quant Library</b> <sub>289 tested functions across 19 modules, callable from every transport</sub></summary>
+<summary><b>Quant Library</b> <sub>306 tested functions across 23 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
@@ -638,6 +638,10 @@ that is a bug, not a pattern.
| `factormodel` · `eventstudy` | Factor regressions, event studies |
| `multipletesting` · `crossvalidation` | Deflated significance, purged CV |
| `impact` | Market-impact models |
+| `volatility` | Heston (1993) stochastic-volatility pricing |
+| `portfolio` | Hierarchical Risk Parity allocation |
+| `copula` | Gaussian and Archimedean copulas |
+| `microstructure` | VPIN, Roll spread, Amihud illiquidity, Kyle's lambda |
The read-only `quantlib_call` tool reaches all of it through one contract, so the
finance math works on the CLI, the Web UI, the REST API and MCP — including
diff --git a/README_ar.md b/README_ar.md
index c9bd9cf8e..48242e7e6 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -613,7 +613,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>Quant Library</b> <sub>289 دالة مختبَرة عبر 19 وحدة، قابلة للاستدعاء من كل المسارات</sub></summary>
+<summary><b>Quant Library</b> <sub>306 دالة مختبَرة عبر 23 وحدة، قابلة للاستدعاء من كل المسارات</sub></summary>
يحتفظ `src/quantlib` بتنفيذ مختبَر **واحد فقط** لكل قطعة من الرياضيات المالية التي
يحتاجها الـ agent. صارت الـ skills **تستورد** هذه الدوال بدلاً من حمل الصيغ داخل كتل
@@ -631,6 +631,10 @@ LONGBRIDGE_ACCESS_TOKEN=...
| `factormodel` · `eventstudy` | انحدارات العوامل، ودراسات الأحداث |
| `multipletesting` · `crossvalidation` | ضبط الدلالة المتعددة، وpurged CV |
| `impact` | نماذج أثر السوق |
+| `volatility` | تسعير التقلب العشوائي وفق Heston (1993) |
+| `portfolio` | توزيع تكافؤ المخاطر الهرمي (HRP) |
+| `copula` | روابط غاوسية وأرخميدية |
+| `microstructure` | VPIN ومدى Roll وانعدام سيولة Amihud ولامدا Kyle |
تصل الأداة `quantlib_call` للقراءة فقط إلى كل ذلك عبر عقد واحد، فتعمل الرياضيات المالية
على CLI وWeb UI وREST API وMCP حيث يكون `bash` مُقفلاً. وهي بنيوياً **ليست** shell — قائمة وحدات
diff --git a/README_es.md b/README_es.md
index bdd42ae96..00fee6cdc 100644
--- a/README_es.md
+++ b/README_es.md
@@ -618,7 +618,7 @@ Barras intradía: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 métricas + comparació
</details>
<details>
-<summary><b>Quant Library</b> <sub>289 funciones probadas en 19 módulos, invocables desde cualquier transporte</sub></summary>
+<summary><b>Quant Library</b> <sub>306 funciones probadas en 23 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
@@ -637,6 +637,10 @@ una fórmula de pricing viviendo en un `SKILL.md`, eso es un bug, no un patrón.
| `factormodel` · `eventstudy` | Regresiones de factores, estudios de eventos |
| `multipletesting` · `crossvalidation` | Significancia deflacionada, CV purgada |
| `impact` | Modelos de impacto de mercado |
+| `volatility` | Valoración con volatilidad estocástica de Heston (1993) |
+| `portfolio` | Asignación por Paridad de Riesgo Jerárquica (HRP) |
+| `copula` | Cópulas gaussianas y arquimedianas |
+| `microstructure` | VPIN, spread de Roll, iliquidez de Amihud, lambda de Kyle |
La herramienta de solo lectura `quantlib_call` da acceso a todo esto mediante un
único contrato, de modo que la matemática financiera funciona en la CLI, la Web
diff --git a/README_ja.md b/README_ja.md
index 0d24a4ab4..d730a4e76 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -613,7 +613,7 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
</details>
<details>
-<summary><b>Quant Library</b> <sub>19 モジュール・289 個のテスト済み関数、すべての経路から呼び出し可能</sub></summary>
+<summary><b>Quant Library</b> <sub>23 モジュール・306 個のテスト済み関数、すべての経路から呼び出し可能</sub></summary>
`src/quantlib` は、agent が必要とする金融数学のそれぞれについて、テスト済みの実装を
**1 つだけ**保持します。skill はこれらを **import** するようになり、markdown コード
@@ -632,6 +632,10 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
| `factormodel` · `eventstudy` | ファクター回帰、イベントスタディ |
| `multipletesting` · `crossvalidation` | 多重検定調整、purged CV |
| `impact` | マーケットインパクトモデル |
+| `volatility` | Heston (1993) 確率的ボラティリティ価格付け |
+| `portfolio` | 階層的リスクパリティ(HRP)配分 |
+| `copula` | ガウス・アルキメデス型コピュラ |
+| `microstructure` | VPIN、Roll スプレッド、Amihud 非流動性、Kyle ラムダ |
読み取り専用の `quantlib_call` ツールが 1 つの契約で全体に到達するため、`bash` が
無効化されている CLI・Web UI・REST API・MCP でも金融数学が使えます。構造的に shell では
diff --git a/README_ko.md b/README_ko.md
index 5d8f0fd42..0c4aa03f4 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -613,7 +613,7 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
</details>
<details>
-<summary><b>Quant Library</b> <sub>19개 모듈 289개의 테스트된 함수, 모든 경로에서 호출 가능</sub></summary>
+<summary><b>Quant Library</b> <sub>23개 모듈 306개의 테스트된 함수, 모든 경로에서 호출 가능</sub></summary>
`src/quantlib`는 agent가 필요로 하는 각 금융 수학에 대해 테스트된 구현을 **하나씩만**
보유합니다. skill은 이제 이 함수들을 **import**하며, markdown 코드 블록 안에 수식을
@@ -632,6 +632,10 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
| `factormodel` · `eventstudy` | 팩터 회귀, 이벤트 스터디 |
| `multipletesting` · `crossvalidation` | 다중검정 보정, purged CV |
| `impact` | 시장충격 모델 |
+| `volatility` | Heston (1993) 확률적 변동성 가격결정 |
+| `portfolio` | 계층적 리스크 패리티(HRP) 배분 |
+| `copula` | 가우시안 및 아르키메데스 코퓰러 |
+| `microstructure` | VPIN, Roll 스프레드, Amihud 비유동성, Kyle 람다 |
읽기 전용 `quantlib_call` 도구가 하나의 계약으로 전체에 도달하므로, `bash`가 차단된
CLI·Web UI·REST API·MCP에서도 금융 수학이 동작합니다. 구조적으로 shell이 **아닙니다** —
diff --git a/README_zh.md b/README_zh.md
index 7e3115753..f2b261e16 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -610,7 +610,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>Quant Library</b> <sub>19 个模块 289 个经测试的函数,四条通路皆可调用</sub></summary>
+<summary><b>Quant Library</b> <sub>23 个模块 306 个经测试的函数,四条通路皆可调用</sub></summary>
`src/quantlib` 为 agent 需要的每一块金融数学各提供**一份**经测试的实现。skill 现在是
**import** 这些函数,而不再把公式抄在 markdown 代码块里——如果你在某个 `SKILL.md`
@@ -628,6 +628,10 @@ LONGBRIDGE_ACCESS_TOKEN=...
| `factormodel` · `eventstudy` | 因子回归、事件研究 |
| `multipletesting` · `crossvalidation` | 去偏显著性、purged CV |
| `impact` | 市场冲击模型 |
+| `volatility` | Heston (1993) 随机波动率定价 |
+| `portfolio` | 分层风险平价(HRP)配置 |
+| `copula` | 高斯与阿基米德 Copula |
+| `microstructure` | VPIN、Roll 价差、Amihud 非流动性、Kyle lambda |
只读工具 `quantlib_call` 用一份契约触达全部函数,因此在 `bash` 被关闭的 CLI、Web UI、
REST API 与 MCP 上金融数学照样可用。它在结构上**不是 shell**——模块白名单、只按 `__all__` 分派、
diff --git a/agent/src/quantlib/volatility.py b/agent/src/quantlib/volatility.py
index 3b9def497..030959fe8 100644
--- a/agent/src/quantlib/volatility.py
+++ b/agent/src/quantlib/volatility.py
@@ -151,6 +151,14 @@ def heston_price(
def integrand(u: float) -> float:
if u == 0.0:
return 0.0
+ # The sign of this exponent is load-bearing and invisible to the usual
+ # sanity checks. With sigma_v -> 0 the centered CF is real, so
+ # Re[e^{+iuk} phi] == Re[e^{-iuk} phi] and the Black-Scholes limit
+ # passes either way; at-the-money k is 0, so benchmark and put-call
+ # parity checks pass either way too. It only shows up once rho != 0,
+ # where flipping it inverts the volatility skew — a negative rho would
+ # price OTM calls richer than ITM ones. test_volatility pins the skew
+ # direction for exactly this reason.
# Centered characteristic function for u - i/2
phi = heston_characteristic_function(
u=u - 0.5j,
@@ -164,7 +172,7 @@ def heston_price(
sigma_v=sigma_v,
rho=rho,
)
- val = cmath.exp(-1j * u * k) * phi / (u**2 + 0.25)
+ val = cmath.exp(1j * u * k) * phi / (u**2 + 0.25)
return float(val.real)
integ, _ = quad(integrand, 0.0, integration_limit, limit=2000)
diff --git a/agent/tests/quantlib/test_volatility.py b/agent/tests/quantlib/test_volatility.py
index 843fd28ac..fcbef956b 100644
--- a/agent/tests/quantlib/test_volatility.py
+++ b/agent/tests/quantlib/test_volatility.py
@@ -7,7 +7,7 @@ from src.quantlib.volatility import (
heston_price,
heston_feller_condition,
)
-from src.quantlib.options import bs_price
+from src.quantlib.options import bs_price, implied_volatility
class TestHestonModel:
@@ -86,6 +86,43 @@ class TestHestonModel:
bs = bs_price(S=S0, K=K, T=T, r=r, sigma=vol, option_type="call", q=q)
assert pytest.approx(h_price, abs=1e-3) == bs
+ def test_negative_rho_produces_a_downward_sloping_skew(self):
+ """A leverage-effect correlation must make low strikes the expensive ones.
+
+ This is the only property in this file that can see the sign of the
+ Lewis integrand's ``e^{iuk}`` factor. With ``sigma_v -> 0`` the centered
+ characteristic function is real, so the Black-Scholes limit is identical
+ under either sign; at the money ``k`` is zero, so the benchmark and the
+ put-call parity check are identical too. Flipping the sign inverts the
+ skew and nothing else in the suite moves.
+ """
+ S0, T, r, q = 100.0, 1.0, 0.02, 0.01
+ kappa, theta, sigma_v, v0 = 3.0, 0.04, 0.2, 0.04
+
+ def iv(K: float, rho: float) -> float:
+ price = heston_price(
+ S0, K, T, r, v0, kappa, theta, sigma_v, rho, option_type="call", q=q
+ )
+ return implied_volatility(price, S0, K, T, r, "call", q=q)
+
+ low, high = 80.0, 120.0
+ assert iv(low, -0.6) > iv(high, -0.6), "rho < 0 must give a negative skew"
+ assert iv(low, 0.6) < iv(high, 0.6), "rho > 0 must give a positive skew"
+ # Symmetric parameters: flipping rho must mirror the smile, not shift it.
+ assert iv(low, -0.6) == pytest.approx(iv(high, 0.6), abs=2e-3)
+
+ def test_negative_rho_cheapens_out_of_the_money_calls(self):
+ """The price-level consequence of the skew, checked without inverting IV."""
+ S0, K, T, r, q = 100.0, 120.0, 1.0, 0.02, 0.01
+ kappa, theta, sigma_v, v0 = 3.0, 0.04, 0.2, 0.04
+
+ def price(rho: float) -> float:
+ return heston_price(
+ S0, K, T, r, v0, kappa, theta, sigma_v, rho, option_type="call", q=q
+ )
+
+ assert price(-0.6) < price(0.0) < price(0.6)
+
def test_invalid_parameters_raise(self):
with pytest.raises(ValueError):
heston_price(S0=-100.0, K=100.0, T=1.0, r=0.05, v0=0.04, kappa=1.0, theta=0.04, sigma_v=0.3, rho=0.0)
diff --git a/agent/tests/test_readme_counts.py b/agent/tests/test_readme_counts.py
index e38b10621..ce3aebc5e 100644
--- a/agent/tests/test_readme_counts.py
+++ b/agent/tests/test_readme_counts.py
@@ -155,6 +155,34 @@ def _quantlib_export_count() -> int:
return total
+def _quantlib_module_count() -> int:
+ """Count the `src/quantlib` submodules the badge claims.
+
+ Counted the same way the function total is: a submodule that exports an
+ `__all__` is one module of the library. The badge states both numbers and
+ only the function half was ever guarded, so four modules landed while the
+ badge still said nineteen — the count was right about functions and wrong
+ about modules for as long as nobody read it.
+
+ Returns:
+ Number of `quantlib` submodules exporting `__all__`.
+ """
+ import importlib
+ import pkgutil
+
+ if str(AGENT_DIR) not in sys.path:
+ sys.path.insert(0, str(AGENT_DIR))
+ quantlib = importlib.import_module("src.quantlib")
+
+ return len(
+ [
+ module
+ for module in pkgutil.walk_packages(quantlib.__path__, "src.quantlib.")
+ if getattr(importlib.import_module(module.name), "__all__", None)
+ ]
+ )
+
+
def _counts() -> dict[str, int]:
"""Return every code-derived count the READMEs state.
@@ -326,6 +354,20 @@ def test_feature_badges_state_the_real_counts(name: str) -> None:
)
[email protected]("name", READMES)
+def test_quantlib_badge_states_both_the_function_and_module_counts(name: str) -> None:
+ """The Quant Library badge carries two numbers; both must be the real ones."""
+ badge = _badges(_read(name))[BADGE_ORDER.index("quantlib")]
+
+ assert _numbers(badge) == {
+ str(_quantlib_export_count()),
+ str(_quantlib_module_count()),
+ }, (
+ f"{name}: quantlib badge says {badge!r}, code ships "
+ f"{_quantlib_export_count()} functions across {_quantlib_module_count()} modules"
+ )
+
+
@pytest.mark.parametrize("name", READMES)
def test_the_slash_table_is_the_router(name: str) -> None:
"""The documented TUI commands must be exactly the ones the router resolves.