Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(quantlib): add market microstructure analytics (VPIN, Roll spread, Amihud, Kyle)

santhrealad54ab73a12d
diff --git a/README.md b/README.md
index c1a96567d..c3ec3fc3c 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>290 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..4df9e9a98 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>290 دالة مختبَرة عبر 19 وحدة، قابلة للاستدعاء من كل المسارات</sub></summary>
يحتفظ `src/quantlib` بتنفيذ مختبَر **واحد فقط** لكل قطعة من الرياضيات المالية التي
يحتاجها الـ agent. صارت الـ skills **تستورد** هذه الدوال بدلاً من حمل الصيغ داخل كتل
diff --git a/README_es.md b/README_es.md
index ab9c70de6..29920cf17 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>290 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..c2bf0abd7 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 モジュール・290 個のテスト済み関数、すべての経路から呼び出し可能</sub></summary>
`src/quantlib` は、agent が必要とする金融数学のそれぞれについて、テスト済みの実装を
**1 つだけ**保持します。skill はこれらを **import** するようになり、markdown コード
diff --git a/README_ko.md b/README_ko.md
index 092f4db1d..d293acdde 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개 모듈 290개의 테스트된 함수, 모든 경로에서 호출 가능</sub></summary>
`src/quantlib`는 agent가 필요로 하는 각 금융 수학에 대해 테스트된 구현을 **하나씩만**
보유합니다. skill은 이제 이 함수들을 **import**하며, markdown 코드 블록 안에 수식을
diff --git a/README_zh.md b/README_zh.md
index 61a55db26..622f39348 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 个模块 290 个经测试的函数,四条通路皆可调用</sub></summary>
`src/quantlib` 为 agent 需要的每一块金融数学各提供**一份**经测试的实现。skill 现在是
**import** 这些函数,而不再把公式抄在 markdown 代码块里——如果你在某个 `SKILL.md`
diff --git a/agent/src/quantlib/microstructure.py b/agent/src/quantlib/microstructure.py
new file mode 100644
index 000000000..c445d5b17
--- /dev/null
+++ b/agent/src/quantlib/microstructure.py
@@ -0,0 +1,172 @@
+"""Market microstructure signals: VPIN, Roll's effective spread, and Amihud illiquidity.
+
+Implements institutional market microstructure indicators:
+ 1. Volume-Synchronized Probability of Toxicity (VPIN - Easley et al. 2012)
+ 2. Roll's (1984) effective bid-ask spread estimator from serial covariance
+ 3. Amihud's (2002) price impact / illiquidity ratio
+ 4. Kyle's (1985) price impact lambda
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Sequence
+
+import numpy as np
+import pandas as pd
+
+__all__ = [
+ "amihud_illiquidity",
+ "kyles_lambda",
+ "roll_effective_spread",
+ "vpin",
+]
+
+
+def roll_effective_spread(prices: Sequence[float] | np.ndarray | pd.Series) -> float:
+ """Calculate Roll's (1984) effective spread estimator from serial price changes.
+
+ Roll's model: s = 2 * sqrt(-cov(ΔP_t, ΔP_{t-1})) if cov < 0, else 0.0.
+
+ Args:
+ prices: Sequence of transaction or closing prices.
+
+ Returns:
+ Estimated effective dollar spread (non-negative float).
+ """
+ p = np.asarray(prices, dtype=float)
+ if len(p) < 4:
+ raise ValueError("prices sequence must have at least 4 points to compute serial covariance")
+ dp = np.diff(p)
+ dp_t = dp[1:]
+ dp_t_minus_1 = dp[:-1]
+ cov = float(np.cov(dp_t, dp_t_minus_1)[0, 1])
+ if cov < 0.0:
+ return float(2.0 * math.sqrt(-cov))
+ return 0.0
+
+
+def amihud_illiquidity(
+ returns: Sequence[float] | np.ndarray | pd.Series,
+ dollar_volumes: Sequence[float] | np.ndarray | pd.Series,
+) -> float:
+ """Calculate Amihud's (2002) illiquidity ratio: mean(|R_t| / DollarVolume_t).
+
+ Measures the average price response per dollar of trading volume.
+
+ Args:
+ returns: Array of asset returns (decimal).
+ dollar_volumes: Array of traded dollar volumes (> 0).
+
+ Returns:
+ Amihud illiquidity metric (positive float).
+ """
+ r = np.asarray(returns, dtype=float)
+ v = np.asarray(dollar_volumes, dtype=float)
+ if r.shape != v.shape or len(r) == 0:
+ raise ValueError("returns and dollar_volumes must be non-empty and have matching shapes")
+ valid_mask = (v > 0.0) & ~np.isnan(r) & ~np.isnan(v)
+ if not np.any(valid_mask):
+ return float("nan")
+ ratios = np.abs(r[valid_mask]) / v[valid_mask]
+ return float(np.mean(ratios))
+
+
+def kyles_lambda(
+ price_changes: Sequence[float] | np.ndarray | pd.Series,
+ signed_order_flow: Sequence[float] | np.ndarray | pd.Series,
+) -> float:
+ """Estimate Kyle's (1985) price impact coefficient lambda from linear regression.
+
+ ΔP_t = lambda * OrderFlow_t + epsilon_t
+
+ Args:
+ price_changes: Array of price differences ΔP_t.
+ signed_order_flow: Array of signed trade volumes (+ for buy, - for sell).
+
+ Returns:
+ Kyle's lambda price impact slope.
+ """
+ dp = np.asarray(price_changes, dtype=float)
+ flow = np.asarray(signed_order_flow, dtype=float)
+ if dp.shape != flow.shape or len(dp) < 2:
+ raise ValueError("price_changes and signed_order_flow must match with >= 2 observations")
+ denom = float(np.sum(flow**2))
+ if denom == 0.0:
+ return 0.0
+ return float(np.sum(dp * flow) / denom)
+
+
+def vpin(
+ buy_volume: Sequence[float] | np.ndarray,
+ sell_volume: Sequence[float] | np.ndarray,
+ bucket_size: float,
+ n_buckets: int = 50,
+) -> np.ndarray:
+ """Compute Volume-Synchronized Probability of Toxicity (VPIN - Easley et al. 2012).
+
+ VPIN = sum_{i=t-N+1}^t |V_B,i - V_S,i| / (N * V)
+ aggregating trade volume into standardized constant-volume buckets of size V.
+
+ Args:
+ buy_volume: Array of buy trade volumes per time bar.
+ sell_volume: Array of sell trade volumes per time bar.
+ bucket_size: Standardized volume bucket size V (> 0).
+ n_buckets: Number of volume buckets N in rolling window (default=50).
+
+ Returns:
+ 1-D ndarray of VPIN values in [0, 1] for completed volume buckets.
+ """
+ vb = np.asarray(buy_volume, dtype=float)
+ vs = np.asarray(sell_volume, dtype=float)
+ if vb.shape != vs.shape or len(vb) == 0:
+ raise ValueError("buy_volume and sell_volume must have matching non-empty shapes")
+ if bucket_size <= 0.0:
+ raise ValueError(f"bucket_size must be positive, got {bucket_size}")
+ if n_buckets <= 0:
+ raise ValueError(f"n_buckets must be positive, got {n_buckets}")
+
+ # Accumulate trades into constant-volume buckets of size V
+ bucket_imbalances: list[float] = []
+ curr_buy = 0.0
+ curr_sell = 0.0
+
+ for b, s in zip(vb, vs):
+ rem_b = float(b)
+ rem_s = float(s)
+
+ while (rem_b + rem_s) > 0.0:
+ curr_filled = curr_buy + curr_sell
+ space = bucket_size - curr_filled
+ total_bar = rem_b + rem_s
+
+ if total_bar <= space:
+ curr_buy += rem_b
+ curr_sell += rem_s
+ rem_b = 0.0
+ rem_s = 0.0
+ else:
+ # Fill the remaining bucket space proportionally
+ frac_b = rem_b / total_bar
+ frac_s = rem_s / total_bar
+ take_b = space * frac_b
+ take_s = space * frac_s
+
+ curr_buy += take_b
+ curr_sell += take_s
+ rem_b -= take_b
+ rem_s -= take_s
+
+ if (curr_buy + curr_sell) >= bucket_size - 1e-9:
+ bucket_imbalances.append(abs(curr_buy - curr_sell))
+ curr_buy = 0.0
+ curr_sell = 0.0
+
+ if not bucket_imbalances:
+ return np.array([], dtype=float)
+
+ imbalances = pd.Series(bucket_imbalances)
+ rolling_imb = imbalances.rolling(window=n_buckets, min_periods=1).sum()
+ denom = pd.Series(range(1, len(bucket_imbalances) + 1)).clip(upper=n_buckets) * bucket_size
+ vpin_series = rolling_imb / denom
+ return np.clip(vpin_series.to_numpy(), 0.0, 1.0)
diff --git a/agent/src/tools/quantlib_tool.py b/agent/src/tools/quantlib_tool.py
index cdcff3638..3d106a35f 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",
+ "microstructure": "src.quantlib.microstructure",
}
#: Exported names refused because they write to a caller-supplied path. This
diff --git a/agent/tests/quantlib/test_microstructure.py b/agent/tests/quantlib/test_microstructure.py
new file mode 100644
index 000000000..17f57545a
--- /dev/null
+++ b/agent/tests/quantlib/test_microstructure.py
@@ -0,0 +1,59 @@
+"""Tests for microstructure metrics (VPIN, Roll spread, Amihud, Kyle's Lambda)."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+from src.quantlib.microstructure import (
+ amihud_illiquidity,
+ kyles_lambda,
+ roll_effective_spread,
+ vpin,
+)
+
+
+class TestMicrostructureMetrics:
+ """Validate microstructure indicators and edge cases."""
+
+ def test_roll_effective_spread(self) -> None:
+ # Oscillating prices bounce between bid/ask (100.0, 101.0, 100.0, 101.0, ...)
+ # dp = [+1, -1, +1, -1, +1, -1] -> cov(dp_t, dp_{t-1}) < 0
+ prices = [100.0, 101.0, 100.0, 101.0, 100.0, 101.0, 100.0, 101.0]
+ spread = roll_effective_spread(prices)
+ assert spread > 0.0
+ assert spread == pytest.approx(2.0, abs=0.2)
+
+ # Monotonic drift (no negative autocovariance) yields 0.0
+ monotonic = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0]
+ assert roll_effective_spread(monotonic) == 0.0
+
+ def test_amihud_illiquidity(self) -> None:
+ returns = [0.01, -0.02, 0.015]
+ dollar_vol = [1_000_000, 2_000_000, 1_500_000]
+ ratio = amihud_illiquidity(returns, dollar_vol)
+ # mean of [0.01/1M, 0.02/2M, 0.015/1.5M] = [1e-8, 1e-8, 1e-8] -> 1e-8
+ assert ratio == pytest.approx(1e-8)
+
+ def test_kyles_lambda(self) -> None:
+ # Price change = 0.005 * OrderFlow
+ flow = [100.0, -200.0, 300.0, -100.0]
+ dp = [0.5, -1.0, 1.5, -0.5]
+ lam = kyles_lambda(dp, flow)
+ assert lam == pytest.approx(0.005)
+
+ def test_vpin(self) -> None:
+ # Total volume = (100+100) + (200+100) + (300+100) + (100+100) = 1100.
+ # With bucket_size = 200, produces 5 completed buckets.
+ buy_vol = np.array([100.0, 200.0, 300.0, 100.0])
+ sell_vol = np.array([100.0, 100.0, 100.0, 100.0])
+ res = vpin(buy_vol, sell_vol, bucket_size=200.0, n_buckets=3)
+ assert len(res) >= 3
+ assert np.all(res >= 0.0)
+ assert np.all(res <= 1.0)
+
+ def test_validation_errors(self) -> None:
+ with pytest.raises(ValueError, match="at least 4 points"):
+ roll_effective_spread([10.0, 11.0])
+ with pytest.raises(ValueError, match="matching shapes"):
+ amihud_illiquidity([0.01], [100.0, 200.0])