feat(microstructure): trade-sign autocorrelation, PIN, Hasbrouck information share (B15) (#212)

## B15 Microstructure — three new indicators (485 → 488)

| Indicator | Input | Output | Notes |
|-----------|-------|--------|-------|
| `TradeSignAutocorrelation` | `Trade` | `f64` ∈ [-1,1] | lag-1 autocorrelation of the signed aggressor (order-flow persistence) |
| `Pin` | `Trade` | `f64` ∈ [0,1] | probability of informed trading from rolling buy/sell imbalance (EKOP single-window estimator); `name()` = `"PIN"` |
| `HasbrouckInformationShare` | `(f64, f64)` | `f64` ∈ [0,1] | variance-ratio proxy for each venue's share of price discovery |

### Wiring
- Core structs + full unit tests (every branch).
- Hand-written Python/Node/WASM bindings for the two `Trade`-input indicators (precedent `TradeImbalance`); `node_pair_indicator!` / `wasm_pair_indicator!` macro bindings + hand Python pyclass for the pairwise Hasbrouck (precedent `RollingCorrelation`).
- Fuzz drives added to `indicator_update_trade.rs` and `indicator_update_pair.rs`.
- Dedicated Python + Node streaming-vs-batch and reference tests; Hasbrouck in the `PAIR` registry.
- README counter (3 spots) + `docs/README.md` + `FAMILIES` assert bumped to 488.

### Verify (all green, local)
- `cargo test -p wickra-core --lib`: 3991 passed
- `cargo test -p wickra-core --doc`: 438 passed
- `cargo clippy --workspace --all-targets --all-features -- -D warnings`: clean
- node: 561 passed · pytest: 926 passed
This commit is contained in:
kingchenc
2026-06-08 03:07:50 +02:00
committed by GitHub
parent 3a46b210bb
commit e385734275
18 changed files with 1176 additions and 35 deletions
@@ -464,6 +464,8 @@ from ._wickra import (
QuotedSpread,
DepthSlope,
# Microstructure: trade flow
Pin,
TradeSignAutocorrelation,
RollMeasure,
AmihudIlliquidity,
Vpin,
@@ -471,6 +473,7 @@ from ._wickra import (
CumulativeVolumeDelta,
TradeImbalance,
# Microstructure: price impact
HasbrouckInformationShare,
EffectiveSpread,
RealizedSpread,
KylesLambda,
@@ -979,6 +982,8 @@ __all__ = [
"QuotedSpread",
"DepthSlope",
# Microstructure: trade flow
"Pin",
"TradeSignAutocorrelation",
"RollMeasure",
"AmihudIlliquidity",
"Vpin",
@@ -986,6 +991,7 @@ __all__ = [
"CumulativeVolumeDelta",
"TradeImbalance",
# Microstructure: price impact
"HasbrouckInformationShare",
"EffectiveSpread",
"RealizedSpread",
"KylesLambda",
+173
View File
@@ -16980,6 +16980,70 @@ impl PyRollingCorrelation {
}
}
// ========================= HasbrouckInformationShare =========================
#[pyclass(
name = "HasbrouckInformationShare",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyHasbrouckInformationShare {
inner: wc::HasbrouckInformationShare,
}
#[pymethods]
impl PyHasbrouckInformationShare {
#[new]
#[pyo3(signature = (period=20))]
fn new(period: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::HasbrouckInformationShare::new(period).map_err(map_err)?,
})
}
fn update(&mut self, a: f64, b: f64) -> Option<f64> {
self.inner.update((a, b))
}
/// Batch over two equally-sized numpy arrays: `a` and `b`.
fn batch<'py>(
&mut self,
py: Python<'py>,
a: PyReadonlyArray1<'py, f64>,
b: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let xs = a
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let ys = b
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if xs.len() != ys.len() {
return Err(PyValueError::new_err("a and b must be equal length"));
}
let mut out = Vec::with_capacity(xs.len());
for i in 0..xs.len() {
out.push(self.inner.update((xs[i], ys[i])).unwrap_or(f64::NAN));
}
Ok(out.into_pyarray(py))
}
#[getter]
fn period(&self) -> usize {
self.inner.period()
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!("HasbrouckInformationShare(period={})", self.inner.period())
}
}
// ============================== RollingCovariance ==============================
#[pyclass(
@@ -18652,6 +18716,112 @@ impl PyTradeImbalance {
}
}
// Trade-sign autocorrelation carries a `period` parameter, so it is hand-written.
#[pyclass(
name = "TradeSignAutocorrelation",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyTradeSignAutocorrelation {
inner: wc::TradeSignAutocorrelation,
}
#[pymethods]
impl PyTradeSignAutocorrelation {
#[new]
fn new(period: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::TradeSignAutocorrelation::new(period).map_err(map_err)?,
})
}
fn update(&mut self, price: f64, size: f64, is_buy: bool) -> PyResult<Option<f64>> {
Ok(self.inner.update(build_trade(price, size, is_buy)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
price: Vec<f64>,
size: Vec<f64>,
is_buy: Vec<bool>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if price.len() != size.len() || size.len() != is_buy.len() {
return Err(PyValueError::new_err(
"price, size, is_buy must be equal length",
));
}
let mut out = Vec::with_capacity(price.len());
for i in 0..price.len() {
let trade = build_trade(price[i], size[i], is_buy[i])?;
out.push(self.inner.update(trade).unwrap_or(f64::NAN));
}
Ok(out.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!("TradeSignAutocorrelation(period={})", self.inner.period())
}
}
// PIN carries a `window` parameter, so it is hand-written.
#[pyclass(name = "Pin", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyPin {
inner: wc::Pin,
}
#[pymethods]
impl PyPin {
#[new]
fn new(window: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::Pin::new(window).map_err(map_err)?,
})
}
fn update(&mut self, price: f64, size: f64, is_buy: bool) -> PyResult<Option<f64>> {
Ok(self.inner.update(build_trade(price, size, is_buy)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
price: Vec<f64>,
size: Vec<f64>,
is_buy: Vec<bool>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if price.len() != size.len() || size.len() != is_buy.len() {
return Err(PyValueError::new_err(
"price, size, is_buy must be equal length",
));
}
let mut out = Vec::with_capacity(price.len());
for i in 0..price.len() {
let trade = build_trade(price[i], size[i], is_buy[i])?;
out.push(self.inner.update(trade).unwrap_or(f64::NAN));
}
Ok(out.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!("Pin(window={})", self.inner.window())
}
}
// Order Flow Imbalance carries a `period` parameter and an order-book input,
// so it is hand-written.
#[pyclass(
@@ -24743,6 +24913,7 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyCointegration>()?;
m.add_class::<PyRelativeStrengthAB>()?;
m.add_class::<PyRollingCorrelation>()?;
m.add_class::<PyHasbrouckInformationShare>()?;
m.add_class::<PyRollingCovariance>()?;
m.add_class::<PyOuHalfLife>()?;
m.add_class::<PySpreadHurst>()?;
@@ -24833,6 +25004,8 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PySignedVolume>()?;
m.add_class::<PyCumulativeVolumeDelta>()?;
m.add_class::<PyTradeImbalance>()?;
m.add_class::<PyTradeSignAutocorrelation>()?;
m.add_class::<PyPin>()?;
m.add_class::<PyOrderFlowImbalance>()?;
m.add_class::<PyVpin>()?;
m.add_class::<PyAmihudIlliquidity>()?;
@@ -217,6 +217,7 @@ def test_scalar_streaming_matches_batch(cls, args, sine_prices):
# --- Two-series (asset, benchmark) indicators -----------------------------
PAIR = [
(ta.HasbrouckInformationShare, (2,)),
(ta.KendallTau, (20,)),
(ta.SpreadAr1Coefficient, (40,)),
(ta.GrangerCausality, (60, 1)),
@@ -3323,6 +3324,13 @@ def test_tower_top_bottom_reference():
assert t.update((110.0, 110.1, 99.9, 100.0, 1.0, 2)) == pytest.approx(-1.0)
def test_hasbrouck_information_share_reference():
t = ta.HasbrouckInformationShare(2)
assert t.update(7.0, 9.0) is None
assert t.update(7.0, 9.0) is None
assert t.update(7.0, 9.0) == pytest.approx(0.5)
# --- Lifecycle ------------------------------------------------------------
@@ -3663,6 +3671,8 @@ def test_tradeflow_indicators_streaming_equals_batch():
lambda: ta.Vpin(8.0, 5),
lambda: ta.AmihudIlliquidity(14),
lambda: ta.RollMeasure(14),
lambda: ta.TradeSignAutocorrelation(10),
lambda: ta.Pin(10),
):
batch = make().batch(price, size, is_buy)
streamer = make()
@@ -3674,6 +3684,34 @@ def test_tradeflow_indicators_streaming_equals_batch():
assert _eq_nan(batch, streamed)
def test_trade_sign_autocorrelation_reference():
# Perfectly alternating aggressor signs -> lag-1 autocorrelation -1.
t = ta.TradeSignAutocorrelation(10)
last = None
for i in range(20):
last = t.update(100.0, 1.0, i % 2 == 0)
assert last == pytest.approx(-1.0)
# All buys -> perfectly persistent flow -> +1.
t2 = ta.TradeSignAutocorrelation(10)
for _ in range(20):
last2 = t2.update(100.0, 1.0, True)
assert last2 == pytest.approx(1.0)
def test_pin_reference():
# One-sided flow (all buys) -> maximally informed -> PIN 1.
p = ta.Pin(10)
last = None
for _ in range(20):
last = p.update(100.0, 1.0, True)
assert last == pytest.approx(1.0)
# Balanced flow -> uninformed -> PIN 0.
p2 = ta.Pin(10)
for i in range(20):
last2 = p2.update(100.0, 1.0, i % 2 == 0)
assert last2 == pytest.approx(0.0)
def test_price_impact_indicators_streaming_equals_batch():
n = 40
mid = np.array([100.0 + 0.5 * math.sin(i * 0.4) for i in range(n)], dtype=np.float64)