Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): fit Kyle's lambda with an intercept

Lanre Shittuef3139020d0a
diff --git a/agent/src/quantlib/microstructure.py b/agent/src/quantlib/microstructure.py
index c445d5b17..3257e598b 100644
--- a/agent/src/quantlib/microstructure.py
+++ b/agent/src/quantlib/microstructure.py
@@ -78,7 +78,12 @@ def kyles_lambda(
) -> float:
"""Estimate Kyle's (1985) price impact coefficient lambda from linear regression.
- ΔP_t = lambda * OrderFlow_t + epsilon_t
+ ΔP_t = alpha + lambda * OrderFlow_t + epsilon_t
+
+ Fits with an intercept, per the estimation procedure this implements
+ (market-microstructure skill: "Regress ΔP = α + λ × OrderFlow"). Signed
+ order flow is rarely mean-zero over a real window, and forcing the fit
+ through the origin then biases the slope by alpha * mean(flow) / var(flow).
Args:
price_changes: Array of price differences ΔP_t.
@@ -91,10 +96,11 @@ def kyles_lambda(
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))
+ flow_centered = flow - flow.mean()
+ denom = float(np.sum(flow_centered**2))
if denom == 0.0:
return 0.0
- return float(np.sum(dp * flow) / denom)
+ return float(np.sum(flow_centered * (dp - dp.mean())) / denom)
def vpin(
diff --git a/agent/tests/quantlib/test_microstructure.py b/agent/tests/quantlib/test_microstructure.py
index 17f57545a..b134ebce3 100644
--- a/agent/tests/quantlib/test_microstructure.py
+++ b/agent/tests/quantlib/test_microstructure.py
@@ -42,6 +42,16 @@ class TestMicrostructureMetrics:
lam = kyles_lambda(dp, flow)
assert lam == pytest.approx(0.005)
+ def test_kyles_lambda_unbiased_when_flow_mean_is_nonzero(self) -> None:
+ # Order flow with a non-zero mean (net buying pressure), generated by
+ # a known alpha + lambda: a through-origin fit is biased by
+ # alpha * mean(flow) / var(flow) here, so this only passes with an
+ # intercept fitted alongside the slope.
+ flow = [1.0, 2.0, 3.0, 4.0, 5.0]
+ dp = [0.5 * f + 1.0 for f in flow]
+ lam = kyles_lambda(dp, flow)
+ assert lam == pytest.approx(0.5)
+
def test_vpin(self) -> None:
# Total volume = (100+100) + (200+100) + (300+100) + (100+100) = 1100.
# With bucket_size = 200, produces 5 completed buckets.