Files
wickra/crates/wickra-core/src/indicators/vidya.rs
T
kingchencandGitHub 466faddd87 feat: Family 01 Moving Averages — ALMA / McGinley / FRAMA / VIDYA / JMA / Alligator / EVWMA (#39)
* feat(alma): add Arnaud Legoux Moving Average

Gaussian-weighted moving average with configurable centre (offset in
[0, 1]) and kernel width (sigma > 0). Pre-computes normalised weights
at construction so each update is a single rolling window dot product.

Reference: Arnaud Legoux and Dimitrios Kouzis-Loukas, 2009.

Touchpoints:
- crates/wickra-core: alma.rs + mod.rs + lib.rs re-export
- bindings/python: PyAlma + __init__.py + test_new_indicators +
  test_known_values reference
- bindings/node: AlmaNode + index.d.ts/index.js + indicators.test.js
  factory + reference value
- bindings/wasm: wasm_scalar_indicator! macro
- fuzz: indicator_update target covers ALMA(9, 0.85, 6.0)
- crates/wickra/benches: bench_scalar entry
- README + CHANGELOG: Moving Averages row + Unreleased entry

* feat(mcginley): add McGinley Dynamic moving average

John McGinley's self-adjusting moving average with the recurrence
MD + (price - MD) / (0.6 * period * (price / MD)^4). Speeds up when
price falls below the indicator and damps when price runs above the
indicator. Seeded with the simple average of the first period inputs.

Reference: McGinley, Technical Analysis of Stocks & Commodities, 1990.

Touchpoints:
- crates/wickra-core: mcginley_dynamic.rs + mod.rs + lib.rs re-export
- bindings/python: PyMcGinleyDynamic + __init__.py + test_new_indicators
  + test_known_values reference
- bindings/node: McGinleyDynamicNode (scalar macro) + index.d.ts/index.js
  + indicators.test.js factory + reference value
- bindings/wasm: wasm_scalar_indicator! macro
- fuzz: indicator_update target covers McGinleyDynamic(10)
- crates/wickra/benches: bench_scalar entry
- README + CHANGELOG: Moving Averages row + Unreleased entry

* feat(frama): add Fractal Adaptive Moving Average

Ehlers' FRAMA adapts its smoothing constant to the fractal dimension of
the recent window: tight tracking in trends, heavy smoothing in chop.
Uses the close-only variant where max/min over each window half drive
the dimension estimate. Period must be even (default 16).

Reference: Ehlers, Fractal Adaptive Moving Average, 2005.

Touchpoints:
- crates/wickra-core: frama.rs + mod.rs + lib.rs re-export
- bindings/python: PyFrama + __init__.py + test_new_indicators +
  test_known_values reference (constant series + uptrend tracking)
- bindings/node: FramaNode (scalar macro) + index.d.ts/index.js +
  indicators.test.js factory + reference value
- bindings/wasm: wasm_scalar_indicator! macro
- fuzz: indicator_update target covers Frama(16)
- crates/wickra/benches: bench_scalar entry
- README + CHANGELOG: Moving Averages row + Unreleased entry

* feat(vidya): add Variable Index Dynamic Average

Chande's VIDYA — an EMA whose alpha scales with |CMO(cmo_period)| / 100.
Strong directional momentum lifts the smoothing constant toward the
EMA-of-period rate; flat or choppy windows shrink it toward zero so
VIDYA coasts on its previous value. Two parameters: period (14) and
cmo_period (9). Reuses the existing wickra-core Cmo internally.

Reference: Chande, Stocks & Commodities, 1992.

Also fixes a silent gap from d37fbd1 (feat(frama)): the PyFrama Python
class wrapper and its add_class registration were dropped because the
two edits hit "File has not been read yet" errors that scrolled past
in a batch. Adds them here alongside VIDYA's bindings.

Touchpoints (VIDYA): vidya.rs + mod.rs + lib.rs re-export, PyVidya +
__init__.py + test_new_indicators + test_known_values reference,
VidyaNode (manual two-param binding) + index.d.ts/index.js +
indicators.test.js factory + reference, wasm_scalar_indicator! macro,
fuzz target, bench, README + CHANGELOG.

* feat(jma): add Jurik Moving Average

Three-stage filter reconstruction of Mark Jurik's adaptive MA (the
algorithm is proprietary; this is the form used by most open-source
ports since the 1999 TASC article). Parameters: period (14), phase in
[-100, 100] (0), power in 1..=4 (2). State is seeded by setting
e0 = JMA = first input so a constant input stream is reproduced exactly.

