F13b: add True Range, Chaikin Volatility, Z-Score and Linear Regression Angle
Second half of the eight indicators that fill out the new family taxonomy. - Rust core: true_range.rs (TrueRange — the raw single-bar volatility ATR averages), chaikin_volatility.rs (ChaikinVolatility — rate of change of a smoothed high-low spread), z_score.rs (ZScore — price normalised against its rolling mean and standard deviation) and linreg_angle.rs (LinRegAngle — the rolling regression slope as a degree angle). Each with a full Indicator impl, runnable doctest and reference / property / warmup / reset / batch==streaming tests. - Python / Node / WASM: classes wired through all three bindings (ZScore and LinRegAngle ride the scalar macros where possible) plus .pyi stubs and __init__.py / __all__ entries. - Wiki: four new Indicator-*.md pages. The eight-family taxonomy restructure (Overview / Home / README / folder layout) lands next in F13c. cargo fmt + clippy (core/wickra/data/wasm/node) clean; 508 core tests, 25 data tests and 74 doctests green.
This commit is contained in:
@@ -0,0 +1,223 @@
|
||||
//! Chaikin Volatility.
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::indicators::ema::Ema;
|
||||
use crate::indicators::roc::Roc;
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Chaikin Volatility — the rate of change of a smoothed high-low spread.
|
||||
///
|
||||
/// ```text
|
||||
/// spread_t = high_t − low_t
|
||||
/// smoothed_t = EMA(spread, ema_period)_t
|
||||
/// ChaikinVol = 100 · (smoothed_t − smoothed_{t−roc_period}) / smoothed_{t−roc_period}
|
||||
/// ```
|
||||
///
|
||||
/// Marc Chaikin's volatility measure tracks not the *level* of the trading
|
||||
/// range but how fast it is *widening or narrowing*. A rising value means
|
||||
/// ranges are expanding (often near a top, as fear spikes); a falling value
|
||||
/// means they are contracting (often a quiet, complacent market). The classic
|
||||
/// configuration smooths the spread with a `10`-period EMA and takes its
|
||||
/// `10`-period rate of change.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Candle, Indicator, ChaikinVolatility};
|
||||
///
|
||||
/// let mut indicator = ChaikinVolatility::new(10, 10).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// let base = 100.0 + f64::from(i);
|
||||
/// let candle =
|
||||
/// Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
|
||||
/// last = indicator.update(candle);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChaikinVolatility {
|
||||
ema: Ema,
|
||||
roc: Roc,
|
||||
ema_period: usize,
|
||||
roc_period: usize,
|
||||
}
|
||||
|
||||
impl ChaikinVolatility {
|
||||
/// Construct a Chaikin Volatility with explicit EMA and rate-of-change
|
||||
/// periods.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`](crate::Error::PeriodZero) if either period
|
||||
/// is zero.
|
||||
pub fn new(ema_period: usize, roc_period: usize) -> Result<Self> {
|
||||
Ok(Self {
|
||||
ema: Ema::new(ema_period)?,
|
||||
roc: Roc::new(roc_period)?,
|
||||
ema_period,
|
||||
roc_period,
|
||||
})
|
||||
}
|
||||
|
||||
/// Marc Chaikin's classic configuration: `EMA(10)` of the spread, `ROC(10)`.
|
||||
pub fn classic() -> Self {
|
||||
Self::new(10, 10).expect("classic Chaikin Volatility params are valid")
|
||||
}
|
||||
|
||||
/// Configured `(ema_period, roc_period)`.
|
||||
pub const fn periods(&self) -> (usize, usize) {
|
||||
(self.ema_period, self.roc_period)
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for ChaikinVolatility {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
let spread = candle.high - candle.low;
|
||||
let smoothed = self.ema.update(spread)?;
|
||||
self.roc.update(smoothed)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.ema.reset();
|
||||
self.roc.reset();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// The EMA emits at candle `ema_period`; the ROC then needs
|
||||
// `roc_period` more smoothed values to span its lookback.
|
||||
self.ema_period + self.roc_period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.roc.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"ChaikinVolatility"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(high: f64, low: f64, close: f64, ts: i64) -> Candle {
|
||||
Candle::new((high + low) / 2.0, high, low, close, 1.0, ts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_range_yields_zero() {
|
||||
// A constant high-low spread smooths to a constant EMA, whose rate of
|
||||
// change is zero.
|
||||
let candles: Vec<Candle> = (0..60)
|
||||
.map(|i| {
|
||||
let base = 100.0 + i as f64;
|
||||
c(base + 1.0, base - 1.0, base, i)
|
||||
})
|
||||
.collect();
|
||||
let mut cv = ChaikinVolatility::new(10, 10).unwrap();
|
||||
for v in cv.batch(&candles).into_iter().flatten() {
|
||||
assert_relative_eq!(v, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_range_reads_positive() {
|
||||
// Each bar's range is strictly wider than the last -> expanding
|
||||
// volatility -> positive Chaikin Volatility.
|
||||
let candles: Vec<Candle> = (0..60)
|
||||
.map(|i| {
|
||||
let half = 1.0 + i as f64 * 0.1;
|
||||
c(100.0 + half, 100.0 - half, 100.0, i)
|
||||
})
|
||||
.collect();
|
||||
let mut cv = ChaikinVolatility::new(10, 10).unwrap();
|
||||
for v in cv.batch(&candles).into_iter().flatten() {
|
||||
assert!(v > 0.0, "an expanding range should read positive, got {v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_independent_ema_and_roc() {
|
||||
let candles: Vec<Candle> = (0..80)
|
||||
.map(|i| {
|
||||
let half = 1.0 + (i as f64 * 0.2).sin().abs() * 2.0;
|
||||
c(100.0 + half, 100.0 - half, 100.0, i)
|
||||
})
|
||||
.collect();
|
||||
let mut cv = ChaikinVolatility::new(10, 10).unwrap();
|
||||
let mut ema = Ema::new(10).unwrap();
|
||||
let mut roc = Roc::new(10).unwrap();
|
||||
for (i, candle) in candles.iter().enumerate() {
|
||||
let got = cv.update(*candle);
|
||||
match ema.update(candle.high - candle.low) {
|
||||
Some(e) => {
|
||||
let want = roc.update(e);
|
||||
assert_eq!(got, want, "i={i}");
|
||||
}
|
||||
None => assert!(got.is_none(), "i={i}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_matches_warmup_period() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.map(|i| {
|
||||
let base = 100.0 + i as f64;
|
||||
c(base + 1.0, base - 1.0, base, i)
|
||||
})
|
||||
.collect();
|
||||
let mut cv = ChaikinVolatility::new(5, 5).unwrap();
|
||||
let out = cv.batch(&candles);
|
||||
assert_eq!(cv.warmup_period(), 10);
|
||||
for (i, v) in out.iter().enumerate().take(9) {
|
||||
assert!(v.is_none(), "index {i} must be None during warmup");
|
||||
}
|
||||
assert!(out[9].is_some(), "first value lands at warmup_period - 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(ChaikinVolatility::new(0, 10).is_err());
|
||||
assert!(ChaikinVolatility::new(10, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.map(|i| {
|
||||
let base = 100.0 + i as f64;
|
||||
c(base + 1.0, base - 1.0, base, i)
|
||||
})
|
||||
.collect();
|
||||
let mut cv = ChaikinVolatility::classic();
|
||||
cv.batch(&candles);
|
||||
assert!(cv.is_ready());
|
||||
cv.reset();
|
||||
assert!(!cv.is_ready());
|
||||
assert_eq!(cv.update(candles[0]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..80)
|
||||
.map(|i| {
|
||||
let half = 1.0 + (i as f64 * 0.25).sin().abs() * 3.0;
|
||||
c(100.0 + half, 100.0 - half, 100.0, i)
|
||||
})
|
||||
.collect();
|
||||
let mut a = ChaikinVolatility::classic();
|
||||
let mut b = ChaikinVolatility::classic();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Linear Regression Angle.
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::indicators::linreg_slope::LinRegSlope;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Linear Regression Angle — the slope of the rolling least-squares fit,
|
||||
/// expressed as an angle in degrees.
|
||||
///
|
||||
/// ```text
|
||||
/// LinRegAngle = atan(LinRegSlope) · 180 / π
|
||||
/// ```
|
||||
///
|
||||
/// It carries exactly the same information as [`LinRegSlope`](crate::LinRegSlope)
|
||||
/// — positive while price trends up, negative while it trends down — but maps
|
||||
/// the unbounded slope through `atan` onto `(−90°, +90°)`. That bounded,
|
||||
/// price-unit-free scale makes "how steep is the trend" comparable at a glance
|
||||
/// and across instruments. This is TA-Lib's `LINEARREG_ANGLE`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, LinRegAngle};
|
||||
///
|
||||
/// let mut indicator = LinRegAngle::new(14).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LinRegAngle {
|
||||
slope: LinRegSlope,
|
||||
}
|
||||
|
||||
impl LinRegAngle {
|
||||
/// Construct a new rolling linear-regression angle over `period` inputs.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`Error::InvalidPeriod`](crate::Error::InvalidPeriod) if
|
||||
/// `period < 2` — a regression line is undefined for fewer than two points.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
Ok(Self {
|
||||
slope: LinRegSlope::new(period)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.slope.period()
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for LinRegAngle {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, value: f64) -> Option<f64> {
|
||||
self.slope.update(value).map(|s| s.atan().to_degrees())
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.slope.reset();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.slope.warmup_period()
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.slope.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"LinRegAngle"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn unit_slope_is_forty_five_degrees() {
|
||||
// A series rising by exactly 1 per step has slope 1, and atan(1) = 45°.
|
||||
let mut angle = LinRegAngle::new(5).unwrap();
|
||||
let out = angle.batch(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
|
||||
for (i, v) in out.iter().enumerate().take(4) {
|
||||
assert!(v.is_none(), "index {i} must be None during warmup");
|
||||
}
|
||||
assert_relative_eq!(out[4].unwrap(), 45.0, epsilon = 1e-9);
|
||||
assert_relative_eq!(out[5].unwrap(), 45.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value_steep_slope() {
|
||||
// period 3 over [1, 2, 9]: slope 4, angle = atan(4) in degrees.
|
||||
let mut angle = LinRegAngle::new(3).unwrap();
|
||||
let out = angle.batch(&[1.0, 2.0, 9.0]);
|
||||
assert_relative_eq!(out[2].unwrap(), 4.0_f64.atan().to_degrees(), epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_has_zero_angle() {
|
||||
let mut angle = LinRegAngle::new(8).unwrap();
|
||||
for v in angle.batch(&[42.0; 20]).into_iter().flatten() {
|
||||
assert_relative_eq!(v, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falling_series_has_negative_angle() {
|
||||
let prices: Vec<f64> = (0..30).map(|i| 100.0 - f64::from(i)).collect();
|
||||
let mut angle = LinRegAngle::new(10).unwrap();
|
||||
for v in angle.batch(&prices).into_iter().flatten() {
|
||||
assert!(v < 0.0, "a falling series must have a negative angle");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stays_within_ninety_degrees() {
|
||||
let prices: Vec<f64> = (0..60)
|
||||
.map(|i| 50.0 + (f64::from(i) * 0.3).sin() * 1000.0)
|
||||
.collect();
|
||||
let mut angle = LinRegAngle::new(14).unwrap();
|
||||
for v in angle.batch(&prices).into_iter().flatten() {
|
||||
assert!(v > -90.0 && v < 90.0, "angle {v} outside (-90, 90)");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_period_below_two() {
|
||||
assert!(LinRegAngle::new(0).is_err());
|
||||
assert!(LinRegAngle::new(1).is_err());
|
||||
assert!(LinRegAngle::new(2).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut angle = LinRegAngle::new(5).unwrap();
|
||||
angle.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
assert!(angle.is_ready());
|
||||
angle.reset();
|
||||
assert!(!angle.is_ready());
|
||||
assert_eq!(angle.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (0..60)
|
||||
.map(|i| 50.0 + (f64::from(i) * 0.3).sin() * 10.0)
|
||||
.collect();
|
||||
let mut a = LinRegAngle::new(14).unwrap();
|
||||
let mut b = LinRegAngle::new(14).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ mod bollinger;
|
||||
mod bollinger_bandwidth;
|
||||
mod cci;
|
||||
mod chaikin_oscillator;
|
||||
mod chaikin_volatility;
|
||||
mod chande_kroll_stop;
|
||||
mod chandelier_exit;
|
||||
mod choppiness_index;
|
||||
@@ -34,6 +35,7 @@ mod hma;
|
||||
mod kama;
|
||||
mod keltner;
|
||||
mod linreg;
|
||||
mod linreg_angle;
|
||||
mod linreg_slope;
|
||||
mod macd;
|
||||
mod mass_index;
|
||||
@@ -58,6 +60,7 @@ mod t3;
|
||||
mod tema;
|
||||
mod trima;
|
||||
mod trix;
|
||||
mod true_range;
|
||||
mod tsi;
|
||||
mod typical_price;
|
||||
mod ulcer_index;
|
||||
@@ -70,6 +73,7 @@ mod vwma;
|
||||
mod weighted_close;
|
||||
mod williams_r;
|
||||
mod wma;
|
||||
mod z_score;
|
||||
mod zlema;
|
||||
|
||||
pub use accelerator_oscillator::AcceleratorOscillator;
|
||||
@@ -85,6 +89,7 @@ pub use bollinger::{BollingerBands, BollingerOutput};
|
||||
pub use bollinger_bandwidth::BollingerBandwidth;
|
||||
pub use cci::Cci;
|
||||
pub use chaikin_oscillator::ChaikinOscillator;
|
||||
pub use chaikin_volatility::ChaikinVolatility;
|
||||
pub use chande_kroll_stop::{ChandeKrollStop, ChandeKrollStopOutput};
|
||||
pub use chandelier_exit::{ChandelierExit, ChandelierExitOutput};
|
||||
pub use choppiness_index::ChoppinessIndex;
|
||||
@@ -102,6 +107,7 @@ pub use hma::Hma;
|
||||
pub use kama::Kama;
|
||||
pub use keltner::{Keltner, KeltnerOutput};
|
||||
pub use linreg::LinearRegression;
|
||||
pub use linreg_angle::LinRegAngle;
|
||||
pub use linreg_slope::LinRegSlope;
|
||||
pub use macd::{MacdIndicator, MacdOutput};
|
||||
pub use mass_index::MassIndex;
|
||||
@@ -126,6 +132,7 @@ pub use t3::T3;
|
||||
pub use tema::Tema;
|
||||
pub use trima::Trima;
|
||||
pub use trix::Trix;
|
||||
pub use true_range::TrueRange;
|
||||
pub use tsi::Tsi;
|
||||
pub use typical_price::TypicalPrice;
|
||||
pub use ulcer_index::UlcerIndex;
|
||||
@@ -138,4 +145,5 @@ pub use vwma::Vwma;
|
||||
pub use weighted_close::WeightedClose;
|
||||
pub use williams_r::WilliamsR;
|
||||
pub use wma::Wma;
|
||||
pub use z_score::ZScore;
|
||||
pub use zlema::Zlema;
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! True Range.
|
||||
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// True Range — the single-bar building block of every ATR-based indicator.
|
||||
///
|
||||
/// ```text
|
||||
/// TR = max( high − low, |high − close_prev|, |low − close_prev| )
|
||||
/// ```
|
||||
///
|
||||
/// True Range is the greatest of the bar's own range and the two gaps to the
|
||||
/// previous close, so it captures volatility that opens *between* bars rather
|
||||
/// than only within them. The first bar has no previous close and falls back
|
||||
/// to `high − low`. Where [`Atr`](crate::Atr) smooths this series, `TrueRange`
|
||||
/// exposes it raw, one value per bar.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Candle, Indicator, TrueRange};
|
||||
///
|
||||
/// let mut indicator = TrueRange::new();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// let base = 100.0 + f64::from(i);
|
||||
/// let candle =
|
||||
/// Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
|
||||
/// last = indicator.update(candle);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TrueRange {
|
||||
prev_close: Option<f64>,
|
||||
has_emitted: bool,
|
||||
}
|
||||
|
||||
impl TrueRange {
|
||||
/// Construct a new True Range indicator.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
prev_close: None,
|
||||
has_emitted: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for TrueRange {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
let tr = candle.true_range(self.prev_close);
|
||||
self.prev_close = Some(candle.close);
|
||||
self.has_emitted = true;
|
||||
Some(tr)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev_close = None;
|
||||
self.has_emitted = false;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.has_emitted
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"TrueRange"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(high: f64, low: f64, close: f64, ts: i64) -> Candle {
|
||||
Candle::new((high + low) / 2.0, high, low, close, 1.0, ts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_values() {
|
||||
// Bar 1 has no previous close -> TR = high - low = 12 - 8 = 4.
|
||||
// Bar 2: prev close 11, TR = max(10-9, |10-11|, |9-11|) = max(1, 1, 2) = 2.
|
||||
let mut tr = TrueRange::new();
|
||||
let out = tr.batch(&[c(12.0, 8.0, 11.0, 0), c(10.0, 9.0, 9.5, 1)]);
|
||||
assert_relative_eq!(out[0].unwrap(), 4.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(out[1].unwrap(), 2.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emits_from_first_candle() {
|
||||
let mut tr = TrueRange::new();
|
||||
assert_eq!(tr.warmup_period(), 1);
|
||||
assert!(!tr.is_ready());
|
||||
assert!(tr.update(c(11.0, 9.0, 10.0, 0)).is_some());
|
||||
assert!(tr.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_negative() {
|
||||
let candles: Vec<Candle> = (0..120)
|
||||
.map(|i| {
|
||||
let base = 100.0 + (i as f64 * 0.3).sin() * 5.0;
|
||||
c(base + 1.0, base - 1.0, base, i)
|
||||
})
|
||||
.collect();
|
||||
let mut tr = TrueRange::new();
|
||||
for v in tr.batch(&candles).into_iter().flatten() {
|
||||
assert!(v >= 0.0, "true range must be non-negative, got {v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut tr = TrueRange::new();
|
||||
tr.batch(&[c(12.0, 8.0, 10.0, 0), c(13.0, 9.0, 11.0, 1)]);
|
||||
assert!(tr.is_ready());
|
||||
tr.reset();
|
||||
assert!(!tr.is_ready());
|
||||
// After reset the next bar again has no previous close.
|
||||
assert_relative_eq!(
|
||||
tr.update(c(12.0, 8.0, 10.0, 0)).unwrap(),
|
||||
4.0,
|
||||
epsilon = 1e-12
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..60)
|
||||
.map(|i| {
|
||||
let mid = 100.0 + (i as f64 * 0.3).sin() * 8.0;
|
||||
c(mid + 1.5, mid - 1.5, mid + 0.5, i)
|
||||
})
|
||||
.collect();
|
||||
let mut a = TrueRange::new();
|
||||
let mut b = TrueRange::new();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//! Z-Score.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Z-Score — how many standard deviations the latest price sits from its
|
||||
/// rolling mean.
|
||||
///
|
||||
/// ```text
|
||||
/// ZScore = (price − SMA(price, n)) / population_stddev(price, n)
|
||||
/// ```
|
||||
///
|
||||
/// A reading of `+2` means price is two standard deviations above its recent
|
||||
/// average — statistically stretched to the upside; `−2` is the mirror. It is
|
||||
/// the standard normalisation behind mean-reversion strategies: a large
|
||||
/// magnitude flags an extension, a return toward `0` flags reversion. A window
|
||||
/// with zero dispersion (a flat series) yields `0`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, ZScore};
|
||||
///
|
||||
/// let mut indicator = ZScore::new(20).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ZScore {
|
||||
period: usize,
|
||||
window: VecDeque<f64>,
|
||||
sum: f64,
|
||||
sum_sq: f64,
|
||||
}
|
||||
|
||||
impl ZScore {
|
||||
/// Construct a new Z-Score over a rolling window of `period` prices.
|
||||
///
|
||||
/// # 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: 0.0,
|
||||
sum_sq: 0.0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for ZScore {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, value: f64) -> Option<f64> {
|
||||
if self.window.len() == self.period {
|
||||
let old = self.window.pop_front().expect("non-empty");
|
||||
self.sum -= old;
|
||||
self.sum_sq -= old * old;
|
||||
}
|
||||
self.window.push_back(value);
|
||||
self.sum += value;
|
||||
self.sum_sq += value * value;
|
||||
if self.window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let n = self.period as f64;
|
||||
let mean = self.sum / n;
|
||||
// Population variance E[x²] − E[x]²; clamp away tiny negative drift.
|
||||
let variance = (self.sum_sq / n - mean * mean).max(0.0);
|
||||
let std = variance.sqrt();
|
||||
if std == 0.0 {
|
||||
// A window with no dispersion: the price is exactly its own mean.
|
||||
return Some(0.0);
|
||||
}
|
||||
Some((value - mean) / std)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.sum = 0.0;
|
||||
self.sum_sq = 0.0;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.window.len() == self.period
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"ZScore"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn reference_values() {
|
||||
// Window [1, 3]: mean 2, population variance (1 + 9)/2 − 4 = 1,
|
||||
// stddev 1; the latest price 3 is (3 − 2) / 1 = 1 stddev above.
|
||||
let mut z = ZScore::new(2).unwrap();
|
||||
let out = z.batch(&[1.0, 3.0]);
|
||||
assert!(out[0].is_none());
|
||||
assert_relative_eq!(out[1].unwrap(), 1.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
let mut z = ZScore::new(10).unwrap();
|
||||
for v in z.batch(&[42.0; 30]).into_iter().flatten() {
|
||||
assert_relative_eq!(v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rising_price_is_above_its_mean() {
|
||||
// A monotonically rising series always sits above its trailing mean.
|
||||
let prices: Vec<f64> = (0..40).map(f64::from).collect();
|
||||
let mut z = ZScore::new(10).unwrap();
|
||||
for v in z.batch(&prices).into_iter().flatten() {
|
||||
assert!(
|
||||
v > 0.0,
|
||||
"a rising price should score above its mean, got {v}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_value_on_period_th_input() {
|
||||
let mut z = ZScore::new(5).unwrap();
|
||||
let out = z.batch(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
|
||||
for (i, v) in out.iter().enumerate().take(4) {
|
||||
assert!(v.is_none(), "index {i} must be None during warmup");
|
||||
}
|
||||
assert!(out[4].is_some(), "first value lands at index period - 1");
|
||||
assert_eq!(z.warmup_period(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(ZScore::new(0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut z = ZScore::new(5).unwrap();
|
||||
z.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
assert!(z.is_ready());
|
||||
z.reset();
|
||||
assert!(!z.is_ready());
|
||||
assert_eq!(z.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (0..60)
|
||||
.map(|i| 50.0 + (f64::from(i) * 0.3).sin() * 10.0)
|
||||
.collect();
|
||||
let mut a = ZScore::new(20).unwrap();
|
||||
let mut b = ZScore::new(20).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user