feat: add Market Breadth family with CrossSection input (#153)

## What

Adds a new indicator input type and family for **market-breadth** analysis — indicators that aggregate the state of an entire universe of symbols at each tick, rather than a single instrument's price. This is the last open input-type on the expansion roadmap (S10) and unblocks the remaining breadth indicators (McClellan, TRIN, High-Low Index, ...).

## Core

- **`CrossSection` input type** (`crates/wickra-core/src/cross_section.rs`) — one tick carrying the per-symbol state of the whole universe as a `Vec<Member>` + `timestamp`. Each `Member` precomputes a signed `change` (sign classifies advancing / declining / unchanged), a `volume`, and `new_high` / `new_low` extreme flags, so the breadth indicators stay stateless per tick. Both `Member` and `CrossSection` are `#[non_exhaustive]` for additive field growth. `CrossSection::new` validates the universe (non-empty, finite changes, finite non-negative volumes); `new_unchecked` skips validation for hot paths. `advancers()` / `decliners()` count by sign.
- **`Error::InvalidCrossSection`** variant for the validation failures.
- **`AdvanceDecline`** (`advance_decline.rs`) — the Advance/Decline Line: the running cumulative sum of net advancing-minus-declining issues. `Input = CrossSection`, `Output = f64`, ready after the first tick.
- New **"Market Breadth"** `FAMILIES` group; indicator count **314 → 315**, family count nineteen → twenty.

## Bindings

All custom (CrossSection is non-scalar, so no macros apply). The universe crosses each boundary as parallel arrays (`change`, `volume`, `new_high`, `new_low`):
- **Python / Node** expose `update` + `batch` (one array group per tick). Node satisfies the completeness contract (`update`/`batch`/`reset`/`isReady`/`warmupPeriod`).
- **WASM** exposes only `update` (the universe is ragged across ticks, matching the other multi-input wasm indicators) with numeric high/low flags.
- Python `map_err` gains the new error arm; `__init__.py` gets a `# Market Breadth` section in both the import and `__all__` blocks. `index.d.ts` / `index.js` regenerated.

## Tests / Fuzz

- Dedicated **streaming-vs-batch + reference-value + ragged-rejection** tests in Python (`test_new_indicators.py`) and Node (`indicators.test.js`) — kept out of the scalar/candle parametrize lists.
- Rust unit tests cover every reject branch (empty / non-finite change / negative & non-finite volume) and every indicator branch.
- New fuzz target `indicator_update_crosssection` drives `AdvanceDecline` over bounded ragged universes built with `new_unchecked`.

## Verify

- `cargo fmt --all` clean
- `cargo test -p wickra-core --lib` → 2593 passed; `--doc` → 298 passed
- `cargo clippy --workspace --all-targets --all-features -- -D warnings` clean
- `cd bindings/node && npm run build && npm test` → 398 passed
- `maturin develop --release` + `pytest bindings/python/tests` → all passed
- counter check: mod-count 315 == lib-block 315
This commit is contained in:
kingchenc
2026-06-03 04:11:10 +02:00
committed by GitHub
parent 72ec65bbde
commit 53941b7b07
18 changed files with 881 additions and 66 deletions
@@ -341,6 +341,8 @@ from ._wickra import (
LiquidationFeatures,
TermStructureBasis,
CalendarSpread,
# Market Breadth
AdvanceDecline,
# Risk / Performance
SharpeRatio,
SortinoRatio,
@@ -679,6 +681,8 @@ __all__ = [
"LiquidationFeatures",
"TermStructureBasis",
"CalendarSpread",
# Market Breadth
"AdvanceDecline",
# Risk / Performance
"SharpeRatio",
"SortinoRatio",
+98 -1
View File
@@ -29,7 +29,8 @@ fn map_err(e: wc::Error) -> PyErr {
| wc::Error::InvalidTick { .. }
| wc::Error::InvalidOrderBook { .. }
| wc::Error::InvalidTrade { .. }
| wc::Error::InvalidDerivatives { .. } => PyValueError::new_err(e.to_string()),
| wc::Error::InvalidDerivatives { .. }
| wc::Error::InvalidCrossSection { .. } => PyValueError::new_err(e.to_string()),
}
}
@@ -14383,6 +14384,101 @@ impl PyCalendarSpread {
}
}
// ============================== Market Breadth ==============================
//
// Market-breadth indicators consume a `CrossSection`: one tick carrying the
// per-symbol state of the whole universe. The Python convention passes a tick as
// four equal-length parallel arrays (`change`, `volume`, `new_high`, `new_low`);
// `batch` takes one such group of arrays per tick.
fn build_cross_section(
change: &[f64],
volume: &[f64],
new_high: &[bool],
new_low: &[bool],
) -> PyResult<wc::CrossSection> {
if change.len() != volume.len()
|| change.len() != new_high.len()
|| change.len() != new_low.len()
{
return Err(PyValueError::new_err(
"change, volume, new_high and new_low must be equal length",
));
}
let members = (0..change.len())
.map(|i| wc::Member::new(change[i], volume[i], new_high[i], new_low[i]))
.collect();
wc::CrossSection::new(members, 0).map_err(map_err)
}
// AdvanceDecline takes no parameters; streaming `update(change, volume, new_high,
// new_low)` over one universe, `batch` over one such array group per tick.
#[pyclass(
name = "AdvanceDecline",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyAdvanceDecline {
inner: wc::AdvanceDecline,
}
#[pymethods]
impl PyAdvanceDecline {
#[new]
fn new() -> Self {
Self {
inner: wc::AdvanceDecline::new(),
}
}
fn update(
&mut self,
change: Vec<f64>,
volume: Vec<f64>,
new_high: Vec<bool>,
new_low: Vec<bool>,
) -> PyResult<Option<f64>> {
Ok(self
.inner
.update(build_cross_section(&change, &volume, &new_high, &new_low)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
change: Vec<Vec<f64>>,
volume: Vec<Vec<f64>>,
new_high: Vec<Vec<bool>>,
new_low: Vec<Vec<bool>>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if change.len() != volume.len()
|| change.len() != new_high.len()
|| change.len() != new_low.len()
{
return Err(PyValueError::new_err(
"change, volume, new_high and new_low must have the same number of ticks",
));
}
let mut out = Vec::with_capacity(change.len());
for i in 0..change.len() {
let section = build_cross_section(&change[i], &volume[i], &new_high[i], &new_low[i])?;
out.push(self.inner.update(section).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 {
"AdvanceDecline()".to_string()
}
}
// ============================== Family 15: Risk / Performance ==============================
#[pyclass(name = "SharpeRatio", module = "wickra._wickra", skip_from_py_object)]
@@ -15776,6 +15872,7 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyLiquidationFeatures>()?;
m.add_class::<PyTermStructureBasis>()?;
m.add_class::<PyCalendarSpread>()?;
m.add_class::<PyAdvanceDecline>()?;
// Family 15: Risk / Performance metrics.
m.add_class::<PySharpeRatio>()?;
m.add_class::<PySortinoRatio>()?;
@@ -2659,6 +2659,38 @@ def test_funding_indicators_streaming_equals_batch():
assert _eq_nan(batch, streamed)
def test_advance_decline_streaming_equals_batch():
# Three ticks over a universe of four symbols; the sign of `change`
# classifies each symbol as advancing / declining / unchanged.
change = [
[1.0, 0.5, 2.0, -1.0], # 3 up, 1 down -> net +2
[-1.0, -0.5, -2.0, 1.0], # 1 up, 3 down -> net -2
[0.0, 0.0, 1.0, -1.0], # 1 up, 1 down -> net 0
]
volume = [[10.0] * 4 for _ in range(3)]
new_high = [[False] * 4 for _ in range(3)]
new_low = [[False] * 4 for _ in range(3)]
batch = ta.AdvanceDecline().batch(change, volume, new_high, new_low)
streamer = ta.AdvanceDecline()
streamed = np.array(
[
streamer.update(change[i], volume[i], new_high[i], new_low[i])
for i in range(3)
],
dtype=np.float64,
)
assert batch.shape == (3,)
assert _eq_nan(batch, streamed)
# Cumulative line: +2 -> 0 -> 0.
assert list(batch) == [2.0, 0.0, 0.0]
def test_advance_decline_rejects_ragged_universe():
ad = ta.AdvanceDecline()
with pytest.raises(ValueError):
ad.update([1.0, -1.0], [10.0], [False, False], [False, False])
def test_funding_basis_streaming_equals_batch():
n = 40
index = np.array([100.0 + 0.5 * math.sin(i * 0.2) for i in range(n)], dtype=np.float64)