Touchpoints: jma.rs + mod.rs + lib.rs re-export, PyJma + __init__.py +
test_new_indicators + test_known_values reference, JmaNode (manual
three-param binding) + index.d.ts/index.js + indicators.test.js factory
+ reference, wasm_scalar_indicator! macro, fuzz target, bench, README +
CHANGELOG.

* feat(alligator): add Bill Williams Alligator

Three SMMA lines (Jaw / Teeth / Lips) over the median price
(high + low) / 2 with default periods 13 / 8 / 5. Multi-output
indicator returning AlligatorOutput { jaw, teeth, lips }. The
original chart variant shifts each line forward for display; we
publish the unshifted SMMA values and leave the visual shift to
the consumer.

Reference: Bill Williams, Trading Chaos, 1995.

Touchpoints: alligator.rs + mod.rs + lib.rs re-export, PyAlligator
(Candle input, returns 3-tuple, ndarray (n, 3) batch) + __init__.py
+ test_new_indicators + test_known_values reference, AlligatorNode +
AlligatorValue + index.d.ts/index.js + indicators.test.js multi
factory + reference, WasmAlligator (manual JsValue object) +
candle-fuzz target + README + CHANGELOG.

* feat(evwma): add Elastic Volume-Weighted Moving Average

Christian P. Fries' elastic recurrence where the smoothing weight is the
bar's volume relative to the running window total:

  V_sum_t = sum of volumes over the last period candles
  EVWMA_t = ((V_sum_t - v_t) * EVWMA_{t-1} + v_t * close_t) / V_sum_t

A bar whose volume is small barely moves the average; a bar that
dominates the window pulls it strongly toward that bar's close. Seeded
with the close of the first full window; holds its previous value if
the entire window has zero volume.

Reference: Fries, Wilmott Magazine, 2001.

Touchpoints: evwma.rs + mod.rs + lib.rs re-export, PyEvwma (close +
volume batch) + __init__.py + test_new_indicators CANDLE_SCALAR +
test_known_values reference, EvwmaNode + index.d.ts/index.js +
indicators.test.js candleScalar factory + reference, WasmEvwma,
candle-fuzz target + README + CHANGELOG.

* ci: Force local wheel install in Python jobs

Use --no-index --no-deps so the Python matrix installs the freshly
built wheel from dist/ and never falls back to PyPI. Previously pip
sometimes picked the released 0.2.x wheel on macOS / Windows when its
platform tag was a wider match than the local build, which made the
job test the released package and miss any new symbols added in the
PR (e.g. AttributeError: module 'wickra' has no attribute 'ALMA').
numpy is already installed by the preceding pip step, so --no-deps
is safe.
2026-05-25 15:01:14 +02:00

194 lines
5.6 KiB
Rust

