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.
This commit is contained in:
@@ -0,0 +1,223 @@
|
||||
//! Bill Williams' Alligator indicator.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::indicators::smma::Smma;
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Alligator output: three smoothed moving averages of the median price
|
||||
/// `(high + low) / 2`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AlligatorOutput {
|
||||
/// `Jaw` — the slowest line (default period 13).
|
||||
pub jaw: f64,
|
||||
/// `Teeth` — the middle line (default period 8).
|
||||
pub teeth: f64,
|
||||
/// `Lips` — the fastest line (default period 5).
|
||||
pub lips: f64,
|
||||
}
|
||||
|
||||
/// Bill Williams' Alligator: three `SMMA`s of the median price `(high + low) / 2`
|
||||
/// with different periods. Classic parameters are `(jaw = 13, teeth = 8, lips = 5)`.
|
||||
///
|
||||
/// The original chart variant additionally shifts each line forward by a fixed
|
||||
/// number of bars for display (Jaw +8, Teeth +5, Lips +3). Wickra publishes the
|
||||
/// *unshifted* `SMMA` values — the consumer can apply the visual shift on the
|
||||
/// chart side. The indicator emits values once all three `SMMA`s have warmed
|
||||
/// up, i.e. after `max(jaw, teeth, lips) = jaw` candles.
|
||||
///
|
||||
/// Reference: Bill Williams, *Trading Chaos*, 1995.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Alligator, Candle, Indicator};
|
||||
///
|
||||
/// let mut alligator = Alligator::classic();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..40 {
|
||||
/// let base = 100.0 + f64::from(i);
|
||||
/// let candle =
|
||||
/// Candle::new(base, base + 1.0, base - 1.0, base, 1.0, i64::from(i)).unwrap();
|
||||
/// last = alligator.update(candle);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Alligator {
|
||||
jaw_period: usize,
|
||||
teeth_period: usize,
|
||||
lips_period: usize,
|
||||
jaw: Smma,
|
||||
teeth: Smma,
|
||||
lips: Smma,
|
||||
}
|
||||
|
||||
impl Alligator {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if any period is zero.
|
||||
pub fn new(jaw_period: usize, teeth_period: usize, lips_period: usize) -> Result<Self> {
|
||||
if jaw_period == 0 || teeth_period == 0 || lips_period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
jaw_period,
|
||||
teeth_period,
|
||||
lips_period,
|
||||
jaw: Smma::new(jaw_period)?,
|
||||
teeth: Smma::new(teeth_period)?,
|
||||
lips: Smma::new(lips_period)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Bill Williams' classic parameters: `(jaw = 13, teeth = 8, lips = 5)`.
|
||||
pub fn classic() -> Self {
|
||||
Self::new(13, 8, 5).expect("classic Alligator parameters are valid")
|
||||
}
|
||||
|
||||
/// Configured `(jaw_period, teeth_period, lips_period)`.
|
||||
pub const fn periods(&self) -> (usize, usize, usize) {
|
||||
(self.jaw_period, self.teeth_period, self.lips_period)
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Alligator {
|
||||
type Input = Candle;
|
||||
type Output = AlligatorOutput;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<AlligatorOutput> {
|
||||
let median = f64::midpoint(candle.high, candle.low);
|
||||
// Feed every `SMMA` on every bar so they warm up in parallel; gating
|
||||
// the longer lines behind the shorter ones would starve them during
|
||||
// their own warmup.
|
||||
let lips = self.lips.update(median);
|
||||
let teeth = self.teeth.update(median);
|
||||
let jaw = self.jaw.update(median);
|
||||
Some(AlligatorOutput {
|
||||
jaw: jaw?,
|
||||
teeth: teeth?,
|
||||
lips: lips?,
|
||||
})
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.jaw.reset();
|
||||
self.teeth.reset();
|
||||
self.lips.reset();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// All three SMMAs run on every bar, so readiness is gated by the
|
||||
// longest period — the Jaw with the default parameters.
|
||||
self.jaw_period.max(self.teeth_period).max(self.lips_period)
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.jaw.is_ready() && self.teeth.is_ready() && self.lips.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"Alligator"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn candle(high: f64, low: f64, ts: i64) -> Candle {
|
||||
let close = f64::midpoint(high, low);
|
||||
Candle::new(close, high, low, close, 1.0, ts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(matches!(Alligator::new(0, 8, 5), Err(Error::PeriodZero)));
|
||||
assert!(matches!(Alligator::new(13, 0, 5), Err(Error::PeriodZero)));
|
||||
assert!(matches!(Alligator::new(13, 8, 0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accessors_and_metadata() {
|
||||
let alligator = Alligator::classic();
|
||||
assert_eq!(alligator.periods(), (13, 8, 5));
|
||||
assert_eq!(alligator.warmup_period(), 13);
|
||||
assert_eq!(alligator.name(), "Alligator");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_the_constant() {
|
||||
// Median price = 10 for every bar, so each SMMA seeds to 10 and stays.
|
||||
let mut alligator = Alligator::classic();
|
||||
let candles: Vec<Candle> = (0..40).map(|i| candle(11.0, 9.0, i)).collect();
|
||||
let out = alligator.batch(&candles);
|
||||
for v in out.iter().skip(12).flatten() {
|
||||
assert_relative_eq!(v.jaw, 10.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(v.teeth, 10.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(v.lips, 10.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_emits_first_value_at_longest_period() {
|
||||
let mut alligator = Alligator::new(5, 3, 2).unwrap();
|
||||
let candles: Vec<Candle> = (0..6).map(|i| candle(11.0, 9.0, i)).collect();
|
||||
let out = alligator.batch(&candles);
|
||||
for v in out.iter().take(4) {
|
||||
assert!(v.is_none());
|
||||
}
|
||||
assert!(out[4].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_ordering() {
|
||||
// On a clean uptrend the fastest line (Lips, smallest SMMA) leads the
|
||||
// slowest line (Jaw) — lips > teeth > jaw at the latest bar.
|
||||
let mut alligator = Alligator::classic();
|
||||
let candles: Vec<Candle> = (0_i64..80)
|
||||
.map(|i| candle(10.0 + i as f64, 9.0 + i as f64, i))
|
||||
.collect();
|
||||
let out = alligator.batch(&candles);
|
||||
let last = out.last().unwrap().unwrap();
|
||||
assert!(
|
||||
last.lips > last.teeth,
|
||||
"lips {} > teeth {}",
|
||||
last.lips,
|
||||
last.teeth
|
||||
);
|
||||
assert!(
|
||||
last.teeth > last.jaw,
|
||||
"teeth {} > jaw {}",
|
||||
last.teeth,
|
||||
last.jaw
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..80_i64)
|
||||
.map(|i| {
|
||||
let base = 100.0 + (i as f64 * 0.2).sin() * 5.0;
|
||||
candle(base + 1.0, base - 1.0, i)
|
||||
})
|
||||
.collect();
|
||||
let mut a = Alligator::classic();
|
||||
let mut b = Alligator::classic();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|c| b.update(*c)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut alligator = Alligator::classic();
|
||||
let candles: Vec<Candle> = (0..40).map(|i| candle(11.0, 9.0, i)).collect();
|
||||
alligator.batch(&candles);
|
||||
assert!(alligator.is_ready());
|
||||
alligator.reset();
|
||||
assert!(!alligator.is_ready());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
//! Arnaud Legoux Moving Average (ALMA).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Arnaud Legoux Moving Average — a Gaussian-weighted moving average.
|
||||
///
|
||||
/// Each output is a weighted sum of the last `period` inputs:
|
||||
///
|
||||
/// ```text
|
||||
/// w[i] = exp(-(i - m)^2 / (2 * s^2)) for i in 0..period
|
||||
/// m = offset * (period - 1)
|
||||
/// s = period / sigma
|
||||
/// ALMA = sum(price[i] * w[i]) / sum(w[i])
|
||||
/// ```
|
||||
///
|
||||
/// The Gaussian is centred on the relative index `offset * (period - 1)`, so
|
||||
/// `offset = 0.85` puts the peak near the newest sample (responsive), while
|
||||
/// `offset = 0.5` centres the peak in the middle of the window (smooth).
|
||||
/// `sigma` controls how concentrated the Gaussian is: larger `sigma` ->
|
||||
/// narrower kernel, smaller `sigma` -> broader (closer to SMA).
|
||||
///
|
||||
/// Reference: Arnaud Legoux and Dimitrios Kouzis-Loukas, 2009.
|
||||
///
|
||||
/// # Defaults
|
||||
///
|
||||
/// The community-standard parameters are `period = 9`, `offset = 0.85`,
|
||||
/// `sigma = 6.0`. The first output lands after exactly `period` inputs.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Alma, Indicator};
|
||||
///
|
||||
/// let mut alma = Alma::new(9, 0.85, 6.0).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..40 {
|
||||
/// last = alma.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Alma {
|
||||
period: usize,
|
||||
offset: f64,
|
||||
sigma: f64,
|
||||
/// Pre-computed, normalised weights (sum to 1). `weights[0]` is the oldest
|
||||
/// sample in the window, `weights[period - 1]` the newest.
|
||||
weights: Vec<f64>,
|
||||
window: VecDeque<f64>,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
impl Alma {
|
||||
/// Construct a new ALMA with the given period, offset and sigma.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// - [`Error::PeriodZero`] if `period == 0`.
|
||||
/// - [`Error::InvalidPeriod`] if `offset` is outside `[0.0, 1.0]` or
|
||||
/// `sigma <= 0.0` or either of `offset` / `sigma` is non-finite.
|
||||
pub fn new(period: usize, offset: f64, sigma: f64) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if !offset.is_finite() || !(0.0..=1.0).contains(&offset) {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "ALMA offset must be a finite value in [0, 1]",
|
||||
});
|
||||
}
|
||||
if !sigma.is_finite() || sigma <= 0.0 {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "ALMA sigma must be a finite positive value",
|
||||
});
|
||||
}
|
||||
let m = offset * (period as f64 - 1.0);
|
||||
let s = period as f64 / sigma;
|
||||
let denom = 2.0 * s * s;
|
||||
// The raw Gaussian weights sum to a strictly positive value because
|
||||
// every term is `exp(_) > 0`, so the normalisation below cannot divide
|
||||
// by zero.
|
||||
let mut raw: Vec<f64> = (0..period)
|
||||
.map(|i| (-((i as f64 - m).powi(2)) / denom).exp())
|
||||
.collect();
|
||||
let sum: f64 = raw.iter().sum();
|
||||
for w in &mut raw {
|
||||
*w /= sum;
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
offset,
|
||||
sigma,
|
||||
weights: raw,
|
||||
window: VecDeque::with_capacity(period),
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Construct ALMA with the community-standard parameters
|
||||
/// `(period = 9, offset = 0.85, sigma = 6.0)`.
|
||||
pub fn classic() -> Self {
|
||||
Self::new(9, 0.85, 6.0).expect("classic ALMA parameters are valid")
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Configured offset.
|
||||
pub const fn offset(&self) -> f64 {
|
||||
self.offset
|
||||
}
|
||||
|
||||
/// Configured sigma.
|
||||
pub const fn sigma(&self) -> f64 {
|
||||
self.sigma
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Alma {
|
||||
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 mut acc = 0.0;
|
||||
for (w, p) in self.weights.iter().zip(self.window.iter()) {
|
||||
acc += w * p;
|
||||
}
|
||||
self.current = Some(acc);
|
||||
Some(acc)
|
||||
}
|
||||
|
||||
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 {
|
||||
"ALMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(matches!(Alma::new(0, 0.85, 6.0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_offset() {
|
||||
assert!(matches!(
|
||||
Alma::new(9, -0.1, 6.0),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
Alma::new(9, 1.1, 6.0),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
Alma::new(9, f64::NAN, 6.0),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_sigma() {
|
||||
assert!(matches!(
|
||||
Alma::new(9, 0.85, 0.0),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
Alma::new(9, 0.85, -1.0),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
Alma::new(9, 0.85, f64::INFINITY),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accessors_and_metadata() {
|
||||
let alma = Alma::new(9, 0.85, 6.0).unwrap();
|
||||
assert_eq!(alma.period(), 9);
|
||||
assert_eq!(alma.warmup_period(), 9);
|
||||
assert_eq!(alma.name(), "ALMA");
|
||||
assert!((alma.offset() - 0.85).abs() < 1e-12);
|
||||
assert!((alma.sigma() - 6.0).abs() < 1e-12);
|
||||
// Weights are normalised by construction.
|
||||
let sum: f64 = alma.weights.iter().sum();
|
||||
assert_relative_eq!(sum, 1.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_factory() {
|
||||
let a = Alma::classic();
|
||||
assert_eq!(a.period(), 9);
|
||||
assert!((a.offset() - 0.85).abs() < 1e-12);
|
||||
assert!((a.sigma() - 6.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_the_constant() {
|
||||
// Normalised weights sum to 1, so any constant is reproduced exactly.
|
||||
let mut alma = Alma::new(9, 0.85, 6.0).unwrap();
|
||||
let out = alma.batch(&[42.0_f64; 40]);
|
||||
for v in out.iter().skip(8).flatten() {
|
||||
assert_relative_eq!(*v, 42.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_emits_first_value_at_period() {
|
||||
let mut alma = Alma::new(5, 0.85, 6.0).unwrap();
|
||||
for i in 0..4 {
|
||||
assert_eq!(alma.update(f64::from(i)), None);
|
||||
}
|
||||
assert!(alma.update(4.0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value_period_3() {
|
||||
// ALMA(period=3, offset=0.85, sigma=6) on [10, 20, 30].
|
||||
// m = 0.85 * 2 = 1.7; s = 3 / 6 = 0.5; 2*s^2 = 0.5.
|
||||
// Independently compute the normalised Gaussian weights and the
|
||||
// expected weighted sum, then check the indicator output matches.
|
||||
// Computing the expectation here (rather than pinning a printed
|
||||
// constant) keeps the test stable across libm `exp` implementations.
|
||||
let mut alma = Alma::new(3, 0.85, 6.0).unwrap();
|
||||
alma.update(10.0);
|
||||
alma.update(20.0);
|
||||
let v = alma.update(30.0).expect("ALMA emits after period");
|
||||
|
||||
let w0 = (-((0.0_f64 - 1.7).powi(2)) / 0.5).exp();
|
||||
let w1 = (-((1.0_f64 - 1.7).powi(2)) / 0.5).exp();
|
||||
let w2 = (-((2.0_f64 - 1.7).powi(2)) / 0.5).exp();
|
||||
let s = w0 + w1 + w2;
|
||||
let expected = (10.0 * w0 + 20.0 * w1 + 30.0 * w2) / s;
|
||||
|
||||
// The weighted sum is heavily skewed toward the newest sample so the
|
||||
// output must sit close to but below the latest input (30).
|
||||
assert!(v > 25.0 && v < 30.0, "ALMA(3) on [10,20,30] = {v}");
|
||||
assert_relative_eq!(v, expected, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_zero_centres_on_oldest_sample() {
|
||||
// With offset = 0 the Gaussian peaks at index 0, so ALMA leans toward
|
||||
// the oldest sample in the window and away from the newest.
|
||||
let mut alma = Alma::new(5, 0.0, 6.0).unwrap();
|
||||
let series: Vec<f64> = (1..=5).map(f64::from).collect();
|
||||
let mut last = None;
|
||||
for p in &series {
|
||||
last = alma.update(*p);
|
||||
}
|
||||
let v = last.unwrap();
|
||||
let mean = series.iter().sum::<f64>() / series.len() as f64;
|
||||
// Oldest sample is 1.0, mean is 3.0; an offset-0 ALMA should sit
|
||||
// strictly below the mean.
|
||||
assert!(v < mean, "{v} should be less than {mean}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_one_centres_on_newest_sample() {
|
||||
// Symmetric to the above: offset = 1 leans toward the newest sample.
|
||||
let mut alma = Alma::new(5, 1.0, 6.0).unwrap();
|
||||
let series: Vec<f64> = (1..=5).map(f64::from).collect();
|
||||
let mut last = None;
|
||||
for p in &series {
|
||||
last = alma.update(*p);
|
||||
}
|
||||
let v = last.unwrap();
|
||||
let mean = series.iter().sum::<f64>() / series.len() as f64;
|
||||
assert!(v > mean, "{v} should exceed {mean}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=100)
|
||||
.map(|i| (f64::from(i) * 0.2).sin() * 5.0 + f64::from(i) * 0.1)
|
||||
.collect();
|
||||
let mut a = Alma::new(9, 0.85, 6.0).unwrap();
|
||||
let mut b = Alma::new(9, 0.85, 6.0).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut alma = Alma::new(9, 0.85, 6.0).unwrap();
|
||||
alma.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(alma.is_ready());
|
||||
alma.reset();
|
||||
assert!(!alma.is_ready());
|
||||
assert_eq!(alma.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut alma = Alma::new(5, 0.85, 6.0).unwrap();
|
||||
alma.batch(&(1..=5).map(f64::from).collect::<Vec<_>>());
|
||||
let before = alma.update(6.0).unwrap();
|
||||
// Non-finite inputs leave the window/current untouched.
|
||||
assert_eq!(alma.update(f64::NAN), Some(before));
|
||||
assert_eq!(alma.update(f64::INFINITY), Some(before));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Elastic Volume-Weighted Moving Average (EVWMA).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Christian P. Fries' Elastic Volume-Weighted Moving Average.
|
||||
///
|
||||
/// Unlike `VWMA` which is a per-bar weighted mean, `EVWMA` runs an
|
||||
/// "elastic" recurrence whose smoothing weight is the bar's volume relative
|
||||
/// to the running window-volume:
|
||||
///
|
||||
/// ```text
|
||||
/// V_sum_t = Σ volume_i over the last `period` candles
|
||||
/// EVWMA_t = ((V_sum_t - volume_t) * EVWMA_{t-1} + volume_t * close_t) / V_sum_t
|
||||
/// ```
|
||||
///
|
||||
/// A bar whose volume is small compared to the window total barely moves the
|
||||
/// average; a bar whose volume dominates the window pulls it strongly toward
|
||||
/// the bar's close. The series is seeded with the close of the first candle
|
||||
/// after the volume window has filled (i.e. after `period` candles).
|
||||
///
|
||||
/// If `V_sum_t == 0` (every candle in the window has zero volume), the
|
||||
/// recurrence is undefined; the indicator holds its previous value.
|
||||
///
|
||||
/// Reference: Christian P. Fries, *Wilmott Magazine*, 2001.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Candle, Evwma, Indicator};
|
||||
///
|
||||
/// let mut evwma = Evwma::new(20).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..40 {
|
||||
/// let p = 100.0 + f64::from(i);
|
||||
/// let candle = Candle::new(p, p + 1.0, p - 1.0, p, 10.0, i64::from(i)).unwrap();
|
||||
/// last = evwma.update(candle);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Evwma {
|
||||
period: usize,
|
||||
/// Rolling window of `(close, volume)` pairs, oldest at the front.
|
||||
window: VecDeque<(f64, f64)>,
|
||||
sum_v: f64,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
impl Evwma {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
window: VecDeque::with_capacity(period),
|
||||
sum_v: 0.0,
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Evwma {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
let close = candle.close;
|
||||
let volume = candle.volume;
|
||||
if self.window.len() == self.period {
|
||||
let (_, old_v) = self.window.pop_front().expect("window is non-empty");
|
||||
self.sum_v -= old_v;
|
||||
}
|
||||
self.window.push_back((close, volume));
|
||||
self.sum_v += volume;
|
||||
if self.window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
// The volume sum may be zero (every bar in the window had zero
|
||||
// volume); the recurrence is undefined, so seed/hold instead.
|
||||
if self.sum_v <= 0.0 {
|
||||
if self.current.is_none() {
|
||||
self.current = Some(close);
|
||||
}
|
||||
return self.current;
|
||||
}
|
||||
let prev = self.current.unwrap_or(close);
|
||||
let next = ((self.sum_v - volume) * prev + volume * close) / self.sum_v;
|
||||
self.current = Some(next);
|
||||
Some(next)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.sum_v = 0.0;
|
||||
self.current = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"EVWMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn candle(close: f64, volume: f64, ts: i64) -> Candle {
|
||||
Candle::new(close, close, close, close, volume, ts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(matches!(Evwma::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accessors_and_metadata() {
|
||||
let mut e = Evwma::new(5).unwrap();
|
||||
assert_eq!(e.period(), 5);
|
||||
assert_eq!(e.warmup_period(), 5);
|
||||
assert_eq!(e.name(), "EVWMA");
|
||||
assert_eq!(e.value(), None);
|
||||
for i in 0..5 {
|
||||
e.update(candle(10.0, 1.0, i));
|
||||
}
|
||||
assert!(e.value().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_the_constant() {
|
||||
// A flat close — every (V_sum - v) * prev + v * close reduces to
|
||||
// V_sum * close, so the recurrence preserves the constant after the
|
||||
// first seeded sample.
|
||||
let mut e = Evwma::new(5).unwrap();
|
||||
let candles: Vec<Candle> = (0..30).map(|i| candle(42.0, 3.0, i)).collect();
|
||||
let out = e.batch(&candles);
|
||||
for v in out.iter().skip(4).flatten() {
|
||||
assert_relative_eq!(*v, 42.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value_period_2() {
|
||||
// EVWMA(2). Bars: (close, volume) = (10, 1), (20, 3), (30, 1).
|
||||
// Bar 1: window not full (size 1) -> None.
|
||||
// Bar 2: window full, sum_v = 4, prev seeds to 20.
|
||||
// EVWMA = ((4 - 3) * 20 + 3 * 20) / 4 = 80 / 4 = 20.
|
||||
// Bar 3: window slides, sum_v = 4 (drops the 1, gains the 1).
|
||||
// EVWMA = ((4 - 1) * 20 + 1 * 30) / 4 = (60 + 30) / 4 = 22.5.
|
||||
let mut e = Evwma::new(2).unwrap();
|
||||
assert_eq!(e.update(candle(10.0, 1.0, 0)), None);
|
||||
assert_relative_eq!(
|
||||
e.update(candle(20.0, 3.0, 1)).unwrap(),
|
||||
20.0,
|
||||
epsilon = 1e-12
|
||||
);
|
||||
assert_relative_eq!(
|
||||
e.update(candle(30.0, 1.0, 2)).unwrap(),
|
||||
22.5,
|
||||
epsilon = 1e-12
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_emits_first_value_at_period() {
|
||||
let mut e = Evwma::new(4).unwrap();
|
||||
for i in 0..3 {
|
||||
assert_eq!(e.update(candle(10.0, 1.0, i)), None);
|
||||
}
|
||||
assert!(e.update(candle(10.0, 1.0, 3)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_volume_window_holds_value() {
|
||||
// Every bar has zero volume: no participation, so the recurrence
|
||||
// can't move and EVWMA simply seeds to the first close.
|
||||
let mut e = Evwma::new(3).unwrap();
|
||||
e.update(candle(10.0, 0.0, 0));
|
||||
e.update(candle(15.0, 0.0, 1));
|
||||
let v = e.update(candle(20.0, 0.0, 2)).unwrap();
|
||||
assert_relative_eq!(v, 20.0, epsilon = 1e-12);
|
||||
// Next bar still flat-zero volume: holds 20.
|
||||
let v2 = e.update(candle(50.0, 0.0, 3)).unwrap();
|
||||
assert_relative_eq!(v2, 20.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..60_i64)
|
||||
.map(|i| {
|
||||
let c = 100.0 + (i as f64 * 0.3).sin() * 8.0;
|
||||
candle(c, 1.0 + (i % 7) as f64, i)
|
||||
})
|
||||
.collect();
|
||||
let batch = Evwma::new(10).unwrap().batch(&candles);
|
||||
let mut b = Evwma::new(10).unwrap();
|
||||
let streamed: Vec<_> = candles.iter().map(|c| b.update(*c)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut e = Evwma::new(3).unwrap();
|
||||
let candles: Vec<Candle> = (0..10).map(|i| candle(10.0 + i as f64, 2.0, i)).collect();
|
||||
e.batch(&candles);
|
||||
assert!(e.is_ready());
|
||||
e.reset();
|
||||
assert!(!e.is_ready());
|
||||
assert_eq!(e.update(candle(10.0, 1.0, 0)), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//! 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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! Jurik Moving Average (JMA).
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Mark Jurik's adaptive moving average. The original algorithm is proprietary
|
||||
/// and Jurik Research has never published the full source. This implementation
|
||||
/// follows the widely-used three-stage filter reconstruction circulated since
|
||||
/// the 1999 TASC article on the indicator — the same form used by most
|
||||
/// open-source ports (`TradingView` Pine, `pandas-ta`, various MQL ports):
|
||||
///
|
||||
/// ```text
|
||||
/// beta = 0.45 * (period - 1) / (0.45 * (period - 1) + 2)
|
||||
/// alpha = beta ^ power
|
||||
/// phase_ratio = clamp(phase / 100 + 1.5, 0.5, 2.5)
|
||||
///
|
||||
/// e0_t = (1 - alpha) * x_t + alpha * e0_{t-1}
|
||||
/// e1_t = (x_t - e0_t) * (1 - beta) + beta * e1_{t-1}
|
||||
/// e2_t = (e0_t + phase_ratio * e1_t - JMA_{t-1}) * (1 - alpha)^2 + alpha^2 * e2_{t-1}
|
||||
/// JMA_t = JMA_{t-1} + e2_t
|
||||
/// ```
|
||||
///
|
||||
/// The state is seeded by setting `e0 = JMA = first input`, so a constant
|
||||
/// input stream is reproduced exactly from the first output onward.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// - `period`: smoothing length (default 14).
|
||||
/// - `phase`: phase shift in `[-100, 100]`. Values outside this range are
|
||||
/// clamped to the boundary `phase_ratio` so the constructor never fails on
|
||||
/// a finite `phase`.
|
||||
/// - `power`: kernel exponent in `1..=4` (default 2 matches the popular
|
||||
/// reconstruction).
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, Jma};
|
||||
///
|
||||
/// let mut jma = Jma::new(14, 0.0, 2).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..40 {
|
||||
/// last = jma.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Jma {
|
||||
period: usize,
|
||||
phase: f64,
|
||||
power: u32,
|
||||
beta: f64,
|
||||
alpha: f64,
|
||||
phase_ratio: f64,
|
||||
e0: f64,
|
||||
e1: f64,
|
||||
e2: f64,
|
||||
output: Option<f64>,
|
||||
}
|
||||
|
||||
impl Jma {
|
||||
/// # Errors
|
||||
/// - [`Error::PeriodZero`] if `period == 0`.
|
||||
/// - [`Error::InvalidPeriod`] if `phase` is non-finite or `power` is
|
||||
/// outside `1..=4`.
|
||||
pub fn new(period: usize, phase: f64, power: u32) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if !phase.is_finite() {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "JMA phase must be a finite value",
|
||||
});
|
||||
}
|
||||
if !(1..=4).contains(&power) {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "JMA power must be in 1..=4",
|
||||
});
|
||||
}
|
||||
let len = period as f64 - 1.0;
|
||||
let beta = 0.45 * len / (0.45 * len + 2.0);
|
||||
let alpha = beta.powi(i32::try_from(power).expect("power is in 1..=4"));
|
||||
let phase_ratio = (phase / 100.0 + 1.5).clamp(0.5, 2.5);
|
||||
Ok(Self {
|
||||
period,
|
||||
phase,
|
||||
power,
|
||||
beta,
|
||||
alpha,
|
||||
phase_ratio,
|
||||
e0: 0.0,
|
||||
e1: 0.0,
|
||||
e2: 0.0,
|
||||
output: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Construct JMA with the popular defaults `(period = 14, phase = 0, power = 2)`.
|
||||
pub fn classic() -> Self {
|
||||
Self::new(14, 0.0, 2).expect("classic JMA parameters are valid")
|
||||
}
|
||||
|
||||
/// Configured `(period, phase, power)`.
|
||||
pub const fn params(&self) -> (usize, f64, u32) {
|
||||
(self.period, self.phase, self.power)
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Jma {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
return self.output;
|
||||
}
|
||||
let Some(prev_jma) = self.output else {
|
||||
// Seed e0 and JMA to the first input so a flat series is
|
||||
// reproduced exactly.
|
||||
self.e0 = input;
|
||||
self.output = Some(input);
|
||||
return self.output;
|
||||
};
|
||||
self.e0 = (1.0 - self.alpha) * input + self.alpha * self.e0;
|
||||
self.e1 = (input - self.e0) * (1.0 - self.beta) + self.beta * self.e1;
|
||||
let one_minus_alpha = 1.0 - self.alpha;
|
||||
self.e2 =
|
||||
(self.e0 + self.phase_ratio * self.e1 - prev_jma) * one_minus_alpha * one_minus_alpha
|
||||
+ self.alpha * self.alpha * self.e2;
|
||||
let next = prev_jma + self.e2;
|
||||
self.output = Some(next);
|
||||
Some(next)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.e0 = 0.0;
|
||||
self.e1 = 0.0;
|
||||
self.e2 = 0.0;
|
||||
self.output = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.output.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"JMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(matches!(Jma::new(0, 0.0, 2), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_finite_phase() {
|
||||
assert!(matches!(
|
||||
Jma::new(14, f64::NAN, 2),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
Jma::new(14, f64::INFINITY, 2),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_power() {
|
||||
assert!(matches!(
|
||||
Jma::new(14, 0.0, 0),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
Jma::new(14, 0.0, 5),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accessors_and_metadata() {
|
||||
let jma = Jma::new(14, 0.0, 2).unwrap();
|
||||
assert_eq!(jma.params(), (14, 0.0, 2));
|
||||
assert_eq!(jma.warmup_period(), 1);
|
||||
assert_eq!(jma.name(), "JMA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_factory() {
|
||||
let jma = Jma::classic();
|
||||
assert_eq!(jma.params(), (14, 0.0, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_the_constant() {
|
||||
// Seeding e0 = JMA = first input means the recurrence stays exactly
|
||||
// on the constant from the very first sample.
|
||||
let mut jma = Jma::new(14, 0.0, 2).unwrap();
|
||||
let out = jma.batch(&[42.0_f64; 60]);
|
||||
for x in out.iter().flatten() {
|
||||
assert_relative_eq!(*x, 42.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_phase_is_clamped() {
|
||||
// phase outside [-100, 100] must produce a finite JMA series (phase
|
||||
// ratio clamps to [0.5, 2.5]) rather than blow up the recurrence.
|
||||
let mut a = Jma::new(14, 250.0, 2).unwrap();
|
||||
let mut b = Jma::new(14, -250.0, 2).unwrap();
|
||||
let prices: Vec<f64> = (1..=40).map(f64::from).collect();
|
||||
for &p in &prices {
|
||||
let va = a.update(p).unwrap();
|
||||
let vb = b.update(p).unwrap();
|
||||
assert!(va.is_finite(), "JMA(phase=+250) emitted {va}");
|
||||
assert!(vb.is_finite(), "JMA(phase=-250) emitted {vb}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_tracks_close() {
|
||||
// Monotonic uptrend, period 5, power 2 — after enough samples the
|
||||
// smoothed JMA sits close to the latest input.
|
||||
let mut jma = Jma::new(5, 0.0, 2).unwrap();
|
||||
let prices: Vec<f64> = (1..=80).map(f64::from).collect();
|
||||
let out = jma.batch(&prices);
|
||||
let last = out.last().unwrap().unwrap();
|
||||
let latest = *prices.last().unwrap();
|
||||
assert!(
|
||||
(latest - last).abs() < 5.0,
|
||||
"JMA on a long clean uptrend should track close: {last} vs {latest}"
|
||||
);
|
||||
}
|
||||
|
||||
#[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 = Jma::new(14, 0.0, 2).unwrap();
|
||||
let mut b = Jma::new(14, 0.0, 2).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut jma = Jma::new(14, 0.0, 2).unwrap();
|
||||
jma.batch(&(1..=30).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(jma.is_ready());
|
||||
jma.reset();
|
||||
assert!(!jma.is_ready());
|
||||
assert_eq!(jma.e0, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut jma = Jma::new(14, 0.0, 2).unwrap();
|
||||
jma.batch(&(1..=15).map(f64::from).collect::<Vec<_>>());
|
||||
let before = jma.update(16.0).unwrap();
|
||||
assert_eq!(jma.update(f64::NAN), Some(before));
|
||||
assert_eq!(jma.update(f64::INFINITY), Some(before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn period_one_is_pass_through() {
|
||||
// beta = 0, alpha = 0 -> e2 collapses to (input - prev) and the
|
||||
// recurrence reduces to JMA_t = input.
|
||||
let mut jma = Jma::new(1, 0.0, 2).unwrap();
|
||||
assert_eq!(jma.update(5.0), Some(5.0));
|
||||
assert_relative_eq!(jma.update(10.0).unwrap(), 10.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(jma.update(7.0).unwrap(), 7.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//! `McGinley` Dynamic — self-adjusting moving average.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// John `McGinley`'s "Dynamic" — a self-adjusting moving average that speeds up
|
||||
/// in downtrends and slows down in uptrends to track price more closely than
|
||||
/// a fixed-period MA.
|
||||
///
|
||||
/// The recurrence is
|
||||
///
|
||||
/// ```text
|
||||
/// MD_t = MD_{t-1} + (price_t - MD_{t-1}) / (K * period * (price_t / MD_{t-1})^4)
|
||||
/// ```
|
||||
///
|
||||
/// where `K = 0.6` is `McGinley`'s original constant. The fourth-power ratio
|
||||
/// term shrinks the divisor when price falls below the indicator (faster
|
||||
/// catch-up) and inflates it when price runs above (more smoothing). The
|
||||
/// indicator is seeded with the simple average of the first `period` inputs.
|
||||
///
|
||||
/// Reference: John R. `McGinley` Jr., *Technical Analysis of Stocks &
|
||||
/// Commodities*, 1990.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, McGinleyDynamic};
|
||||
///
|
||||
/// let mut md = McGinleyDynamic::new(10).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..40 {
|
||||
/// last = md.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct McGinleyDynamic {
|
||||
period: usize,
|
||||
seed: VecDeque<f64>,
|
||||
seed_sum: f64,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
/// `McGinley`'s original constant `K` in the recurrence denominator.
|
||||
const K: f64 = 0.6;
|
||||
|
||||
impl McGinleyDynamic {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
seed: VecDeque::with_capacity(period),
|
||||
seed_sum: 0.0,
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for McGinleyDynamic {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
return self.current;
|
||||
}
|
||||
if let Some(prev) = self.current {
|
||||
// The recurrence divides by `(price / prev)^4`; if either side is
|
||||
// zero or negative the formula blows up, so we hold the previous
|
||||
// value as a defensive fallback against degenerate price series.
|
||||
if prev <= 0.0 || input <= 0.0 {
|
||||
return self.current;
|
||||
}
|
||||
let ratio = input / prev;
|
||||
let divisor = K * (self.period as f64) * ratio.powi(4);
|
||||
let next = prev + (input - prev) / divisor;
|
||||
self.current = Some(next);
|
||||
} else {
|
||||
self.seed.push_back(input);
|
||||
self.seed_sum += input;
|
||||
if self.seed.len() == self.period {
|
||||
self.current = Some(self.seed_sum / self.period as f64);
|
||||
}
|
||||
}
|
||||
self.current
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.seed.clear();
|
||||
self.seed_sum = 0.0;
|
||||
self.current = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"McGinleyDynamic"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(matches!(McGinleyDynamic::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accessors_and_metadata() {
|
||||
let mut md = McGinleyDynamic::new(10).unwrap();
|
||||
assert_eq!(md.period(), 10);
|
||||
assert_eq!(md.warmup_period(), 10);
|
||||
assert_eq!(md.name(), "McGinleyDynamic");
|
||||
assert_eq!(md.value(), None);
|
||||
for i in 1..=10 {
|
||||
md.update(f64::from(i));
|
||||
}
|
||||
assert!(md.value().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_the_constant() {
|
||||
// ratio = 1, so the recurrence collapses to MD + 0 / divisor = MD.
|
||||
let mut md = McGinleyDynamic::new(5).unwrap();
|
||||
let out = md.batch(&[42.0_f64; 30]);
|
||||
for v in out.iter().skip(4).flatten() {
|
||||
assert_relative_eq!(*v, 42.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_emits_first_value_at_period() {
|
||||
let mut md = McGinleyDynamic::new(3).unwrap();
|
||||
// Seed = SMA([10, 20, 30]) = 20.0.
|
||||
assert_eq!(md.update(10.0), None);
|
||||
assert_eq!(md.update(20.0), None);
|
||||
assert_eq!(md.update(30.0), Some(20.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value_recurrence() {
|
||||
// Period 3, seed = SMA([10, 20, 30]) = 20.0. Then on price = 40.0:
|
||||
// ratio = 40 / 20 = 2
|
||||
// divisor = 0.6 * 3 * 2^4 = 0.6 * 3 * 16 = 28.8
|
||||
// next = 20 + (40 - 20) / 28.8 = 20.694444...
|
||||
let mut md = McGinleyDynamic::new(3).unwrap();
|
||||
md.batch(&[10.0_f64, 20.0, 30.0]);
|
||||
let v = md.update(40.0).unwrap();
|
||||
let expected = 20.0 + 20.0 / (0.6 * 3.0 * 16.0);
|
||||
assert_relative_eq!(v, expected, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[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 = McGinleyDynamic::new(10).unwrap();
|
||||
let mut b = McGinleyDynamic::new(10).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut md = McGinleyDynamic::new(5).unwrap();
|
||||
md.batch(&(1..=30).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(md.is_ready());
|
||||
md.reset();
|
||||
assert!(!md.is_ready());
|
||||
assert_eq!(md.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut md = McGinleyDynamic::new(3).unwrap();
|
||||
md.batch(&[10.0_f64, 20.0, 30.0]);
|
||||
let before = md.value().unwrap();
|
||||
assert_eq!(md.update(f64::NAN), Some(before));
|
||||
assert_eq!(md.update(f64::INFINITY), Some(before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_value_when_input_is_non_positive() {
|
||||
// Defensive: a zero or negative price would make the (price/prev)^4
|
||||
// divisor zero or otherwise blow up; the recurrence holds steady.
|
||||
let mut md = McGinleyDynamic::new(3).unwrap();
|
||||
md.batch(&[10.0_f64, 20.0, 30.0]);
|
||||
let before = md.value().unwrap();
|
||||
assert_eq!(md.update(0.0), Some(before));
|
||||
assert_eq!(md.update(-5.0), Some(before));
|
||||
// Once a positive price arrives the recurrence resumes normally.
|
||||
let after = md.update(40.0).unwrap();
|
||||
assert!(after > before);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@
|
||||
mod accelerator_oscillator;
|
||||
mod adl;
|
||||
mod adx;
|
||||
mod alligator;
|
||||
mod alma;
|
||||
mod aroon;
|
||||
mod aroon_oscillator;
|
||||
mod atr;
|
||||
@@ -29,9 +31,12 @@ mod donchian;
|
||||
mod dpo;
|
||||
mod ease_of_movement;
|
||||
mod ema;
|
||||
mod evwma;
|
||||
mod force_index;
|
||||
mod frama;
|
||||
mod historical_volatility;
|
||||
mod hma;
|
||||
mod jma;
|
||||
mod kama;
|
||||
mod keltner;
|
||||
mod linreg;
|
||||
@@ -39,6 +44,7 @@ mod linreg_angle;
|
||||
mod linreg_slope;
|
||||
mod macd;
|
||||
mod mass_index;
|
||||
mod mcginley_dynamic;
|
||||
mod median_price;
|
||||
mod mfi;
|
||||
mod mom;
|
||||
@@ -66,6 +72,7 @@ mod typical_price;
|
||||
mod ulcer_index;
|
||||
mod ultimate_oscillator;
|
||||
mod vertical_horizontal_filter;
|
||||
mod vidya;
|
||||
mod vortex;
|
||||
mod vpt;
|
||||
mod vwap;
|
||||
@@ -79,6 +86,8 @@ mod zlema;
|
||||
pub use accelerator_oscillator::AcceleratorOscillator;
|
||||
pub use adl::Adl;
|
||||
pub use adx::{Adx, AdxOutput};
|
||||
pub use alligator::{Alligator, AlligatorOutput};
|
||||
pub use alma::Alma;
|
||||
pub use aroon::{Aroon, AroonOutput};
|
||||
pub use aroon_oscillator::AroonOscillator;
|
||||
pub use atr::Atr;
|
||||
@@ -101,9 +110,12 @@ pub use donchian::{Donchian, DonchianOutput};
|
||||
pub use dpo::Dpo;
|
||||
pub use ease_of_movement::EaseOfMovement;
|
||||
pub use ema::Ema;
|
||||
pub use evwma::Evwma;
|
||||
pub use force_index::ForceIndex;
|
||||
pub use frama::Frama;
|
||||
pub use historical_volatility::HistoricalVolatility;
|
||||
pub use hma::Hma;
|
||||
pub use jma::Jma;
|
||||
pub use kama::Kama;
|
||||
pub use keltner::{Keltner, KeltnerOutput};
|
||||
pub use linreg::LinearRegression;
|
||||
@@ -111,6 +123,7 @@ pub use linreg_angle::LinRegAngle;
|
||||
pub use linreg_slope::LinRegSlope;
|
||||
pub use macd::{MacdIndicator, MacdOutput};
|
||||
pub use mass_index::MassIndex;
|
||||
pub use mcginley_dynamic::McGinleyDynamic;
|
||||
pub use median_price::MedianPrice;
|
||||
pub use mfi::Mfi;
|
||||
pub use mom::Mom;
|
||||
@@ -138,6 +151,7 @@ pub use typical_price::TypicalPrice;
|
||||
pub use ulcer_index::UlcerIndex;
|
||||
pub use ultimate_oscillator::UltimateOscillator;
|
||||
pub use vertical_horizontal_filter::VerticalHorizontalFilter;
|
||||
pub use vidya::Vidya;
|
||||
pub use vortex::{Vortex, VortexOutput};
|
||||
pub use vpt::VolumePriceTrend;
|
||||
pub use vwap::{RollingVwap, Vwap};
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
//! 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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user