Files
wickra/fuzz/fuzz_targets/indicator_update.rs
T
kingchenc 05fcdd9a5e feat(family-12): add 13 Statistik/Regression indicators (#51)
* feat(family-12): add 13 Statistik/Regression indicators

Brings the Price Statistics family to 20 indicators (7 → 20) and the
total catalogue to 84 (71 → 84). Every indicator ships in the Rust
core plus Python, Node, and WASM bindings with full streaming ↔ batch
parity, fuzz coverage, and benches.

Scalar (f64 → f64):
- Variance, CoefficientOfVariation: rolling population variance and
  its dimensionless ratio with the mean. O(1) updates.
- Skewness, Kurtosis: rolling Pearson skewness and excess kurtosis,
  derived from running sums of x, x², x³, x⁴ via the binomial
  identities — also O(1) per bar.
- StandardError, DetrendedStdDev: standard error of estimate (n − 2)
  and population StdDev (n) of OLS residuals, sharing the LinReg
  O(1) sliding sums.
- RSquared: coefficient of determination of the rolling OLS fit; the
  trend-quality filter, clamped to [0, 1].
- MedianAbsoluteDeviation: robust dispersion estimator; O(period log
  period) per emission via two in-place sorts of a reusable scratch
  buffer.
- Autocorrelation(period, lag): rolling lag-k Pearson autocorrelation.
- HurstExponent(period, chunks): R/S-analysis trend-persistence
  estimator clamped to [0, 1].

Pair indicators (Input = (f64, f64)):
- PearsonCorrelation: rolling cross-series Pearson, O(1).
- Beta: rolling OLS slope of asset vs. benchmark (CAPM).
- SpearmanCorrelation: rolling rank correlation with mid-rank tie
  handling; O(period log period).

Touchpoints:
- crates/wickra-core: 13 new indicator modules + mod.rs / lib.rs
  re-exports.
- bindings/python: pyclasses + add_class registration + __init__.py
  import & __all__ updates. The pair indicators expose
  update(x, y) and batch(x, y) over two equally-sized numpy arrays.
- bindings/node: scalar indicators via node_scalar_indicator! macro;
  pair indicators via new node_pair_indicator! macro; explicit
  structs for Autocorrelation and HurstExponent (two-arg ctors).
  index.js extended with the new exports.
- bindings/wasm: scalar wrappers via wasm_scalar_indicator!; pair
  wrappers via new wasm_pair_indicator! macro.
- fuzz: every scalar drove through the generic helper; pair
  indicators stress-tested by pairing adjacent samples of the fuzz
  input.
- Python tests (test_new_indicators.py): added to SCALAR
  parametrisation, plus algebraic reference values
  (variance of [2,4,6] = 8/3, MAD ignoring outlier = 0, monotone
  non-linear Spearman = 1, two-to-one Beta = 2, etc.) and a
  streaming-vs-batch test for the pair indicators.
- Node tests (indicators.test.js): extended the scalar factories
  map and added a pair-indicator section with the same algebraic
  reference values.
- crates/wickra/benches: bench_scalar entries for all 10 single-
  input new indicators.
- README: counter 71 → 84; Price Statistics family-table row
  expanded with the 13 new indicators.
- CHANGELOG: Unreleased section documents the family addition.

Wiki drafts (ghost-ignored, manual sync to wickra.wiki at release
time): indicator-ideas/families/wiki/family-12-statistik-regression/
contains 13 deep-dive pages plus _Sidebar / Indicators-Overview /
Warmup-Periods / Home fragments for the curator merge.

cargo check --workspace --all-features: clean.

* fix(family-12): remove unreachable defensive guards in hurst_exponent

The three guards (m < 2 continue, end > buf.len() break, denom == 0.0
return) are by-construction unreachable given the constructor invariant
period >= 2 * chunks: m = period / k for k in 1..=chunks always
satisfies m >= 2 and end = (c+1) * m <= k * m <= period = buf.len(),
and m_1 = period and m_2 = period / 2 are always distinct so the slope
denominator is strictly positive. Removing them brings codecov/patch
back to 100%.
2026-05-25 23:42:05 +02:00

217 lines
9.2 KiB
Rust

#![no_main]
//! Fuzz scalar-input indicator updates with arbitrary `f64` sequences.
//!
//! Every scalar indicator must tolerate any finite-or-not input stream — NaN,
//! ±inf, subnormals, abrupt jumps — without panicking. Each fuzz iteration
//! runs the **same** input sequence through every scalar indicator twice:
//! once as a streaming `update` loop and once as a full `batch` call. Neither
//! path may panic; `batch` is also expected to agree with the streaming path
//! (the `BatchExt` blanket implementation replays `update` internally, so the
//! agreement is structural — but exercising both paths surfaces any
//! state-mutation bugs in `update` that would only manifest mid-batch).
//!
//! Audit finding R9: the previous version covered only `Rsi(14)` and
//! `Ema(20)`. This target now covers every scalar indicator in the catalogue.
use libfuzzer_sys::fuzz_target;
use wickra_core::{
AdaptiveCycle, Alma, Apo, Autocorrelation, BatchExt, Beta, BollingerBands, CenterOfGravity,
Cfo, Cmo, CoefficientOfVariation, ConnorsRsi, Coppock, CyberneticCycle, Decycler,
DecyclerOscillator, Dema, DetrendedStdDev, DoubleBollinger, Dpo, EhlersStochastic,
ElderImpulse, Ema, EmpiricalModeDecomposition, Fama, FisherTransform, Frama,
HilbertDominantCycle, HistoricalVolatility, Hma, HurstExponent, Indicator,
InstantaneousTrendline, InverseFisherTransform, Jma, Kama, Kst, Kurtosis, LaguerreRsi,
LinRegAngle, LinRegChannel, LinRegSlope, LinearRegression, MaEnvelope, MacdIndicator, Mama,
McGinleyDynamic, MedianAbsoluteDeviation, Mom, PearsonCorrelation, PercentageTrailingStop,
Pmo, Ppo, RSquared, RenkoTrailingStop, Roc, RoofingFilter, Rsi, RviVolatility, SineWave,
Skewness, Sma, Smma, SpearmanCorrelation, StandardError, StandardErrorBands, Stc, StdDev,
StepTrailingStop, StochRsi, SuperSmoother, T3, Tema, Tii, Trima, Trix, Tsi, UlcerIndex,
Variance, VerticalHorizontalFilter, Vidya, Wma, ZScore, ZeroLagMacd, Zlema,
};
/// Drive a single streaming + batch run through one scalar indicator. Marked
/// `#[inline(never)]` so a panic backtrace pin-points the specific indicator.
#[inline(never)]
fn drive<I>(make: impl Fn() -> I, data: &[f64])
where
I: Indicator<Input = f64, Output = f64> + BatchExt,
{
let mut streaming = make();
for &x in data {
let _ = streaming.update(x);
}
let _ = make().batch(data);
}
fuzz_target!(|data: Vec<f64>| {
// Bounded periods keep each iteration cheap and bias the fuzzer toward
// adversarial input patterns rather than enormous windows. The constants
// mirror the README's "common defaults" so we cover the parameterisations
// most users actually instantiate.
drive(|| Sma::new(14).unwrap(), &data);
drive(|| Ema::new(20).unwrap(), &data);
drive(|| Wma::new(14).unwrap(), &data);
drive(|| Rsi::new(14).unwrap(), &data);
drive(|| Dema::new(14).unwrap(), &data);
drive(|| Tema::new(14).unwrap(), &data);
drive(|| Hma::new(14).unwrap(), &data);
drive(|| Roc::new(14).unwrap(), &data);
drive(|| Trix::new(14).unwrap(), &data);
drive(|| Smma::new(14).unwrap(), &data);
drive(|| Trima::new(14).unwrap(), &data);
drive(|| Zlema::new(14).unwrap(), &data);
drive(|| Kama::new(10, 2, 30).unwrap(), &data);
drive(|| Alma::new(9, 0.85, 6.0).unwrap(), &data);
drive(|| McGinleyDynamic::new(10).unwrap(), &data);
drive(|| Frama::new(16).unwrap(), &data);
drive(|| Vidya::new(14, 9).unwrap(), &data);
drive(|| Jma::new(14, 0.0, 2).unwrap(), &data);
drive(|| T3::new(14, 0.7).unwrap(), &data);
drive(|| Mom::new(14).unwrap(), &data);
drive(|| Cmo::new(14).unwrap(), &data);
drive(|| Tsi::new(25, 13).unwrap(), &data);
drive(|| Pmo::new(35, 20).unwrap(), &data);
drive(|| Tii::new(60, 30).unwrap(), &data);
drive(|| StochRsi::new(14, 14).unwrap(), &data);
drive(|| Dpo::new(14).unwrap(), &data);
drive(|| Ppo::new(12, 26).unwrap(), &data);
drive(|| Apo::new(12, 26).unwrap(), &data);
drive(|| Cfo::new(14).unwrap(), &data);
drive(|| ElderImpulse::classic(), &data);
drive(|| Stc::classic(), &data);
drive(|| Coppock::new(14, 11, 10).unwrap(), &data);
drive(|| StdDev::new(14).unwrap(), &data);
drive(|| UlcerIndex::new(14).unwrap(), &data);
drive(|| HistoricalVolatility::new(14, 252).unwrap(), &data);
drive(|| LinearRegression::new(14).unwrap(), &data);
drive(|| LinRegSlope::new(14).unwrap(), &data);
drive(|| LinRegAngle::new(14).unwrap(), &data);
drive(|| VerticalHorizontalFilter::new(14).unwrap(), &data);
drive(|| ZScore::new(14).unwrap(), &data);
drive(|| Variance::new(14).unwrap(), &data);
drive(|| CoefficientOfVariation::new(14).unwrap(), &data);
drive(|| Skewness::new(14).unwrap(), &data);
drive(|| Kurtosis::new(14).unwrap(), &data);
drive(|| StandardError::new(14).unwrap(), &data);
drive(|| DetrendedStdDev::new(14).unwrap(), &data);
drive(|| RSquared::new(14).unwrap(), &data);
drive(|| MedianAbsoluteDeviation::new(14).unwrap(), &data);
drive(|| Autocorrelation::new(14, 2).unwrap(), &data);
// HurstExponent needs `period >= 2 * chunks`; 16/4 is the cheapest fit
// that still exercises every code path.
drive(|| HurstExponent::new(16, 4).unwrap(), &data);
drive(|| RviVolatility::new(10).unwrap(), &data);
drive(|| LaguerreRsi::new(0.5).unwrap(), &data);
drive(|| ConnorsRsi::classic(), &data);
// KST is scalar-input but emits `KstOutput`, so it bypasses the generic
// `drive` helper. Streaming + batch are still both exercised.
{
let mut kst = Kst::classic();
for &x in &data {
let _ = kst.update(x);
}
let _ = Kst::classic().batch(&data);
}
// Zero-Lag MACD shares MACD's multi-output topology, so it gets the
// same hand-rolled streaming + batch drive as classic MACD below.
{
let mut z = ZeroLagMacd::classic();
for &x in &data {
let _ = z.update(x);
}
let _ = ZeroLagMacd::classic().batch(&data);
}
// --- Trailing Stops (scalar) ---
drive(|| PercentageTrailingStop::new(5.0).unwrap(), &data);
drive(|| StepTrailingStop::new(1.0).unwrap(), &data);
drive(|| RenkoTrailingStop::new(1.0).unwrap(), &data);
// Family 10 — Ehlers / Cycle scalar indicators.
drive(|| SuperSmoother::new(10).unwrap(), &data);
drive(|| FisherTransform::new(10).unwrap(), &data);
drive(|| InverseFisherTransform::new(1.0).unwrap(), &data);
drive(|| Decycler::new(20).unwrap(), &data);
drive(|| DecyclerOscillator::new(10, 30).unwrap(), &data);
drive(|| RoofingFilter::new(10, 48).unwrap(), &data);
drive(|| CenterOfGravity::new(10).unwrap(), &data);
drive(|| CyberneticCycle::new(10).unwrap(), &data);
drive(|| InstantaneousTrendline::new(20).unwrap(), &data);
drive(|| EhlersStochastic::new(20).unwrap(), &data);
drive(|| EmpiricalModeDecomposition::new(20, 0.5).unwrap(), &data);
drive(HilbertDominantCycle::new, &data);
drive(AdaptiveCycle::new, &data);
drive(SineWave::new, &data);
drive(|| Fama::new(0.5, 0.05).unwrap(), &data);
// MACD, Bollinger Bands and MAMA have non-`f64` outputs, so they cannot
// use the generic `drive` helper above. Streaming + batch are still both
// exercised.
{
let mut macd = MacdIndicator::new(12, 26, 9).unwrap();
for &x in &data {
let _ = macd.update(x);
}
let _ = MacdIndicator::new(12, 26, 9).unwrap().batch(&data);
}
{
let mut bb = BollingerBands::new(20, 2.0).unwrap();
for &x in &data {
let _ = bb.update(x);
}
let _ = BollingerBands::new(20, 2.0).unwrap().batch(&data);
}
{
let mut mama = Mama::new(0.5, 0.05).unwrap();
for &x in &data {
let _ = mama.update(x);
}
let _ = Mama::new(0.5, 0.05).unwrap().batch(&data);
}
// --- Family 05: scalar-input band/channel indicators (multi-output) ---
{
let mut env = MaEnvelope::new(20, 0.025).unwrap();
for &x in &data {
let _ = env.update(x);
}
let _ = MaEnvelope::new(20, 0.025).unwrap().batch(&data);
}
{
let mut ch = LinRegChannel::new(20, 2.0).unwrap();
for &x in &data {
let _ = ch.update(x);
}
let _ = LinRegChannel::new(20, 2.0).unwrap().batch(&data);
}
{
let mut seb = StandardErrorBands::new(21, 2.0).unwrap();
for &x in &data {
let _ = seb.update(x);
}
let _ = StandardErrorBands::new(21, 2.0).unwrap().batch(&data);
}
{
let mut db = DoubleBollinger::new(20, 1.0, 2.0).unwrap();
for &x in &data {
let _ = db.update(x);
}
let _ = DoubleBollinger::new(20, 1.0, 2.0).unwrap().batch(&data);
}
// Family 12: Two-series indicators — pair adjacent samples of `data`.
{
let mut p = PearsonCorrelation::new(14).unwrap();
let mut b = Beta::new(14).unwrap();
let mut s = SpearmanCorrelation::new(14).unwrap();
for w in data.windows(2) {
let pair = (w[0], w[1]);
let _ = p.update(pair);
let _ = b.update(pair);
let _ = s.update(pair);
}
}
});