Files
wickra/crates/wickra-core/src/indicators/frama.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

260 lines
7.6 KiB
Rust

//! Fractal Adaptive Moving Average (FRAMA).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Ehlers' Fractal Adaptive Moving Average.
///
/// FRAMA picks its smoothing constant from the fractal dimension `D` of the
/// recent window: in a trending (low-`D`) market it follows price tightly, in
/// a choppy (high-`D`) market it smooths heavily. The window of `period`
/// closes is split into two equal halves; the fractal dimension comes from
/// the price ranges of the halves vs. the whole window:
///
/// ```text
/// N1 = (max(first half) - min(first half)) / (period / 2)
/// N2 = (max(second half) - min(second half)) / (period / 2)
/// N3 = (max(window) - min(window)) / period
/// D = (log(N1 + N2) - log(N3)) / log(2)
/// alpha = exp(-4.6 * (D - 1)) clamped to [0.01, 1.0]
/// ```
///
/// The output is an EMA-like recurrence
/// `FRAMA_t = alpha * close_t + (1 - alpha) * FRAMA_{t - 1}`, seeded with the
/// first close. `period` must be even and at least 2.
///
/// Reference: John F. Ehlers, *Fractal Adaptive Moving Average*, 2005.
///
/// # Example
///
/// ```
/// use wickra_core::{Frama, Indicator};
///
/// let mut frama = Frama::new(16).unwrap();
/// let mut last = None;
/// for i in 0..40 {
/// last = frama.update(100.0 + f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct Frama {
period: usize,
half: usize,
window: VecDeque<f64>,
current: Option<f64>,
}
impl Frama {
/// # Errors
/// - [`Error::PeriodZero`] if `period == 0`.
/// - [`Error::InvalidPeriod`] if `period` is odd or below 2.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
if period < 2 {
return Err(Error::InvalidPeriod {
message: "FRAMA period must be at least 2",
});
}
if period % 2 != 0 {
return Err(Error::InvalidPeriod {
message: "FRAMA period must be even",
});
}
Ok(Self {
period,
half: period / 2,
window: VecDeque::with_capacity(period),
current: None,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Frama {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.current;
}
if self.window.len() == self.period {
self.window.pop_front();
}
self.window.push_back(input);
if self.window.len() < self.period {
return None;
}
let half = self.half;
let mut h_first = f64::NEG_INFINITY;
let mut l_first = f64::INFINITY;
let mut h_second = f64::NEG_INFINITY;
let mut l_second = f64::INFINITY;
let mut h_whole = f64::NEG_INFINITY;
let mut l_whole = f64::INFINITY;
for (i, &p) in self.window.iter().enumerate() {
if p > h_whole {
h_whole = p;
}
if p < l_whole {
l_whole = p;
}
if i < half {
if p > h_first {
h_first = p;
}
if p < l_first {
l_first = p;
}
} else {
if p > h_second {
h_second = p;
}
if p < l_second {
l_second = p;
}
}
}
let half_f = half as f64;
let period_f = self.period as f64;
let n1 = (h_first - l_first) / half_f;
let n2 = (h_second - l_second) / half_f;
let n3 = (h_whole - l_whole) / period_f;
let alpha = if n1 > 0.0 && n2 > 0.0 && n3 > 0.0 {
let d = ((n1 + n2).ln() - n3.ln()) / 2.0_f64.ln();
(-4.6 * (d - 1.0)).exp().clamp(0.01, 1.0)
} else {
// Degenerate (perfectly flat half or whole window): use the slowest
// smoothing so the indicator coasts on its previous value.
0.01
};
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.window.clear();
self.current = None;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.current.is_some()
}
fn name(&self) -> &'static str {
"FRAMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn rejects_zero_period() {
assert!(matches!(Frama::new(0), Err(Error::PeriodZero)));
}
#[test]
fn rejects_invalid_period() {
assert!(matches!(Frama::new(1), Err(Error::InvalidPeriod { .. })));
assert!(matches!(Frama::new(3), Err(Error::InvalidPeriod { .. })));
assert!(matches!(Frama::new(15), Err(Error::InvalidPeriod { .. })));
}
#[test]
fn accessors_and_metadata() {
let frama = Frama::new(16).unwrap();
assert_eq!(frama.period(), 16);
assert_eq!(frama.warmup_period(), 16);
assert_eq!(frama.name(), "FRAMA");
}
#[test]
fn constant_series_yields_the_constant() {
// Flat input -> alpha clamps to 0.01 (degenerate ranges) and the
// EMA recurrence holds the seed value forever.
let mut frama = Frama::new(4).unwrap();
let out = frama.batch(&[42.0_f64; 30]);
for v in out.iter().skip(3).flatten() {
assert_relative_eq!(*v, 42.0, epsilon = 1e-12);
}
}
#[test]
fn warmup_emits_first_value_at_period() {
let mut frama = Frama::new(4).unwrap();
assert_eq!(frama.update(1.0), None);
assert_eq!(frama.update(2.0), None);
assert_eq!(frama.update(3.0), None);
assert!(frama.update(4.0).is_some());
}
#[test]
fn pure_uptrend_alpha_close_to_one() {
// A strict monotonic uptrend has fractal dimension ~1, so alpha is
// pushed to 1.0 and FRAMA reduces to the latest price.
let mut frama = Frama::new(4).unwrap();
let prices: Vec<f64> = (1..=8).map(f64::from).collect();
let out = frama.batch(&prices);
let last = out.last().unwrap().unwrap();
assert!(
(last - 8.0).abs() < 0.05,
"FRAMA on a clean uptrend should hug the latest close: {last}"
);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80)
.map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 5.0)
.collect();
let mut a = Frama::new(8).unwrap();
let mut b = Frama::new(8).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut frama = Frama::new(4).unwrap();
frama.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
assert!(frama.is_ready());
frama.reset();
assert!(!frama.is_ready());
assert_eq!(frama.update(1.0), None);
}
#[test]
fn ignores_non_finite_input() {
let mut frama = Frama::new(4).unwrap();
frama.batch(&[1.0, 2.0, 3.0, 4.0]);
let before = frama.update(5.0).unwrap();
assert_eq!(frama.update(f64::NAN), Some(before));
assert_eq!(frama.update(f64::INFINITY), Some(before));
}
}