//! Variable Index Dynamic Average (VIDYA).
use crate::error::{Error, Result};
use crate::indicators::cmo::Cmo;
use crate::traits::Indicator;
/// Tushar Chande's Variable Index Dynamic Average — an EMA whose smoothing
/// factor is scaled by the absolute Chande Momentum Oscillator (`CMO`).
///
/// Strong directional momentum (high `|CMO|`) pushes the effective smoothing
/// constant toward the EMA-of-`period`'s natural rate; flat / choppy windows
/// (`|CMO|` close to zero) shrink it toward zero so VIDYA coasts on its prior
/// value:
///
/// ```text
/// alpha_base = 2 / (period + 1)
/// alpha_t = alpha_base * |CMO(cmo_period)| / 100
/// VIDYA_t = alpha_t * price_t + (1 - alpha_t) * VIDYA_{t-1}
/// ```
///
/// The series is seeded with the first price emitted after the `CMO`
/// warm-up (i.e. after `cmo_period + 1` inputs).
///
/// Reference: Tushar Chande, *Stocks & Commodities*, 1992.
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, Vidya};
///
/// let mut vidya = Vidya::new(14, 9).unwrap();
/// let mut last = None;
/// for i in 0..80 {
/// last = vidya.update(100.0 + f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct Vidya {
period: usize,
cmo_period: usize,
alpha_base: f64,
cmo: Cmo,
current: Option<f64>,
}
impl Vidya {
/// # Errors
/// Returns [`Error::PeriodZero`] if either period is zero.
pub fn new(period: usize, cmo_period: usize) -> Result<Self> {
if period == 0 || cmo_period == 0 {
return Err(Error::PeriodZero);
}
let alpha_base = 2.0 / (period as f64 + 1.0);
Ok(Self {
period,
cmo_period,
alpha_base,
cmo: Cmo::new(cmo_period)?,
current: None,
})
}
/// Configured `(period, cmo_period)`.
pub const fn periods(&self) -> (usize, usize) {
(self.period, self.cmo_period)
}
}
impl Indicator for Vidya {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.current;
}
let cmo = self.cmo.update(input)?;
let alpha = self.alpha_base * (cmo.abs() / 100.0);
let prev = self.current.unwrap_or(input);
let next = alpha * input + (1.0 - alpha) * prev;
self.current = Some(next);
Some(next)
}
fn reset(&mut self) {
self.cmo.reset();
self.current = None;
}
fn warmup_period(&self) -> usize {
self.cmo_period + 1
}
fn is_ready(&self) -> bool {
self.current.is_some()
}
fn name(&self) -> &'static str {
"VIDYA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn rejects_zero_period() {
assert!(matches!(Vidya::new(0, 9), Err(Error::PeriodZero)));
assert!(matches!(Vidya::new(14, 0), Err(Error::PeriodZero)));
}
#[test]
fn accessors_and_metadata() {
let v = Vidya::new(14, 9).unwrap();
assert_eq!(v.periods(), (14, 9));
assert_eq!(v.warmup_period(), 10);
assert_eq!(v.name(), "VIDYA");
}
#[test]
fn constant_series_yields_the_constant() {
// Flat input -> CMO = 0 -> alpha = 0 -> VIDYA holds its seed value.
let mut v = Vidya::new(14, 4).unwrap();
let out = v.batch(&[42.0_f64; 30]);
for x in out.iter().skip(4).flatten() {
assert_relative_eq!(*x, 42.0, epsilon = 1e-12);
}
}
#[test]
fn pure_uptrend_alpha_equals_base() {
// Monotonic uptrend: CMO saturates at +100, so alpha = alpha_base.
// After warmup the recurrence is a plain EMA with that alpha; once
// the series is long enough VIDYA closely tracks the latest input.
let mut v = Vidya::new(2, 4).unwrap();
let prices: Vec<f64> = (1..=40).map(f64::from).collect();
let out = v.batch(&prices);
let last = out.last().unwrap().unwrap();
let latest = *prices.last().unwrap();
// alpha_base = 2/3, EMA(2) tracks close — last value is within 2 of
// the latest input after this many bars.
assert!(
(latest - last).abs() < 2.0,
"VIDYA should track close on a clean uptrend: {last} vs {latest}"
);
}
#[test]
fn warmup_emits_first_value_at_cmo_period_plus_one() {
let mut v = Vidya::new(14, 3).unwrap();
assert_eq!(v.warmup_period(), 4);
assert_eq!(v.update(10.0), None);
assert_eq!(v.update(11.0), None);
assert_eq!(v.update(12.0), None);
assert!(v.update(13.0).is_some());
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=60)
.map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 5.0)
.collect();
let mut a = Vidya::new(14, 9).unwrap();
let mut b = Vidya::new(14, 9).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut v = Vidya::new(14, 9).unwrap();
v.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
assert!(v.is_ready());
v.reset();
assert!(!v.is_ready());
assert_eq!(v.update(1.0), None);
}
#[test]
fn ignores_non_finite_input() {
let mut v = Vidya::new(14, 4).unwrap();
v.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
let before = v.update(21.0).unwrap();
assert_eq!(v.update(f64::NAN), Some(before));
assert_eq!(v.update(f64::INFINITY), Some(before));
}
}