F2: add ZLEMA, T3 and VWMA advanced moving averages
Completes the F2 family (Advanced MAs) end to end: - Rust core: zlema.rs (Zero-Lag EMA over the de-lagged series 2·price − price[lag]), t3.rs (Tillson's six-EMA cascade with the volume-factor polynomial), vwma.rs (volume-weighted rolling mean with a zero-volume fallback to the unweighted mean). Each with a full Indicator impl, runnable doctest and reference-value / warmup / reset / batch==streaming / non-finite tests. - Python: PyZlema / PyT3 / PyVwma PyO3 classes + module registration + .pyi stubs (T3 defaults v=0.7). - Node: ZlemaNode via the scalar macro, explicit T3Node and VwmaNode classes; index.d.ts and index.js updated. - WASM: WasmZlema / WasmT3 via the scalar macro, explicit WasmVwma. - Wiki: Indicator-Zlema.md, Indicator-T3.md, Indicator-Vwma.md plus rows in Indicators-Overview.md and entries in Home.md. cargo fmt + clippy (core/wickra/data/wasm/node) clean; 232 core tests, 25 data tests and 33 doctests green.
This commit is contained in:
@@ -25,12 +25,15 @@ mod rsi;
|
||||
mod sma;
|
||||
mod smma;
|
||||
mod stochastic;
|
||||
mod t3;
|
||||
mod tema;
|
||||
mod trima;
|
||||
mod trix;
|
||||
mod vwap;
|
||||
mod vwma;
|
||||
mod williams_r;
|
||||
mod wma;
|
||||
mod zlema;
|
||||
|
||||
pub use adx::{Adx, AdxOutput};
|
||||
pub use aroon::{Aroon, AroonOutput};
|
||||
@@ -53,9 +56,12 @@ pub use rsi::Rsi;
|
||||
pub use sma::Sma;
|
||||
pub use smma::Smma;
|
||||
pub use stochastic::{Stochastic, StochasticOutput};
|
||||
pub use t3::T3;
|
||||
pub use tema::Tema;
|
||||
pub use trima::Trima;
|
||||
pub use trix::Trix;
|
||||
pub use vwap::{RollingVwap, Vwap};
|
||||
pub use vwma::Vwma;
|
||||
pub use williams_r::WilliamsR;
|
||||
pub use wma::Wma;
|
||||
pub use zlema::Zlema;
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
//! Tillson T3 Moving Average.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
use super::Ema;
|
||||
|
||||
/// Tillson's T3 — a six-fold cascaded EMA recombined with a *volume factor* `v`.
|
||||
///
|
||||
/// T3 is the generalised DEMA applied three times. Tim Tillson's expansion of
|
||||
/// that triple application over six chained EMAs (`e1 … e6`, each of the same
|
||||
/// `period`) gives the closed form used here:
|
||||
///
|
||||
/// ```text
|
||||
/// c1 = −v³
|
||||
/// c2 = 3v² + 3v³
|
||||
/// c3 = −6v² − 3v − 3v³
|
||||
/// c4 = 1 + 3v + v³ + 3v²
|
||||
/// T3 = c1·e6 + c2·e5 + c3·e4 + c4·e3
|
||||
/// ```
|
||||
///
|
||||
/// The volume factor `v ∈ [0, 1]` controls the lag/smoothness trade-off:
|
||||
/// `v = 0` collapses T3 to the plain triple-cascaded EMA `e3`, while the
|
||||
/// conventional `v = 0.7` adds a hump that sharpens the response to turns.
|
||||
/// The coefficients always sum to `1`, so a constant series maps to itself.
|
||||
///
|
||||
/// The first output lands after `6·period − 5` inputs — the index at which the
|
||||
/// sixth cascaded EMA seeds.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, T3};
|
||||
///
|
||||
/// let mut indicator = T3::new(5, 0.7).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..120 {
|
||||
/// last = indicator.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct T3 {
|
||||
period: usize,
|
||||
v: f64,
|
||||
c1: f64,
|
||||
c2: f64,
|
||||
c3: f64,
|
||||
c4: f64,
|
||||
e1: Ema,
|
||||
e2: Ema,
|
||||
e3: Ema,
|
||||
e4: Ema,
|
||||
e5: Ema,
|
||||
e6: Ema,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
impl T3 {
|
||||
/// Construct a new T3 with the given `period` and volume factor `v`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`, or
|
||||
/// [`Error::InvalidPeriod`] if `v` is non-finite or outside `[0.0, 1.0]`.
|
||||
pub fn new(period: usize, v: f64) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if !v.is_finite() || !(0.0..=1.0).contains(&v) {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "T3 volume factor must be a finite value in [0.0, 1.0]",
|
||||
});
|
||||
}
|
||||
let v2 = v * v;
|
||||
let v3 = v2 * v;
|
||||
Ok(Self {
|
||||
period,
|
||||
v,
|
||||
c1: -v3,
|
||||
c2: 3.0 * v2 + 3.0 * v3,
|
||||
c3: -6.0 * v2 - 3.0 * v - 3.0 * v3,
|
||||
c4: 1.0 + 3.0 * v + v3 + 3.0 * v2,
|
||||
e1: Ema::new(period)?,
|
||||
e2: Ema::new(period)?,
|
||||
e3: Ema::new(period)?,
|
||||
e4: Ema::new(period)?,
|
||||
e5: Ema::new(period)?,
|
||||
e6: Ema::new(period)?,
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Configured volume factor `v`.
|
||||
pub const fn volume_factor(&self) -> f64 {
|
||||
self.v
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for T3 {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
// Non-finite input is ignored; the cascade is not advanced.
|
||||
return self.current;
|
||||
}
|
||||
let e1 = self.e1.update(input)?;
|
||||
let e2 = self.e2.update(e1)?;
|
||||
let e3 = self.e3.update(e2)?;
|
||||
let e4 = self.e4.update(e3)?;
|
||||
let e5 = self.e5.update(e4)?;
|
||||
let e6 = self.e6.update(e5)?;
|
||||
let out = self.c1 * e6 + self.c2 * e5 + self.c3 * e4 + self.c4 * e3;
|
||||
self.current = Some(out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.e1.reset();
|
||||
self.e2.reset();
|
||||
self.e3.reset();
|
||||
self.e4.reset();
|
||||
self.e5.reset();
|
||||
self.e6.reset();
|
||||
self.current = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
6 * self.period - 5
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"T3"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(T3::new(0, 0.7), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_out_of_range_volume_factor() {
|
||||
assert!(matches!(T3::new(5, -0.1), Err(Error::InvalidPeriod { .. })));
|
||||
assert!(matches!(T3::new(5, 1.5), Err(Error::InvalidPeriod { .. })));
|
||||
assert!(matches!(
|
||||
T3::new(5, f64::NAN),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(T3::new(5, 0.0).is_ok());
|
||||
assert!(T3::new(5, 1.0).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coefficients_sum_to_one() {
|
||||
// c1 + c2 + c3 + c4 == 1 for any v, so a constant series is preserved.
|
||||
for &v in &[0.0, 0.3, 0.7, 1.0] {
|
||||
let t3 = T3::new(5, v).unwrap();
|
||||
assert_relative_eq!(t3.c1 + t3.c2 + t3.c3 + t3.c4, 1.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_at_warmup_period() {
|
||||
let mut t3 = T3::new(4, 0.7).unwrap();
|
||||
assert_eq!(t3.warmup_period(), 6 * 4 - 5);
|
||||
let out = t3.batch(&(1..=60).map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().take(t3.warmup_period() - 1) {
|
||||
assert!(v.is_none());
|
||||
}
|
||||
assert!(out[t3.warmup_period() - 1].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_the_constant() {
|
||||
let mut t3 = T3::new(6, 0.7).unwrap();
|
||||
let out = t3.batch(&[50.0; 80]);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert_relative_eq!(*last, 50.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_volume_factor_collapses_to_triple_cascaded_ema() {
|
||||
// With v = 0 the coefficients are c1=c2=c3=0, c4=1, so T3 == e3,
|
||||
// the third stage of the EMA cascade.
|
||||
let prices: Vec<f64> = (1..=80)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 9.0)
|
||||
.collect();
|
||||
let mut t3 = T3::new(5, 0.0).unwrap();
|
||||
let got = t3.batch(&prices);
|
||||
|
||||
let mut e1 = Ema::new(5).unwrap();
|
||||
let mut e2 = Ema::new(5).unwrap();
|
||||
let mut e3 = Ema::new(5).unwrap();
|
||||
let want: Vec<Option<f64>> = prices
|
||||
.iter()
|
||||
.map(|p| {
|
||||
e1.update(*p)
|
||||
.and_then(|a| e2.update(a))
|
||||
.and_then(|b| e3.update(b))
|
||||
})
|
||||
.collect();
|
||||
|
||||
for i in (t3.warmup_period() - 1)..prices.len() {
|
||||
assert_relative_eq!(got[i].unwrap(), want[i].unwrap(), epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut t3 = T3::new(4, 0.7).unwrap();
|
||||
let out = t3.batch(&(1..=60).map(f64::from).collect::<Vec<_>>());
|
||||
let last = *out.last().unwrap();
|
||||
assert!(last.is_some());
|
||||
assert_eq!(t3.update(f64::NAN), last);
|
||||
assert_eq!(t3.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut t3 = T3::new(4, 0.7).unwrap();
|
||||
t3.batch(&(1..=60).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(t3.is_ready());
|
||||
t3.reset();
|
||||
assert!(!t3.is_ready());
|
||||
assert_eq!(t3.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=120)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.25).sin() * 7.0)
|
||||
.collect();
|
||||
let batch = T3::new(7, 0.7).unwrap().batch(&prices);
|
||||
let mut b = T3::new(7, 0.7).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Volume-Weighted Moving Average.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Volume-Weighted Moving Average over a rolling window of `period` candles.
|
||||
///
|
||||
/// Each close is weighted by its own bar volume:
|
||||
///
|
||||
/// ```text
|
||||
/// VWMA_t = Σ(close_i · volume_i) / Σ(volume_i) over the last `period` bars
|
||||
/// ```
|
||||
///
|
||||
/// High-volume bars pull the average toward their close, so VWMA reacts to
|
||||
/// price moves that the market actually participated in and largely ignores
|
||||
/// thin, low-conviction bars.
|
||||
///
|
||||
/// If every candle in the window has zero volume the weighted mean is
|
||||
/// undefined; the indicator then falls back to the **unweighted** mean of the
|
||||
/// `period` closes, so the output is always finite. The first output lands
|
||||
/// after exactly `period` candles.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Candle, Indicator, Vwma};
|
||||
///
|
||||
/// let mut indicator = Vwma::new(5).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 = indicator.update(candle);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Vwma {
|
||||
period: usize,
|
||||
/// Rolling window of `(close, volume)` pairs, oldest at the front.
|
||||
window: VecDeque<(f64, f64)>,
|
||||
sum_pv: f64,
|
||||
sum_v: f64,
|
||||
sum_close: f64,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
impl Vwma {
|
||||
/// Construct a new VWMA with the given period.
|
||||
///
|
||||
/// # 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_pv: 0.0,
|
||||
sum_v: 0.0,
|
||||
sum_close: 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 Vwma {
|
||||
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_close, old_volume) = self.window.pop_front().expect("window is non-empty");
|
||||
self.sum_pv -= old_close * old_volume;
|
||||
self.sum_v -= old_volume;
|
||||
self.sum_close -= old_close;
|
||||
}
|
||||
self.window.push_back((close, volume));
|
||||
self.sum_pv += close * volume;
|
||||
self.sum_v += volume;
|
||||
self.sum_close += close;
|
||||
if self.window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let value = if self.sum_v > 0.0 {
|
||||
self.sum_pv / self.sum_v
|
||||
} else {
|
||||
// Degenerate window: every bar had zero volume. Fall back to the
|
||||
// plain mean of the closes so the output stays finite.
|
||||
self.sum_close / self.period as f64
|
||||
};
|
||||
self.current = Some(value);
|
||||
Some(value)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.sum_pv = 0.0;
|
||||
self.sum_v = 0.0;
|
||||
self.sum_close = 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 {
|
||||
"VWMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
/// Build a flat candle with a given close and volume.
|
||||
fn candle(close: f64, volume: f64, ts: i64) -> Candle {
|
||||
Candle::new(close, close, close, close, volume, ts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Vwma::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value() {
|
||||
// VWMA(2): (10·1 + 20·3) / (1 + 3) = 70 / 4 = 17.5.
|
||||
let mut vwma = Vwma::new(2).unwrap();
|
||||
assert_eq!(vwma.update(candle(10.0, 1.0, 0)), None);
|
||||
assert_relative_eq!(
|
||||
vwma.update(candle(20.0, 3.0, 1)).unwrap(),
|
||||
17.5,
|
||||
epsilon = 1e-12
|
||||
);
|
||||
// Window slides: (20·3 + 30·1) / (3 + 1) = 90 / 4 = 22.5.
|
||||
assert_relative_eq!(
|
||||
vwma.update(candle(30.0, 1.0, 2)).unwrap(),
|
||||
22.5,
|
||||
epsilon = 1e-12
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_volume_window_falls_back_to_unweighted_mean() {
|
||||
let mut vwma = Vwma::new(2).unwrap();
|
||||
assert_eq!(vwma.update(candle(10.0, 0.0, 0)), None);
|
||||
// Both bars have zero volume: fall back to mean(10, 20) = 15.
|
||||
assert_relative_eq!(
|
||||
vwma.update(candle(20.0, 0.0, 1)).unwrap(),
|
||||
15.0,
|
||||
epsilon = 1e-12
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_the_constant() {
|
||||
let mut vwma = Vwma::new(5).unwrap();
|
||||
let candles: Vec<Candle> = (0..30).map(|i| candle(42.0, 3.0, i)).collect();
|
||||
let out = vwma.batch(&candles);
|
||||
for x in out.iter().skip(4).flatten() {
|
||||
assert_relative_eq!(*x, 42.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_volume_bar_pulls_the_average() {
|
||||
// A heavy bar at a higher close drags VWMA above the simple mean.
|
||||
let mut vwma = Vwma::new(3).unwrap();
|
||||
vwma.update(candle(10.0, 1.0, 0));
|
||||
vwma.update(candle(10.0, 1.0, 1));
|
||||
let v = vwma.update(candle(20.0, 100.0, 2)).unwrap();
|
||||
let simple_mean = (10.0 + 10.0 + 20.0) / 3.0;
|
||||
assert!(
|
||||
v > simple_mean,
|
||||
"{v} should exceed simple mean {simple_mean}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_at_warmup_period() {
|
||||
let mut vwma = Vwma::new(4).unwrap();
|
||||
assert_eq!(vwma.warmup_period(), 4);
|
||||
for i in 0..3 {
|
||||
assert_eq!(vwma.update(candle(10.0, 1.0, i)), None);
|
||||
}
|
||||
assert!(vwma.update(candle(10.0, 1.0, 3)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut vwma = Vwma::new(3).unwrap();
|
||||
let candles: Vec<Candle> = (0..10).map(|i| candle(10.0 + i as f64, 2.0, i)).collect();
|
||||
vwma.batch(&candles);
|
||||
assert!(vwma.is_ready());
|
||||
vwma.reset();
|
||||
assert!(!vwma.is_ready());
|
||||
assert_eq!(vwma.update(candle(10.0, 1.0, 0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..50_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 = Vwma::new(8).unwrap().batch(&candles);
|
||||
let mut b = Vwma::new(8).unwrap();
|
||||
let streamed: Vec<_> = candles.iter().map(|c| b.update(*c)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Zero-Lag Exponential Moving Average.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
use super::Ema;
|
||||
|
||||
/// Zero-Lag Exponential Moving Average (Ehlers & Way).
|
||||
///
|
||||
/// A standard EMA applied to a *de-lagged* price series. The de-lagged input
|
||||
/// is `2·price_t − price_{t−lag}` with `lag = (period − 1) / 2`; adding that
|
||||
/// momentum term to the current price cancels most of the EMA's group delay,
|
||||
/// so the average tracks turns far more tightly than a plain [`Ema`].
|
||||
///
|
||||
/// The first output lands after exactly `lag + period` inputs: `lag` inputs
|
||||
/// are needed before the de-lagged series is defined, then `period` de-lagged
|
||||
/// values seed the inner EMA.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, Zlema};
|
||||
///
|
||||
/// let mut indicator = Zlema::new(10).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Zlema {
|
||||
period: usize,
|
||||
lag: usize,
|
||||
/// Rolling buffer of the last `lag + 1` raw inputs, oldest at the front.
|
||||
window: VecDeque<f64>,
|
||||
ema: Ema,
|
||||
}
|
||||
|
||||
impl Zlema {
|
||||
/// Construct a new ZLEMA with the given period.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
let lag = (period - 1) / 2;
|
||||
Ok(Self {
|
||||
period,
|
||||
lag,
|
||||
window: VecDeque::with_capacity(lag + 1),
|
||||
ema: Ema::new(period)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Lag offset `(period − 1) / 2` used to de-lag the price series.
|
||||
pub const fn lag(&self) -> usize {
|
||||
self.lag
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.ema.value()
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Zlema {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
// Non-finite input is ignored; state is left untouched.
|
||||
return self.ema.value();
|
||||
}
|
||||
if self.window.len() == self.lag + 1 {
|
||||
self.window.pop_front();
|
||||
}
|
||||
self.window.push_back(input);
|
||||
if self.window.len() < self.lag + 1 {
|
||||
return None;
|
||||
}
|
||||
let lagged = *self.window.front().expect("window is non-empty");
|
||||
let de_lagged = 2.0f64.mul_add(input, -lagged);
|
||||
self.ema.update(de_lagged)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.ema.reset();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.lag + self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.ema.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"ZLEMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Zlema::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lag_is_half_of_period_minus_one() {
|
||||
assert_eq!(Zlema::new(3).unwrap().lag(), 1);
|
||||
assert_eq!(Zlema::new(10).unwrap().lag(), 4);
|
||||
assert_eq!(Zlema::new(1).unwrap().lag(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_values() {
|
||||
// ZLEMA(3): lag = 1, de_lagged_t = 2·xt − x_{t-1}, then EMA(3).
|
||||
// [1,2,3,4,5] -> de-lagged [_, 3, 4, 5, 6]; EMA(3) seeds at the third
|
||||
// de-lagged value: mean(3,4,5) = 4.0; next = 0.5·6 + 0.5·4 = 5.0.
|
||||
let mut zlema = Zlema::new(3).unwrap();
|
||||
let out = zlema.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
assert_eq!(zlema.warmup_period(), 4);
|
||||
assert_eq!(out[0], None);
|
||||
assert_eq!(out[1], None);
|
||||
assert_eq!(out[2], None);
|
||||
assert_relative_eq!(out[3].unwrap(), 4.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(out[4].unwrap(), 5.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_the_constant() {
|
||||
// De-lagging a constant gives the same constant (2c − c = c).
|
||||
let mut zlema = Zlema::new(7).unwrap();
|
||||
let out = zlema.batch(&[33.0; 60]);
|
||||
for x in out.iter().skip(zlema.warmup_period() - 1).flatten() {
|
||||
assert_relative_eq!(*x, 33.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut zlema = Zlema::new(3).unwrap();
|
||||
let out = zlema.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
let last = out[4];
|
||||
assert!(last.is_some());
|
||||
assert_eq!(zlema.update(f64::NAN), last);
|
||||
assert_eq!(zlema.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut zlema = Zlema::new(5).unwrap();
|
||||
zlema.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(zlema.is_ready());
|
||||
zlema.reset();
|
||||
assert!(!zlema.is_ready());
|
||||
assert_eq!(zlema.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=60)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 8.0)
|
||||
.collect();
|
||||
let batch = Zlema::new(9).unwrap().batch(&prices);
|
||||
let mut b = Zlema::new(9).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ pub use indicators::{
|
||||
Adx, AdxOutput, Aroon, AroonOutput, Atr, AwesomeOscillator, BollingerBands, BollingerOutput,
|
||||
Cci, Dema, Donchian, DonchianOutput, Ema, Hma, Kama, Keltner, KeltnerOutput, MacdIndicator,
|
||||
MacdOutput, Mfi, Obv, Psar, Roc, RollingVwap, Rsi, Sma, Smma, Stochastic, StochasticOutput,
|
||||
Tema, Trima, Trix, Vwap, WilliamsR, Wma,
|
||||
Tema, Trima, Trix, Vwap, Vwma, WilliamsR, Wma, Zlema, T3,
|
||||
};
|
||||
pub use ohlcv::{Candle, Tick};
|
||||
pub use traits::{BatchExt, Chain, Indicator};
|
||||
|
||||
Reference in New Issue
Block a user