Wickra 0.1.0: streaming-first technical indicators
A multi-language technical analysis library: 25 indicators across trend,
momentum, volatility, and volume families, every one a state machine with
O(1) per-tick updates. Batch evaluation is provided by a blanket extension
trait over the streaming primitive, so live trading bots and historical
backtests run the same code path.
What ships in this initial drop:
crates/wickra-core - 25 indicators, Indicator/BatchExt/Chain traits,
OHLCV types with validation; 171 unit tests,
property tests, Wilder/Bollinger textbook tests.
crates/wickra - top-level facade + criterion benches for every
indicator at 1K/10K/100K series sizes.
crates/wickra-data - streaming CSV reader, tick-to-candle aggregator,
multi-timeframe resampler, Binance Spot kline
WebSocket adapter behind feature live-binance;
11 unit + 1 doctest.
bindings/python - PyO3 + maturin, NumPy I/O, type stubs (.pyi),
56 pytest tests including streaming==batch
equivalence, Wilder reference values, lifecycle.
bindings/node - napi-rs native module, TypeScript .d.ts
auto-generated, 7 node --test cases.
bindings/wasm - wasm-bindgen ES module for browser/bundler/Node;
interactive HTML demo at examples/index.html.
examples/ - Python and Rust scripts: backtest, live trading,
parallel multi-asset, multi-timeframe, Binance.
benchmarks/ - cross-library comparison against TA-Lib,
pandas-ta, finta, talipp; Wickra wins every
category by 11-1030x (batch) and 17x+ streaming.
.github/workflows/ - CI matrix (Rust + Python + Node + WASM on
Linux/macOS/Windows), release pipeline for
PyPI wheels and npm.
Indicators (25):
Trend SMA EMA WMA DEMA TEMA HMA KAMA
Momentum RSI MACD Stochastic CCI ROC WilliamsR ADX MFI TRIX
AwesomeOscillator Aroon
Volatility BollingerBands ATR Keltner Donchian PSAR
Volume OBV VWAP (cumulative + rolling)
cargo clippy --workspace --all-targets -D warnings is clean. License: Apache-2.0.
This commit is contained in:
@@ -0,0 +1,298 @@
|
||||
//! Average Directional Index (ADX) with +DI / -DI components.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// ADX output: the three Wilder lines.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AdxOutput {
|
||||
/// Plus Directional Indicator.
|
||||
pub plus_di: f64,
|
||||
/// Minus Directional Indicator.
|
||||
pub minus_di: f64,
|
||||
/// Average Directional Index (smoothed |DX|).
|
||||
pub adx: f64,
|
||||
}
|
||||
|
||||
/// Wilder's Average Directional Index.
|
||||
///
|
||||
/// Uses Wilder smoothing throughout. First `period` candles seed the directional
|
||||
/// movement / true range sums; the next `period` candles produce DX values that
|
||||
/// seed the ADX. The first complete `AdxOutput` is emitted after `2 * period`
|
||||
/// candles.
|
||||
#[allow(clippy::struct_field_names)] // adx_value pairs with adx (the output line) — renaming hurts clarity
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Adx {
|
||||
period: usize,
|
||||
prev: Option<Candle>,
|
||||
|
||||
// Wilder-smoothed sums during seeding.
|
||||
tr_seed: f64,
|
||||
plus_dm_seed: f64,
|
||||
minus_dm_seed: f64,
|
||||
seed_count: usize,
|
||||
|
||||
// Smoothed running values after seeding.
|
||||
tr_smooth: Option<f64>,
|
||||
plus_dm_smooth: Option<f64>,
|
||||
minus_dm_smooth: Option<f64>,
|
||||
|
||||
// ADX seeding.
|
||||
dx_buf: Vec<f64>,
|
||||
adx_value: Option<f64>,
|
||||
last_plus_di: f64,
|
||||
last_minus_di: f64,
|
||||
}
|
||||
|
||||
impl Adx {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
prev: None,
|
||||
tr_seed: 0.0,
|
||||
plus_dm_seed: 0.0,
|
||||
minus_dm_seed: 0.0,
|
||||
seed_count: 0,
|
||||
tr_smooth: None,
|
||||
plus_dm_smooth: None,
|
||||
minus_dm_smooth: None,
|
||||
dx_buf: Vec::with_capacity(period),
|
||||
adx_value: None,
|
||||
last_plus_di: 0.0,
|
||||
last_minus_di: 0.0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
fn directional_movement(prev: &Candle, current: &Candle) -> (f64, f64) {
|
||||
let up = current.high - prev.high;
|
||||
let down = prev.low - current.low;
|
||||
let plus_dm = if up > down && up > 0.0 { up } else { 0.0 };
|
||||
let minus_dm = if down > up && down > 0.0 { down } else { 0.0 };
|
||||
(plus_dm, minus_dm)
|
||||
}
|
||||
|
||||
impl Indicator for Adx {
|
||||
type Input = Candle;
|
||||
type Output = AdxOutput;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<AdxOutput> {
|
||||
let Some(prev) = self.prev else {
|
||||
self.prev = Some(candle);
|
||||
return None;
|
||||
};
|
||||
self.prev = Some(candle);
|
||||
|
||||
let tr = candle.true_range(Some(prev.close));
|
||||
let (plus_dm, minus_dm) = directional_movement(&prev, &candle);
|
||||
let n = self.period as f64;
|
||||
|
||||
let (tr_v, plus_v, minus_v) = if let (Some(t), Some(p), Some(m)) =
|
||||
(self.tr_smooth, self.plus_dm_smooth, self.minus_dm_smooth)
|
||||
{
|
||||
let t_new = t - t / n + tr;
|
||||
let p_new = p - p / n + plus_dm;
|
||||
let m_new = m - m / n + minus_dm;
|
||||
self.tr_smooth = Some(t_new);
|
||||
self.plus_dm_smooth = Some(p_new);
|
||||
self.minus_dm_smooth = Some(m_new);
|
||||
(t_new, p_new, m_new)
|
||||
} else {
|
||||
self.tr_seed += tr;
|
||||
self.plus_dm_seed += plus_dm;
|
||||
self.minus_dm_seed += minus_dm;
|
||||
self.seed_count += 1;
|
||||
if self.seed_count < self.period {
|
||||
return None;
|
||||
}
|
||||
self.tr_smooth = Some(self.tr_seed);
|
||||
self.plus_dm_smooth = Some(self.plus_dm_seed);
|
||||
self.minus_dm_smooth = Some(self.minus_dm_seed);
|
||||
(self.tr_seed, self.plus_dm_seed, self.minus_dm_seed)
|
||||
};
|
||||
|
||||
let plus_di = if tr_v == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
100.0 * plus_v / tr_v
|
||||
};
|
||||
let minus_di = if tr_v == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
100.0 * minus_v / tr_v
|
||||
};
|
||||
self.last_plus_di = plus_di;
|
||||
self.last_minus_di = minus_di;
|
||||
|
||||
let dx_den = plus_di + minus_di;
|
||||
let dx = if dx_den == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
100.0 * (plus_di - minus_di).abs() / dx_den
|
||||
};
|
||||
|
||||
if let Some(prev_adx) = self.adx_value {
|
||||
let new_adx = (prev_adx * (n - 1.0) + dx) / n;
|
||||
self.adx_value = Some(new_adx);
|
||||
return Some(AdxOutput {
|
||||
plus_di,
|
||||
minus_di,
|
||||
adx: new_adx,
|
||||
});
|
||||
}
|
||||
|
||||
self.dx_buf.push(dx);
|
||||
if self.dx_buf.len() == self.period {
|
||||
let seed = self.dx_buf.iter().sum::<f64>() / n;
|
||||
self.adx_value = Some(seed);
|
||||
return Some(AdxOutput {
|
||||
plus_di,
|
||||
minus_di,
|
||||
adx: seed,
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev = None;
|
||||
self.tr_seed = 0.0;
|
||||
self.plus_dm_seed = 0.0;
|
||||
self.minus_dm_seed = 0.0;
|
||||
self.seed_count = 0;
|
||||
self.tr_smooth = None;
|
||||
self.plus_dm_smooth = None;
|
||||
self.minus_dm_smooth = None;
|
||||
self.dx_buf.clear();
|
||||
self.adx_value = None;
|
||||
self.last_plus_di = 0.0;
|
||||
self.last_minus_di = 0.0;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
2 * self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.adx_value.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"ADX"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_yields_plus_di_dominant() {
|
||||
// Strict uptrend: highs increase, lows increase, ADX should trend up,
|
||||
// +DI should dominate -DI.
|
||||
let candles: Vec<Candle> = (0..50)
|
||||
.map(|i| {
|
||||
let base = 100.0 + f64::from(i) * 2.0;
|
||||
c(base + 1.0, base - 0.5, base + 0.5)
|
||||
})
|
||||
.collect();
|
||||
let mut adx = Adx::new(14).unwrap();
|
||||
let last = adx
|
||||
.batch(&candles)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.last()
|
||||
.expect("emits");
|
||||
assert!(
|
||||
last.plus_di > last.minus_di,
|
||||
"+DI {} should exceed -DI {}",
|
||||
last.plus_di,
|
||||
last.minus_di
|
||||
);
|
||||
assert!(last.adx > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_downtrend_yields_minus_di_dominant() {
|
||||
let candles: Vec<Candle> = (0..50)
|
||||
.rev()
|
||||
.map(|i| {
|
||||
let base = 100.0 + f64::from(i) * 2.0;
|
||||
c(base + 1.0, base - 0.5, base + 0.5)
|
||||
})
|
||||
.collect();
|
||||
let mut adx = Adx::new(14).unwrap();
|
||||
let last = adx
|
||||
.batch(&candles)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.last()
|
||||
.expect("emits");
|
||||
assert!(last.minus_di > last.plus_di);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(Adx::new(0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..60)
|
||||
.map(|i| {
|
||||
let base = 100.0 + (f64::from(i) * 0.3).sin() * 5.0;
|
||||
c(base + 1.0, base - 1.0, base)
|
||||
})
|
||||
.collect();
|
||||
let mut a = Adx::new(14).unwrap();
|
||||
let mut b = Adx::new(14).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let candles: Vec<Candle> = (0..40).map(|_| c(11.0, 9.0, 10.0)).collect();
|
||||
let mut adx = Adx::new(14).unwrap();
|
||||
adx.batch(&candles);
|
||||
adx.reset();
|
||||
assert!(!adx.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outputs_remain_finite() {
|
||||
let candles: Vec<Candle> = (0..200)
|
||||
.map(|i| {
|
||||
let m = 100.0 + (f64::from(i) * 0.2).sin() * 5.0;
|
||||
c(m + 1.0, m - 1.0, m)
|
||||
})
|
||||
.collect();
|
||||
let mut adx = Adx::new(14).unwrap();
|
||||
for v in adx.batch(&candles).into_iter().flatten() {
|
||||
assert!(v.plus_di.is_finite() && v.minus_di.is_finite() && v.adx.is_finite());
|
||||
}
|
||||
// Sanity: ADX is bounded by 100.
|
||||
let last = adx.batch(&candles).into_iter().flatten().last().unwrap();
|
||||
assert!(last.adx <= 100.0 + 1e-6);
|
||||
assert_relative_eq!(0.0_f64.max(last.adx), last.adx, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Aroon Up / Down indicator.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Aroon output: up and down strengths in [0, 100].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AroonOutput {
|
||||
/// Time since the highest high, expressed as a percentage of the window.
|
||||
pub up: f64,
|
||||
/// Time since the lowest low, same convention.
|
||||
pub down: f64,
|
||||
}
|
||||
|
||||
/// Aroon indicator: tracks how many bars since the highest high and lowest low
|
||||
/// inside a `period + 1`-bar window. Returned as a percentage.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Aroon {
|
||||
period: usize,
|
||||
candles: VecDeque<Candle>,
|
||||
}
|
||||
|
||||
impl Aroon {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
candles: VecDeque::with_capacity(period + 1),
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Aroon {
|
||||
type Input = Candle;
|
||||
type Output = AroonOutput;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<AroonOutput> {
|
||||
if self.candles.len() == self.period + 1 {
|
||||
self.candles.pop_front();
|
||||
}
|
||||
self.candles.push_back(candle);
|
||||
if self.candles.len() < self.period + 1 {
|
||||
return None;
|
||||
}
|
||||
// Find the index (0 = oldest) of the highest high and lowest low.
|
||||
let (mut hh_idx, mut ll_idx) = (0_usize, 0_usize);
|
||||
let (mut hh, mut ll) = (f64::NEG_INFINITY, f64::INFINITY);
|
||||
for (i, c) in self.candles.iter().enumerate() {
|
||||
if c.high >= hh {
|
||||
hh = c.high;
|
||||
hh_idx = i;
|
||||
}
|
||||
if c.low <= ll {
|
||||
ll = c.low;
|
||||
ll_idx = i;
|
||||
}
|
||||
}
|
||||
let n = self.period as f64;
|
||||
let up = 100.0 * hh_idx as f64 / n;
|
||||
let down = 100.0 * ll_idx as f64 / n;
|
||||
Some(AroonOutput { up, down })
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.candles.clear();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period + 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.candles.len() == self.period + 1
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"Aroon"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_aroon_up_100() {
|
||||
let candles: Vec<Candle> = (1..=15)
|
||||
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
|
||||
.collect();
|
||||
let mut a = Aroon::new(14).unwrap();
|
||||
let last = a.batch(&candles).into_iter().flatten().last().unwrap();
|
||||
assert_relative_eq!(last.up, 100.0, epsilon = 1e-9);
|
||||
// The lowest low is at the oldest position (index 0).
|
||||
assert_relative_eq!(last.down, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_downtrend_aroon_down_100() {
|
||||
let candles: Vec<Candle> = (1..=15)
|
||||
.rev()
|
||||
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
|
||||
.collect();
|
||||
let mut a = Aroon::new(14).unwrap();
|
||||
let last = a.batch(&candles).into_iter().flatten().last().unwrap();
|
||||
assert_relative_eq!(last.down, 100.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.map(|i| {
|
||||
let m = 50.0 + (f64::from(i) * 0.3).sin() * 5.0;
|
||||
c(m + 1.0, m - 1.0, m)
|
||||
})
|
||||
.collect();
|
||||
let mut a = Aroon::new(14).unwrap();
|
||||
let mut b = Aroon::new(14).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outputs_in_range() {
|
||||
let candles: Vec<Candle> = (0..200)
|
||||
.map(|i| {
|
||||
let m = 50.0 + (f64::from(i) * 0.2).sin() * 5.0;
|
||||
c(m + 1.0, m - 1.0, m)
|
||||
})
|
||||
.collect();
|
||||
let mut a = Aroon::new(14).unwrap();
|
||||
for o in a.batch(&candles).into_iter().flatten() {
|
||||
assert!((0.0..=100.0).contains(&o.up));
|
||||
assert!((0.0..=100.0).contains(&o.down));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Average True Range (Wilder).
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Average True Range with Wilder smoothing.
|
||||
///
|
||||
/// The first emitted value, by convention, appears after `period` candles: the
|
||||
/// first `period − 1` true-range values seed the Wilder average alongside the
|
||||
/// `period`-th, then the smoothed update begins.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Atr {
|
||||
period: usize,
|
||||
prev_close: Option<f64>,
|
||||
seed_buf: Vec<f64>,
|
||||
avg: Option<f64>,
|
||||
}
|
||||
|
||||
impl Atr {
|
||||
/// Construct an ATR with the given Wilder 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,
|
||||
prev_close: None,
|
||||
seed_buf: Vec::with_capacity(period),
|
||||
avg: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.avg
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Atr {
|
||||
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);
|
||||
|
||||
if let Some(avg) = self.avg {
|
||||
let n = self.period as f64;
|
||||
let new_avg = avg.mul_add(n - 1.0, tr) / n;
|
||||
self.avg = Some(new_avg);
|
||||
return Some(new_avg);
|
||||
}
|
||||
|
||||
self.seed_buf.push(tr);
|
||||
if self.seed_buf.len() == self.period {
|
||||
let seed = self.seed_buf.iter().copied().sum::<f64>() / self.period as f64;
|
||||
self.avg = Some(seed);
|
||||
return Some(seed);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev_close = None;
|
||||
self.seed_buf.clear();
|
||||
self.avg = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.avg.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"ATR"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
// ts/open/volume don't affect ATR; use safe placeholders.
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(matches!(Atr::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_emits_on_period_th_candle() {
|
||||
let candles = vec![
|
||||
c(2.0, 1.0, 1.5),
|
||||
c(3.0, 2.0, 2.5),
|
||||
c(4.0, 3.0, 3.5),
|
||||
c(5.0, 4.0, 4.5),
|
||||
c(6.0, 5.0, 5.5),
|
||||
];
|
||||
let mut atr = Atr::new(3).unwrap();
|
||||
let out = atr.batch(&candles);
|
||||
assert!(out[0].is_none());
|
||||
assert!(out[1].is_none());
|
||||
assert!(out[2].is_some());
|
||||
assert!(out[3].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_range_yields_constant_atr() {
|
||||
// Every candle has H=11, L=9, C=10 -> TR=2 (no gaps).
|
||||
let candles: Vec<Candle> = (0..30).map(|_| c(11.0, 9.0, 10.0)).collect();
|
||||
let mut atr = Atr::new(14).unwrap();
|
||||
let out = atr.batch(&candles);
|
||||
for v in out.iter().skip(13).flatten() {
|
||||
assert_relative_eq!(*v, 2.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gap_up_uses_high_minus_prev_close() {
|
||||
// Previous close 5, current candle H=10 L=9 C=9.5 -> TR = max(1, 5, 4) = 5.
|
||||
let candles = vec![
|
||||
c(6.0, 4.0, 5.0), // prev close = 5
|
||||
c(10.0, 9.0, 9.5), // TR = 5
|
||||
];
|
||||
let mut atr = Atr::new(2).unwrap();
|
||||
let out = atr.batch(&candles);
|
||||
// Seed window covers TR_1 and TR_2. TR_1 = H1-L1 = 2 (no prev close). TR_2 = 5.
|
||||
// Seed = (2+5)/2 = 3.5
|
||||
assert_relative_eq!(out[1].unwrap(), 3.5, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.map(|i| {
|
||||
let mid = f64::from(i) + 10.0;
|
||||
c(mid + 0.5, mid - 0.5, mid)
|
||||
})
|
||||
.collect();
|
||||
let mut a = Atr::new(14).unwrap();
|
||||
let mut b = Atr::new(14).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let candles: Vec<Candle> = (0..20).map(|_| c(11.0, 9.0, 10.0)).collect();
|
||||
let mut atr = Atr::new(5).unwrap();
|
||||
atr.batch(&candles);
|
||||
assert!(atr.is_ready());
|
||||
atr.reset();
|
||||
assert!(!atr.is_ready());
|
||||
assert_eq!(atr.update(candles[0]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_negative() {
|
||||
let candles: Vec<Candle> = (0..200)
|
||||
.map(|i| {
|
||||
let base = 100.0 + (f64::from(i) * 0.3).sin() * 5.0;
|
||||
c(base + 1.0, base - 1.0, base)
|
||||
})
|
||||
.collect();
|
||||
let mut atr = Atr::new(14).unwrap();
|
||||
for v in atr.batch(&candles).into_iter().flatten() {
|
||||
assert!(v >= 0.0, "ATR must be non-negative: {v}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Awesome Oscillator (Bill Williams).
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::indicators::sma::Sma;
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Awesome Oscillator: `SMA(median_price, 5) - SMA(median_price, 34)`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AwesomeOscillator {
|
||||
fast: Sma,
|
||||
slow: Sma,
|
||||
fast_period: usize,
|
||||
slow_period: usize,
|
||||
}
|
||||
|
||||
impl AwesomeOscillator {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] for zero periods or [`Error::InvalidPeriod`] when fast >= slow.
|
||||
pub fn new(fast: usize, slow: usize) -> Result<Self> {
|
||||
if fast == 0 || slow == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if fast >= slow {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "AO fast period must be strictly less than slow",
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
fast: Sma::new(fast)?,
|
||||
slow: Sma::new(slow)?,
|
||||
fast_period: fast,
|
||||
slow_period: slow,
|
||||
})
|
||||
}
|
||||
|
||||
/// Classic Bill Williams configuration: (5, 34).
|
||||
pub fn classic() -> Self {
|
||||
Self::new(5, 34).expect("classic AO periods are valid")
|
||||
}
|
||||
|
||||
/// Configured `(fast, slow)` periods.
|
||||
pub const fn periods(&self) -> (usize, usize) {
|
||||
(self.fast_period, self.slow_period)
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for AwesomeOscillator {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
let median = candle.median_price();
|
||||
let f = self.fast.update(median);
|
||||
let s = self.slow.update(median);
|
||||
match (f, s) {
|
||||
(Some(a), Some(b)) => Some(a - b),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.fast.reset();
|
||||
self.slow.reset();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.slow_period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.slow.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"AwesomeOscillator"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
let candles: Vec<Candle> = (0..80).map(|_| c(11.0, 9.0, 10.0)).collect();
|
||||
let mut ao = AwesomeOscillator::classic();
|
||||
let last = ao.batch(&candles).into_iter().flatten().last().unwrap();
|
||||
assert_relative_eq!(last, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_fast_geq_slow() {
|
||||
assert!(AwesomeOscillator::new(34, 5).is_err());
|
||||
assert!(AwesomeOscillator::new(5, 5).is_err());
|
||||
assert!(AwesomeOscillator::new(0, 5).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..50)
|
||||
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
|
||||
.collect();
|
||||
let mut a = AwesomeOscillator::classic();
|
||||
let mut b = AwesomeOscillator::classic();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Bollinger Bands.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Bollinger Bands output.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BollingerOutput {
|
||||
/// Upper band: `middle + multiplier * stddev`.
|
||||
pub upper: f64,
|
||||
/// Middle band: SMA over the window.
|
||||
pub middle: f64,
|
||||
/// Lower band: `middle − multiplier * stddev`.
|
||||
pub lower: f64,
|
||||
/// Sample standard deviation (denominator `period`, population stddev) used to build
|
||||
/// the bands. Reported separately because some callers compute their own bands.
|
||||
pub stddev: f64,
|
||||
}
|
||||
|
||||
/// Bollinger Bands with SMA middle band and population standard deviation envelopes.
|
||||
///
|
||||
/// Standard parameters are `period = 20`, `multiplier = 2.0`. Bollinger's original
|
||||
/// publication uses population (not sample) standard deviation, which matches every
|
||||
/// reference implementation (TA-Lib, pandas-ta, etc.).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BollingerBands {
|
||||
period: usize,
|
||||
multiplier: f64,
|
||||
window: VecDeque<f64>,
|
||||
sum: f64,
|
||||
sum_sq: f64,
|
||||
}
|
||||
|
||||
impl BollingerBands {
|
||||
/// Construct a new Bollinger Bands indicator.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] for `period == 0` and
|
||||
/// [`Error::NonPositiveMultiplier`] for `multiplier <= 0`.
|
||||
pub fn new(period: usize, multiplier: f64) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if !multiplier.is_finite() || multiplier <= 0.0 {
|
||||
return Err(Error::NonPositiveMultiplier);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
multiplier,
|
||||
window: VecDeque::with_capacity(period),
|
||||
sum: 0.0,
|
||||
sum_sq: 0.0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Classic configuration: `period = 20`, `multiplier = 2.0`.
|
||||
pub fn classic() -> Self {
|
||||
Self::new(20, 2.0).expect("classic Bollinger parameters are valid")
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Configured multiplier.
|
||||
pub const fn multiplier(&self) -> f64 {
|
||||
self.multiplier
|
||||
}
|
||||
|
||||
fn current(&self) -> Option<BollingerOutput> {
|
||||
if self.window.len() != self.period {
|
||||
return None;
|
||||
}
|
||||
let n = self.period as f64;
|
||||
let mean = self.sum / n;
|
||||
// Population variance: E[x^2] - (E[x])^2. Clamp small negative values that arise
|
||||
// from catastrophic cancellation on near-constant inputs.
|
||||
let var = (self.sum_sq / n - mean * mean).max(0.0);
|
||||
let stddev = var.sqrt();
|
||||
Some(BollingerOutput {
|
||||
upper: mean + self.multiplier * stddev,
|
||||
middle: mean,
|
||||
lower: mean - self.multiplier * stddev,
|
||||
stddev,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for BollingerBands {
|
||||
type Input = f64;
|
||||
type Output = BollingerOutput;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<BollingerOutput> {
|
||||
if !input.is_finite() {
|
||||
return self.current();
|
||||
}
|
||||
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(input);
|
||||
self.sum += input;
|
||||
self.sum_sq += input * input;
|
||||
self.current()
|
||||
}
|
||||
|
||||
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 {
|
||||
"BollingerBands"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn naive(prices: &[f64], period: usize, mult: f64) -> Option<BollingerOutput> {
|
||||
if prices.len() < period {
|
||||
return None;
|
||||
}
|
||||
let w = &prices[prices.len() - period..];
|
||||
let mean = w.iter().sum::<f64>() / period as f64;
|
||||
let var = w.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / period as f64;
|
||||
let s = var.sqrt();
|
||||
Some(BollingerOutput {
|
||||
upper: mean + mult * s,
|
||||
middle: mean,
|
||||
lower: mean - mult * s,
|
||||
stddev: s,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(matches!(
|
||||
BollingerBands::new(0, 2.0),
|
||||
Err(Error::PeriodZero)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_positive_multiplier() {
|
||||
assert!(matches!(
|
||||
BollingerBands::new(20, 0.0),
|
||||
Err(Error::NonPositiveMultiplier)
|
||||
));
|
||||
assert!(matches!(
|
||||
BollingerBands::new(20, -1.0),
|
||||
Err(Error::NonPositiveMultiplier)
|
||||
));
|
||||
assert!(matches!(
|
||||
BollingerBands::new(20, f64::NAN),
|
||||
Err(Error::NonPositiveMultiplier)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_returns_none() {
|
||||
let mut bb = BollingerBands::new(5, 2.0).unwrap();
|
||||
for v in [1.0, 2.0, 3.0, 4.0] {
|
||||
assert!(bb.update(v).is_none());
|
||||
}
|
||||
assert!(bb.update(5.0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero_stddev() {
|
||||
let mut bb = BollingerBands::new(10, 2.0).unwrap();
|
||||
let out = bb.batch(&[5.0_f64; 30]);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert_relative_eq!(last.middle, 5.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(last.stddev, 0.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(last.upper, 5.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(last.lower, 5.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_naive_definition() {
|
||||
let prices: Vec<f64> = (1..=60)
|
||||
.map(|i| (f64::from(i) * 0.3).sin() * 10.0 + 50.0)
|
||||
.collect();
|
||||
let mut bb = BollingerBands::new(20, 2.0).unwrap();
|
||||
let out = bb.batch(&prices);
|
||||
for i in 19..prices.len() {
|
||||
let got = out[i].unwrap();
|
||||
let want = naive(&prices[..=i], 20, 2.0).unwrap();
|
||||
assert_relative_eq!(got.middle, want.middle, epsilon = 1e-9);
|
||||
assert_relative_eq!(got.stddev, want.stddev, epsilon = 1e-9);
|
||||
assert_relative_eq!(got.upper, want.upper, epsilon = 1e-9);
|
||||
assert_relative_eq!(got.lower, want.lower, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upper_above_middle_above_lower() {
|
||||
let prices: Vec<f64> = (1..=100).map(f64::from).collect();
|
||||
let mut bb = BollingerBands::new(20, 2.0).unwrap();
|
||||
for o in bb.batch(&prices).into_iter().flatten() {
|
||||
assert!(o.upper >= o.middle);
|
||||
assert!(o.middle >= o.lower);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=50).map(|i| f64::from(i) * 0.7).collect();
|
||||
let mut a = BollingerBands::new(10, 2.0).unwrap();
|
||||
let mut b = BollingerBands::new(10, 2.0).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut bb = BollingerBands::new(5, 2.0).unwrap();
|
||||
bb.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
assert!(bb.is_ready());
|
||||
bb.reset();
|
||||
assert!(!bb.is_ready());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Commodity Channel Index (CCI).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Commodity Channel Index.
|
||||
///
|
||||
/// `CCI = (TP - SMA(TP)) / (0.015 * mean absolute deviation of TP)`, where
|
||||
/// `TP = (high + low + close) / 3`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Cci {
|
||||
period: usize,
|
||||
factor: f64,
|
||||
window: VecDeque<f64>,
|
||||
sum: f64,
|
||||
}
|
||||
|
||||
impl Cci {
|
||||
/// Construct a new CCI with the canonical 0.015 scaling factor.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
Self::with_factor(period, 0.015)
|
||||
}
|
||||
|
||||
/// Construct a CCI with a custom scaling factor (the standard literature
|
||||
/// uses 0.015 to put roughly 70 % of values inside ±100).
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0` and
|
||||
/// [`Error::NonPositiveMultiplier`] if `factor <= 0`.
|
||||
pub fn with_factor(period: usize, factor: f64) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if !factor.is_finite() || factor <= 0.0 {
|
||||
return Err(Error::NonPositiveMultiplier);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
factor,
|
||||
window: VecDeque::with_capacity(period),
|
||||
sum: 0.0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Cci {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
let tp = candle.typical_price();
|
||||
if self.window.len() == self.period {
|
||||
let old = self.window.pop_front().expect("non-empty");
|
||||
self.sum -= old;
|
||||
}
|
||||
self.window.push_back(tp);
|
||||
self.sum += tp;
|
||||
if self.window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let n = self.period as f64;
|
||||
let mean = self.sum / n;
|
||||
let mad: f64 = self.window.iter().map(|v| (v - mean).abs()).sum::<f64>() / n;
|
||||
if mad == 0.0 {
|
||||
return Some(0.0);
|
||||
}
|
||||
Some((tp - mean) / (self.factor * mad))
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.sum = 0.0;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.window.len() == self.period
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"CCI"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_candles_yield_zero() {
|
||||
let candles: Vec<Candle> = (0..30).map(|_| c(10.0, 10.0, 10.0)).collect();
|
||||
let mut cci = Cci::new(20).unwrap();
|
||||
for v in cci.batch(&candles).into_iter().flatten() {
|
||||
assert_relative_eq!(v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_input() {
|
||||
assert!(Cci::new(0).is_err());
|
||||
assert!(Cci::with_factor(20, 0.0).is_err());
|
||||
assert!(Cci::with_factor(20, -1.0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..60)
|
||||
.map(|i| {
|
||||
let m = 50.0 + (f64::from(i) * 0.2).sin() * 10.0;
|
||||
c(m + 1.0, m - 1.0, m)
|
||||
})
|
||||
.collect();
|
||||
let mut a = Cci::new(20).unwrap();
|
||||
let mut b = Cci::new(20).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let candles: Vec<Candle> = (0..30).map(|_| c(10.0, 10.0, 10.0)).collect();
|
||||
let mut cci = Cci::new(20).unwrap();
|
||||
cci.batch(&candles);
|
||||
assert!(cci.is_ready());
|
||||
cci.reset();
|
||||
assert!(!cci.is_ready());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Double Exponential Moving Average (DEMA).
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::indicators::ema::Ema;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Double Exponential Moving Average: `2 * EMA - EMA(EMA)`.
|
||||
///
|
||||
/// Designed by Patrick Mulloy to reduce the lag of a single EMA while keeping
|
||||
/// the smoothing benefit.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Dema {
|
||||
ema1: Ema,
|
||||
ema2: Ema,
|
||||
period: usize,
|
||||
}
|
||||
|
||||
impl Dema {
|
||||
/// # Errors
|
||||
/// Returns [`crate::Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
Ok(Self {
|
||||
ema1: Ema::new(period)?,
|
||||
ema2: Ema::new(period)?,
|
||||
period,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Dema {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
let e1 = self.ema1.update(input)?;
|
||||
let e2 = self.ema2.update(e1)?;
|
||||
Some(2.0 * e1 - e2)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.ema1.reset();
|
||||
self.ema2.reset();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// EMA1 seeds at period, then EMA2 needs another (period - 1) values to seed.
|
||||
2 * self.period - 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.ema2.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"DEMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_constant_dema() {
|
||||
let mut dema = Dema::new(5).unwrap();
|
||||
let out = dema.batch(&[100.0_f64; 60]);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert_relative_eq!(*last, 100.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_uptrend_dema_above_ema_eventually() {
|
||||
// On a linear uptrend DEMA should be ahead of (greater than) a plain EMA,
|
||||
// because the second-order correction removes lag.
|
||||
let prices: Vec<f64> = (1..=200).map(f64::from).collect();
|
||||
let mut dema = Dema::new(20).unwrap();
|
||||
let mut ema = Ema::new(20).unwrap();
|
||||
let dema_out = dema.batch(&prices);
|
||||
let ema_out = ema.batch(&prices);
|
||||
// Compare at the last index where both are ready.
|
||||
let d = dema_out.last().unwrap().unwrap();
|
||||
let e = ema_out.last().unwrap().unwrap();
|
||||
assert!(d > e, "DEMA={d} should exceed EMA={e} on uptrend");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=80).map(|i| f64::from(i) * 0.5).collect();
|
||||
let mut a = Dema::new(7).unwrap();
|
||||
let mut b = Dema::new(7).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut dema = Dema::new(5).unwrap();
|
||||
dema.batch(&(1..=50).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(dema.is_ready());
|
||||
dema.reset();
|
||||
assert!(!dema.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(Dema::new(0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Donchian Channels.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Donchian Channels output.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct DonchianOutput {
|
||||
/// Highest high over the lookback.
|
||||
pub upper: f64,
|
||||
/// Average of upper and lower.
|
||||
pub middle: f64,
|
||||
/// Lowest low over the lookback.
|
||||
pub lower: f64,
|
||||
}
|
||||
|
||||
/// Donchian Channels: rolling highest high / lowest low envelopes.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Donchian {
|
||||
period: usize,
|
||||
candles: VecDeque<Candle>,
|
||||
}
|
||||
|
||||
impl Donchian {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
candles: VecDeque::with_capacity(period),
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Donchian {
|
||||
type Input = Candle;
|
||||
type Output = DonchianOutput;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<DonchianOutput> {
|
||||
if self.candles.len() == self.period {
|
||||
self.candles.pop_front();
|
||||
}
|
||||
self.candles.push_back(candle);
|
||||
if self.candles.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let upper = self
|
||||
.candles
|
||||
.iter()
|
||||
.map(|c| c.high)
|
||||
.fold(f64::NEG_INFINITY, f64::max);
|
||||
let lower = self
|
||||
.candles
|
||||
.iter()
|
||||
.map(|c| c.low)
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
Some(DonchianOutput {
|
||||
upper,
|
||||
middle: (upper + lower) / 2.0,
|
||||
lower,
|
||||
})
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.candles.clear();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.candles.len() == self.period
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"DonchianChannels"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_market_yields_equal_bands() {
|
||||
let candles: Vec<Candle> = (0..20).map(|_| c(11.0, 9.0, 10.0)).collect();
|
||||
let mut d = Donchian::new(5).unwrap();
|
||||
let last = d.batch(&candles).into_iter().flatten().last().unwrap();
|
||||
assert_relative_eq!(last.upper, 11.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(last.lower, 9.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(last.middle, 10.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.map(|i| c(f64::from(i) + 2.0, f64::from(i), f64::from(i) + 1.0))
|
||||
.collect();
|
||||
let mut a = Donchian::new(10).unwrap();
|
||||
let mut b = Donchian::new(10).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upper_above_middle_above_lower() {
|
||||
let candles: Vec<Candle> = (0..50)
|
||||
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
|
||||
.collect();
|
||||
let mut d = Donchian::new(10).unwrap();
|
||||
for o in d.batch(&candles).into_iter().flatten() {
|
||||
assert!(o.upper >= o.middle);
|
||||
assert!(o.middle >= o.lower);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(Donchian::new(0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//! Exponential Moving Average.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Exponential Moving Average with smoothing factor `alpha = 2 / (period + 1)`.
|
||||
///
|
||||
/// The first value is seeded with the simple mean of the first `period` inputs
|
||||
/// (the classical TA-Lib convention). From then on each new input contributes
|
||||
/// `alpha * input + (1 - alpha) * previous`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Ema {
|
||||
period: usize,
|
||||
alpha: f64,
|
||||
state: Option<f64>,
|
||||
warmup_buf: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Ema {
|
||||
/// Construct an EMA 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 alpha = 2.0 / (period as f64 + 1.0);
|
||||
Ok(Self {
|
||||
period,
|
||||
alpha,
|
||||
state: None,
|
||||
warmup_buf: Vec::with_capacity(period),
|
||||
})
|
||||
}
|
||||
|
||||
/// Construct an EMA with a custom smoothing factor `alpha in (0, 1]`.
|
||||
///
|
||||
/// The reported `period` is derived from `alpha` via `2/alpha - 1` and rounded;
|
||||
/// `warmup_period()` falls back to `1` because the implementation seeds from the
|
||||
/// very first input.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::InvalidPeriod`] if `alpha` is not in `(0.0, 1.0]` or non-finite.
|
||||
pub fn with_alpha(alpha: f64) -> Result<Self> {
|
||||
if !alpha.is_finite() || alpha <= 0.0 || alpha > 1.0 {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "alpha must be in (0.0, 1.0]",
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
period: 1,
|
||||
alpha,
|
||||
state: None,
|
||||
warmup_buf: Vec::with_capacity(1),
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Smoothing factor.
|
||||
pub const fn alpha(&self) -> f64 {
|
||||
self.alpha
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.state
|
||||
}
|
||||
|
||||
/// Internal helper that feeds a value without finiteness validation. The caller
|
||||
/// guarantees `input.is_finite()`. Used by MACD which has already validated.
|
||||
pub(crate) fn step_unchecked(&mut self, input: f64) -> Option<f64> {
|
||||
if let Some(prev) = self.state {
|
||||
let new = self.alpha.mul_add(input, (1.0 - self.alpha) * prev);
|
||||
self.state = Some(new);
|
||||
return Some(new);
|
||||
}
|
||||
self.warmup_buf.push(input);
|
||||
if self.warmup_buf.len() == self.period {
|
||||
let seed = self.warmup_buf.iter().copied().sum::<f64>() / self.period as f64;
|
||||
self.state = Some(seed);
|
||||
return Some(seed);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Ema {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
return self.state;
|
||||
}
|
||||
self.step_unchecked(input)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.state = None;
|
||||
self.warmup_buf.clear();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.state.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"EMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Ema::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_returns_none_until_seed() {
|
||||
let mut ema = Ema::new(3).unwrap();
|
||||
assert_eq!(ema.update(1.0), None);
|
||||
assert_eq!(ema.update(2.0), None);
|
||||
assert_eq!(ema.update(3.0), Some(2.0)); // seed = SMA([1,2,3]) = 2
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_value_equals_sma_seed() {
|
||||
let mut ema = Ema::new(5).unwrap();
|
||||
let inputs = [10.0, 20.0, 30.0, 40.0, 50.0];
|
||||
let mut last = None;
|
||||
for v in inputs {
|
||||
last = ema.update(v);
|
||||
}
|
||||
assert_relative_eq!(last.unwrap(), 30.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alpha_matches_period_formula() {
|
||||
let ema = Ema::new(10).unwrap();
|
||||
assert_relative_eq!(ema.alpha(), 2.0 / 11.0, epsilon = 1e-15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn step_after_seed_uses_alpha_formula() {
|
||||
// period=3 => alpha = 0.5; seed = mean([1,2,3]) = 2; next input 10
|
||||
// expected = 0.5*10 + 0.5*2 = 6
|
||||
let mut ema = Ema::new(3).unwrap();
|
||||
ema.batch(&[1.0, 2.0, 3.0]);
|
||||
assert_relative_eq!(ema.update(10.0).unwrap(), 6.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_converges_to_constant() {
|
||||
let mut ema = Ema::new(10).unwrap();
|
||||
let out = ema.batch(&[42.0_f64; 100]);
|
||||
for x in out.iter().skip(9) {
|
||||
assert_relative_eq!(x.unwrap(), 42.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_alpha_validates_range() {
|
||||
assert!(Ema::with_alpha(0.5).is_ok());
|
||||
assert!(Ema::with_alpha(1.0).is_ok());
|
||||
assert!(matches!(
|
||||
Ema::with_alpha(0.0),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
Ema::with_alpha(1.5),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
Ema::with_alpha(f64::NAN),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut ema = Ema::new(3).unwrap();
|
||||
ema.batch(&[1.0, 2.0, 3.0]);
|
||||
assert!(ema.is_ready());
|
||||
ema.reset();
|
||||
assert!(!ema.is_ready());
|
||||
assert_eq!(ema.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=30).map(f64::from).collect();
|
||||
let mut a = Ema::new(5).unwrap();
|
||||
let mut b = Ema::new(5).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut ema = Ema::new(3).unwrap();
|
||||
ema.batch(&[1.0, 2.0, 3.0]);
|
||||
let before = ema.value();
|
||||
assert_eq!(ema.update(f64::NAN), before);
|
||||
assert_eq!(ema.update(f64::INFINITY), before);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! Hull Moving Average (HMA).
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::indicators::wma::Wma;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Hull Moving Average: `WMA(2 * WMA(n/2) - WMA(n), sqrt(n))`.
|
||||
///
|
||||
/// Designed by Alan Hull as a lag-free moving average that is also responsive.
|
||||
/// The square root of the period is rounded to the nearest integer (minimum 1).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Hma {
|
||||
period: usize,
|
||||
half_wma: Wma,
|
||||
full_wma: Wma,
|
||||
smooth_wma: Wma,
|
||||
}
|
||||
|
||||
impl Hma {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
let half = (period / 2).max(1);
|
||||
let smooth = (period as f64).sqrt().round() as usize;
|
||||
let smooth = smooth.max(1);
|
||||
Ok(Self {
|
||||
period,
|
||||
half_wma: Wma::new(half)?,
|
||||
full_wma: Wma::new(period)?,
|
||||
smooth_wma: Wma::new(smooth)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Hma {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
let h = self.half_wma.update(input)?;
|
||||
let f = self.full_wma.update(input)?;
|
||||
let diff = 2.0 * h - f;
|
||||
self.smooth_wma.update(diff)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.half_wma.reset();
|
||||
self.full_wma.reset();
|
||||
self.smooth_wma.reset();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
let sm = (self.period as f64).sqrt().round() as usize;
|
||||
self.period + sm.max(1) - 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.smooth_wma.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"HMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_constant_hma() {
|
||||
let mut hma = Hma::new(9).unwrap();
|
||||
let out = hma.batch(&[10.0_f64; 80]);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert_relative_eq!(*last, 10.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=100).map(|i| f64::from(i) * 0.7).collect();
|
||||
let mut a = Hma::new(9).unwrap();
|
||||
let mut b = Hma::new(9).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut hma = Hma::new(9).unwrap();
|
||||
hma.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(hma.is_ready());
|
||||
hma.reset();
|
||||
assert!(!hma.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(Hma::new(0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Kaufman's Adaptive Moving Average (KAMA).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Kaufman's Adaptive Moving Average.
|
||||
///
|
||||
/// KAMA adapts its smoothing constant to volatility: efficient (trending) markets
|
||||
/// get a fast smoothing constant, choppy markets get a slow one. Parameters are
|
||||
/// the efficiency-ratio lookback (`er_period`, default 10), the fast EMA period
|
||||
/// (`fast`, default 2) and the slow EMA period (`slow`, default 30).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Kama {
|
||||
er_period: usize,
|
||||
fast_sc: f64,
|
||||
slow_sc: f64,
|
||||
window: VecDeque<f64>,
|
||||
state: Option<f64>,
|
||||
}
|
||||
|
||||
impl Kama {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] / [`Error::InvalidPeriod`] for bad parameters.
|
||||
pub fn new(er_period: usize, fast: usize, slow: usize) -> Result<Self> {
|
||||
if er_period == 0 || fast == 0 || slow == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if fast >= slow {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "KAMA fast period must be strictly less than slow",
|
||||
});
|
||||
}
|
||||
let fast_sc = 2.0 / (fast as f64 + 1.0);
|
||||
let slow_sc = 2.0 / (slow as f64 + 1.0);
|
||||
Ok(Self {
|
||||
er_period,
|
||||
fast_sc,
|
||||
slow_sc,
|
||||
window: VecDeque::with_capacity(er_period + 1),
|
||||
state: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Classic Kaufman parameters: (10, 2, 30).
|
||||
pub fn classic() -> Self {
|
||||
Self::new(10, 2, 30).expect("classic KAMA parameters are valid")
|
||||
}
|
||||
|
||||
/// Configured `(er_period, fast, slow)` periods.
|
||||
pub fn periods(&self) -> (usize, f64, f64) {
|
||||
(self.er_period, self.fast_sc, self.slow_sc)
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Kama {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
return self.state;
|
||||
}
|
||||
if self.window.len() == self.er_period + 1 {
|
||||
self.window.pop_front();
|
||||
}
|
||||
self.window.push_back(input);
|
||||
|
||||
if self.window.len() < self.er_period + 1 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let first = *self.window.front().expect("non-empty");
|
||||
let last = *self.window.back().expect("non-empty");
|
||||
let direction = (last - first).abs();
|
||||
let volatility: f64 = self
|
||||
.window
|
||||
.iter()
|
||||
.zip(self.window.iter().skip(1))
|
||||
.map(|(a, b)| (b - a).abs())
|
||||
.sum();
|
||||
|
||||
let er = if volatility == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
direction / volatility
|
||||
};
|
||||
let sc = (er * (self.fast_sc - self.slow_sc) + self.slow_sc).powi(2);
|
||||
|
||||
let prev = self.state.unwrap_or(first);
|
||||
let new = prev + sc * (input - prev);
|
||||
self.state = Some(new);
|
||||
Some(new)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.state = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.er_period + 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.state.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"KAMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_constant_kama() {
|
||||
let mut k = Kama::classic();
|
||||
let out = k.batch(&[100.0_f64; 100]);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert_relative_eq!(*last, 100.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_periods() {
|
||||
assert!(Kama::new(0, 2, 30).is_err());
|
||||
assert!(Kama::new(10, 30, 2).is_err()); // fast >= slow
|
||||
assert!(Kama::new(10, 2, 2).is_err()); // fast == slow
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=120)
|
||||
.map(|i| (f64::from(i) * 0.2).sin() * 5.0 + f64::from(i) * 0.1)
|
||||
.collect();
|
||||
let mut a = Kama::classic();
|
||||
let mut b = Kama::classic();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut k = Kama::classic();
|
||||
k.batch(&(1..=50).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(k.is_ready());
|
||||
k.reset();
|
||||
assert!(!k.is_ready());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Keltner Channels.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::indicators::atr::Atr;
|
||||
use crate::indicators::ema::Ema;
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Keltner Channels output.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct KeltnerOutput {
|
||||
/// Upper band = middle + multiplier * ATR.
|
||||
pub upper: f64,
|
||||
/// Middle band = EMA of typical price.
|
||||
pub middle: f64,
|
||||
/// Lower band = middle - multiplier * ATR.
|
||||
pub lower: f64,
|
||||
}
|
||||
|
||||
/// Keltner Channels: an EMA centerline with bands sized by ATR.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Keltner {
|
||||
ema: Ema,
|
||||
atr: Atr,
|
||||
multiplier: f64,
|
||||
ema_period: usize,
|
||||
atr_period: usize,
|
||||
}
|
||||
|
||||
impl Keltner {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] / [`Error::NonPositiveMultiplier`] on invalid inputs.
|
||||
pub fn new(ema_period: usize, atr_period: usize, multiplier: f64) -> Result<Self> {
|
||||
if !multiplier.is_finite() || multiplier <= 0.0 {
|
||||
return Err(Error::NonPositiveMultiplier);
|
||||
}
|
||||
Ok(Self {
|
||||
ema: Ema::new(ema_period)?,
|
||||
atr: Atr::new(atr_period)?,
|
||||
multiplier,
|
||||
ema_period,
|
||||
atr_period,
|
||||
})
|
||||
}
|
||||
|
||||
/// Classic configuration: EMA(20), ATR(10), 2.0x multiplier.
|
||||
pub fn classic() -> Self {
|
||||
Self::new(20, 10, 2.0).expect("classic Keltner parameters are valid")
|
||||
}
|
||||
|
||||
/// Configured `(ema_period, atr_period, multiplier)`.
|
||||
pub const fn periods(&self) -> (usize, usize, f64) {
|
||||
(self.ema_period, self.atr_period, self.multiplier)
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Keltner {
|
||||
type Input = Candle;
|
||||
type Output = KeltnerOutput;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<KeltnerOutput> {
|
||||
let mid = self.ema.update(candle.typical_price())?;
|
||||
let atr = self.atr.update(candle)?;
|
||||
Some(KeltnerOutput {
|
||||
upper: mid + self.multiplier * atr,
|
||||
middle: mid,
|
||||
lower: mid - self.multiplier * atr,
|
||||
})
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.ema.reset();
|
||||
self.atr.reset();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.ema_period.max(self.atr_period)
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.ema.is_ready() && self.atr.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"KeltnerChannels"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_market_collapses_bands() {
|
||||
let candles: Vec<Candle> = (0..50).map(|_| c(10.0, 10.0, 10.0)).collect();
|
||||
let mut k = Keltner::new(20, 10, 2.0).unwrap();
|
||||
let last = k.batch(&candles).into_iter().flatten().last().unwrap();
|
||||
assert_relative_eq!(last.upper, last.middle, epsilon = 1e-9);
|
||||
assert_relative_eq!(last.lower, last.middle, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upper_above_middle_above_lower() {
|
||||
let candles: Vec<Candle> = (0..100)
|
||||
.map(|i| {
|
||||
let m = 100.0 + (f64::from(i) * 0.2).sin() * 5.0;
|
||||
c(m + 1.0, m - 1.0, m)
|
||||
})
|
||||
.collect();
|
||||
let mut k = Keltner::classic();
|
||||
for o in k.batch(&candles).into_iter().flatten() {
|
||||
assert!(o.upper >= o.middle);
|
||||
assert!(o.middle >= o.lower);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..50)
|
||||
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
|
||||
.collect();
|
||||
let mut a = Keltner::classic();
|
||||
let mut b = Keltner::classic();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_input() {
|
||||
assert!(Keltner::new(0, 10, 2.0).is_err());
|
||||
assert!(Keltner::new(20, 10, 0.0).is_err());
|
||||
assert!(Keltner::new(20, 10, -1.0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Moving Average Convergence Divergence (MACD).
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::indicators::ema::Ema;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// MACD output: the three classic series at a given step.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct MacdOutput {
|
||||
/// Fast EMA − slow EMA.
|
||||
pub macd: f64,
|
||||
/// EMA of `macd` over the signal period.
|
||||
pub signal: f64,
|
||||
/// `macd − signal`.
|
||||
pub histogram: f64,
|
||||
}
|
||||
|
||||
/// MACD = EMA(fast) − EMA(slow), with a signal EMA on top.
|
||||
///
|
||||
/// Standard parameters are `fast = 12`, `slow = 26`, `signal = 9`. The signal EMA
|
||||
/// is seeded from the first `signal` raw MACD values, so the first full
|
||||
/// [`MacdOutput`] is emitted after `slow + signal − 1` inputs (assuming the
|
||||
/// slow EMA seeded by then).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MacdIndicator {
|
||||
fast: Ema,
|
||||
slow: Ema,
|
||||
signal_ema: Ema,
|
||||
fast_period: usize,
|
||||
slow_period: usize,
|
||||
signal_period: usize,
|
||||
last: Option<MacdOutput>,
|
||||
}
|
||||
|
||||
impl MacdIndicator {
|
||||
/// Construct a MACD with the given periods.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if any period is zero, and
|
||||
/// [`Error::InvalidPeriod`] if `fast >= slow`.
|
||||
pub fn new(fast: usize, slow: usize, signal: usize) -> Result<Self> {
|
||||
if fast == 0 || slow == 0 || signal == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if fast >= slow {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "fast period must be strictly less than slow period",
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
fast: Ema::new(fast)?,
|
||||
slow: Ema::new(slow)?,
|
||||
signal_ema: Ema::new(signal)?,
|
||||
fast_period: fast,
|
||||
slow_period: slow,
|
||||
signal_period: signal,
|
||||
last: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Default `(12, 26, 9)` configuration, matching every classical chart package.
|
||||
pub fn classic() -> Self {
|
||||
Self::new(12, 26, 9).expect("classic MACD periods are valid")
|
||||
}
|
||||
|
||||
/// Configured periods as `(fast, slow, signal)`.
|
||||
pub const fn periods(&self) -> (usize, usize, usize) {
|
||||
(self.fast_period, self.slow_period, self.signal_period)
|
||||
}
|
||||
|
||||
/// Most recent fully-computed output if available.
|
||||
pub const fn value(&self) -> Option<MacdOutput> {
|
||||
self.last
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for MacdIndicator {
|
||||
type Input = f64;
|
||||
type Output = MacdOutput;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<MacdOutput> {
|
||||
if !input.is_finite() {
|
||||
return self.last;
|
||||
}
|
||||
|
||||
let fast = self.fast.update(input);
|
||||
let slow = self.slow.update(input);
|
||||
|
||||
match (fast, slow) {
|
||||
(Some(f), Some(s)) => {
|
||||
let macd = f - s;
|
||||
let signal = self.signal_ema.update(macd)?;
|
||||
let out = MacdOutput {
|
||||
macd,
|
||||
signal,
|
||||
histogram: macd - signal,
|
||||
};
|
||||
self.last = Some(out);
|
||||
Some(out)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.fast.reset();
|
||||
self.slow.reset();
|
||||
self.signal_ema.reset();
|
||||
self.last = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// Slow EMA needs `slow` inputs to seed; signal EMA needs another `signal - 1`.
|
||||
self.slow_period + self.signal_period - 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.last.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"MACD"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn rejects_fast_geq_slow() {
|
||||
assert!(matches!(
|
||||
MacdIndicator::new(26, 12, 9),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
MacdIndicator::new(12, 12, 9),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_periods() {
|
||||
assert!(matches!(
|
||||
MacdIndicator::new(0, 26, 9),
|
||||
Err(Error::PeriodZero)
|
||||
));
|
||||
assert!(matches!(
|
||||
MacdIndicator::new(12, 0, 9),
|
||||
Err(Error::PeriodZero)
|
||||
));
|
||||
assert!(matches!(
|
||||
MacdIndicator::new(12, 26, 0),
|
||||
Err(Error::PeriodZero)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_matches_warmup_period() {
|
||||
let prices: Vec<f64> = (1..=60).map(f64::from).collect();
|
||||
let mut macd = MacdIndicator::classic();
|
||||
let out = macd.batch(&prices);
|
||||
let warmup = macd.warmup_period();
|
||||
// Indices 0..warmup-1 are None, index warmup-1 might be Some or might still need
|
||||
// the signal EMA's seeding. Our warmup_period is the index at which the first
|
||||
// signal value appears: slow + signal - 1.
|
||||
for x in out.iter().take(warmup - 1) {
|
||||
assert!(x.is_none(), "expected None within warmup");
|
||||
}
|
||||
assert!(
|
||||
out[warmup - 1].is_some(),
|
||||
"expected first emission at warmup_period - 1 ({warmup} idx)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_equals_macd_minus_signal() {
|
||||
let prices: Vec<f64> = (1..=80).map(|i| f64::from(i) * 0.5).collect();
|
||||
let mut macd = MacdIndicator::classic();
|
||||
for v in macd.batch(&prices).into_iter().flatten() {
|
||||
assert_relative_eq!(v.histogram, v.macd - v.signal, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero_macd_eventually() {
|
||||
let mut macd = MacdIndicator::classic();
|
||||
let out = macd.batch(&[100.0_f64; 200]);
|
||||
// Both EMAs converge to 100, so MACD must approach 0.
|
||||
let last = out.iter().rev().flatten().next().expect("emits a value");
|
||||
assert_relative_eq!(last.macd, 0.0, epsilon = 1e-9);
|
||||
assert_relative_eq!(last.signal, 0.0, epsilon = 1e-9);
|
||||
assert_relative_eq!(last.histogram, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rising_series_macd_positive_then_signal_catches_up() {
|
||||
let prices: Vec<f64> = (1..=200).map(f64::from).collect();
|
||||
let mut macd = MacdIndicator::classic();
|
||||
let out = macd.batch(&prices);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert!(last.macd > 0.0, "rising series must yield positive MACD");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=100)
|
||||
.map(|i| (f64::from(i) * 0.4).cos() * 10.0)
|
||||
.collect();
|
||||
let mut a = MacdIndicator::classic();
|
||||
let mut b = MacdIndicator::classic();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut macd = MacdIndicator::classic();
|
||||
macd.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(macd.is_ready());
|
||||
macd.reset();
|
||||
assert!(!macd.is_ready());
|
||||
assert_eq!(macd.update(1.0), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Money Flow Index (MFI).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Money Flow Index: a volume-weighted version of RSI.
|
||||
///
|
||||
/// `MFI = 100 - 100 / (1 + positive_money_flow / negative_money_flow)` where
|
||||
/// money flow is `typical_price * volume`, classified positive when TP increases
|
||||
/// and negative when it decreases.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Mfi {
|
||||
period: usize,
|
||||
prev_tp: Option<f64>,
|
||||
pos_window: VecDeque<f64>,
|
||||
neg_window: VecDeque<f64>,
|
||||
pos_sum: f64,
|
||||
neg_sum: f64,
|
||||
}
|
||||
|
||||
impl Mfi {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
prev_tp: None,
|
||||
pos_window: VecDeque::with_capacity(period),
|
||||
neg_window: VecDeque::with_capacity(period),
|
||||
pos_sum: 0.0,
|
||||
neg_sum: 0.0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Mfi {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
let tp = candle.typical_price();
|
||||
let mf = tp * candle.volume;
|
||||
let (pos_flow, neg_flow) = match self.prev_tp {
|
||||
None => (0.0, 0.0),
|
||||
Some(prev) => {
|
||||
if tp > prev {
|
||||
(mf, 0.0)
|
||||
} else if tp < prev {
|
||||
(0.0, mf)
|
||||
} else {
|
||||
(0.0, 0.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if self.pos_window.len() == self.period {
|
||||
self.pos_sum -= self.pos_window.pop_front().expect("non-empty");
|
||||
self.neg_sum -= self.neg_window.pop_front().expect("non-empty");
|
||||
}
|
||||
self.pos_window.push_back(pos_flow);
|
||||
self.neg_window.push_back(neg_flow);
|
||||
self.pos_sum += pos_flow;
|
||||
self.neg_sum += neg_flow;
|
||||
|
||||
self.prev_tp = Some(tp);
|
||||
|
||||
// Need period+1 candles total (the first one only gives prev_tp).
|
||||
if self.prev_tp.is_none() || self.pos_window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
// Need at least one comparison-based flow inside the window, otherwise we
|
||||
// are still on the very first candle.
|
||||
if self.pos_sum == 0.0 && self.neg_sum == 0.0 {
|
||||
return Some(50.0);
|
||||
}
|
||||
if self.neg_sum == 0.0 {
|
||||
return Some(100.0);
|
||||
}
|
||||
let mr = self.pos_sum / self.neg_sum;
|
||||
Some(100.0 - 100.0 / (1.0 + mr))
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev_tp = None;
|
||||
self.pos_window.clear();
|
||||
self.neg_window.clear();
|
||||
self.pos_sum = 0.0;
|
||||
self.neg_sum = 0.0;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.pos_window.len() == self.period
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"MFI"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(price: f64, volume: f64) -> Candle {
|
||||
Candle::new(price, price, price, price, volume, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_yields_high_mfi() {
|
||||
let candles: Vec<Candle> = (1..30).map(|i| c(f64::from(i), 100.0)).collect();
|
||||
let mut mfi = Mfi::new(14).unwrap();
|
||||
let last = mfi.batch(&candles).into_iter().flatten().last().unwrap();
|
||||
assert_relative_eq!(last, 100.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_downtrend_yields_low_mfi() {
|
||||
let candles: Vec<Candle> = (1..30).rev().map(|i| c(f64::from(i), 100.0)).collect();
|
||||
let mut mfi = Mfi::new(14).unwrap();
|
||||
let last = mfi.batch(&candles).into_iter().flatten().last().unwrap();
|
||||
assert_relative_eq!(last, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..40).map(|i| c(f64::from(i) + 10.0, 50.0)).collect();
|
||||
let mut a = Mfi::new(14).unwrap();
|
||||
let mut b = Mfi::new(14).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let candles: Vec<Candle> = (1..30).map(|i| c(f64::from(i), 100.0)).collect();
|
||||
let mut mfi = Mfi::new(14).unwrap();
|
||||
mfi.batch(&candles);
|
||||
assert!(mfi.is_ready());
|
||||
mfi.reset();
|
||||
assert!(!mfi.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(Mfi::new(0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Built-in indicators. Every indicator implements [`crate::Indicator`].
|
||||
//!
|
||||
//! Modules are organised internally by category (trend, momentum, volatility,
|
||||
//! volume) but every public name is also re-exported flat from this module and
|
||||
//! from the crate root for convenience.
|
||||
|
||||
mod adx;
|
||||
mod aroon;
|
||||
mod atr;
|
||||
mod awesome_oscillator;
|
||||
mod bollinger;
|
||||
mod cci;
|
||||
mod dema;
|
||||
mod donchian;
|
||||
mod ema;
|
||||
mod hma;
|
||||
mod kama;
|
||||
mod keltner;
|
||||
mod macd;
|
||||
mod mfi;
|
||||
mod obv;
|
||||
mod psar;
|
||||
mod roc;
|
||||
mod rsi;
|
||||
mod sma;
|
||||
mod stochastic;
|
||||
mod tema;
|
||||
mod trix;
|
||||
mod vwap;
|
||||
mod williams_r;
|
||||
mod wma;
|
||||
|
||||
pub use adx::{Adx, AdxOutput};
|
||||
pub use aroon::{Aroon, AroonOutput};
|
||||
pub use atr::Atr;
|
||||
pub use awesome_oscillator::AwesomeOscillator;
|
||||
pub use bollinger::{BollingerBands, BollingerOutput};
|
||||
pub use cci::Cci;
|
||||
pub use dema::Dema;
|
||||
pub use donchian::{Donchian, DonchianOutput};
|
||||
pub use ema::Ema;
|
||||
pub use hma::Hma;
|
||||
pub use kama::Kama;
|
||||
pub use keltner::{Keltner, KeltnerOutput};
|
||||
pub use macd::{MacdIndicator, MacdOutput};
|
||||
pub use mfi::Mfi;
|
||||
pub use obv::Obv;
|
||||
pub use psar::Psar;
|
||||
pub use roc::Roc;
|
||||
pub use rsi::Rsi;
|
||||
pub use sma::Sma;
|
||||
pub use stochastic::{Stochastic, StochasticOutput};
|
||||
pub use tema::Tema;
|
||||
pub use trix::Trix;
|
||||
pub use vwap::{RollingVwap, Vwap};
|
||||
pub use williams_r::WilliamsR;
|
||||
pub use wma::Wma;
|
||||
@@ -0,0 +1,159 @@
|
||||
//! On-Balance Volume.
|
||||
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// On-Balance Volume: a cumulative signed-volume series.
|
||||
///
|
||||
/// Each candle adds `+volume`, `-volume`, or `0` depending on whether its close
|
||||
/// is above, below, or equal to the previous close. The first value (after the
|
||||
/// first candle) is conventionally `0`.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Obv {
|
||||
prev_close: Option<f64>,
|
||||
total: f64,
|
||||
has_emitted: bool,
|
||||
}
|
||||
|
||||
impl Obv {
|
||||
/// Construct a new OBV instance starting at zero.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
prev_close: None,
|
||||
total: 0.0,
|
||||
has_emitted: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Current cumulative value if at least one candle has been ingested.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
if self.has_emitted {
|
||||
Some(self.total)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Obv {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
// The first candle establishes the baseline at 0; subsequent candles
|
||||
// add/subtract their volume based on close direction. Equal closes do nothing.
|
||||
if let Some(prev) = self.prev_close {
|
||||
if candle.close > prev {
|
||||
self.total += candle.volume;
|
||||
} else if candle.close < prev {
|
||||
self.total -= candle.volume;
|
||||
}
|
||||
}
|
||||
self.prev_close = Some(candle.close);
|
||||
self.has_emitted = true;
|
||||
Some(self.total)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev_close = None;
|
||||
self.total = 0.0;
|
||||
self.has_emitted = false;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.has_emitted
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"OBV"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(close: f64, volume: f64) -> Candle {
|
||||
Candle::new(close, close, close, close, volume, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_candle_baseline_zero() {
|
||||
let mut obv = Obv::new();
|
||||
assert_relative_eq!(obv.update(c(10.0, 100.0)).unwrap(), 0.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn up_close_adds_volume() {
|
||||
let mut obv = Obv::new();
|
||||
obv.update(c(10.0, 100.0)); // baseline 0
|
||||
let v = obv.update(c(11.0, 50.0)).unwrap();
|
||||
assert_relative_eq!(v, 50.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn down_close_subtracts_volume() {
|
||||
let mut obv = Obv::new();
|
||||
obv.update(c(10.0, 100.0));
|
||||
let v = obv.update(c(9.0, 50.0)).unwrap();
|
||||
assert_relative_eq!(v, -50.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_close_does_nothing() {
|
||||
let mut obv = Obv::new();
|
||||
obv.update(c(10.0, 100.0));
|
||||
let v = obv.update(c(10.0, 50.0)).unwrap();
|
||||
assert_relative_eq!(v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cumulative_sequence() {
|
||||
let candles = vec![
|
||||
c(10.0, 100.0), // baseline
|
||||
c(11.0, 20.0), // +20
|
||||
c(10.5, 30.0), // -30
|
||||
c(10.5, 40.0), // unchanged
|
||||
c(12.0, 10.0), // +10
|
||||
];
|
||||
let mut obv = Obv::new();
|
||||
let out = obv.batch(&candles);
|
||||
assert_relative_eq!(out[0].unwrap(), 0.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(out[1].unwrap(), 20.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(out[2].unwrap(), -10.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(out[3].unwrap(), -10.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(out[4].unwrap(), 0.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..20)
|
||||
.map(|i| {
|
||||
let cl = 10.0 + (f64::from(i) * 0.5).sin();
|
||||
c(cl, 1.0)
|
||||
})
|
||||
.collect();
|
||||
let mut a = Obv::new();
|
||||
let mut b = Obv::new();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut obv = Obv::new();
|
||||
obv.batch(&[c(10.0, 50.0), c(11.0, 30.0)]);
|
||||
assert!(obv.is_ready());
|
||||
obv.reset();
|
||||
assert!(!obv.is_ready());
|
||||
assert_eq!(obv.value(), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! Parabolic SAR (Wilder).
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Trade direction in the SAR state machine.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Trend {
|
||||
Up,
|
||||
Down,
|
||||
}
|
||||
|
||||
/// Parabolic Stop And Reverse.
|
||||
///
|
||||
/// Implementation follows Wilder's original recursion: each step computes a new
|
||||
/// SAR from the previous SAR, extreme point (EP) and acceleration factor (AF);
|
||||
/// the trend flips when price crosses the SAR.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Psar {
|
||||
af_start: f64,
|
||||
af_step: f64,
|
||||
af_max: f64,
|
||||
|
||||
initialised: bool,
|
||||
prev_high: f64,
|
||||
prev_low: f64,
|
||||
trend: Trend,
|
||||
sar: f64,
|
||||
ep: f64,
|
||||
af: f64,
|
||||
}
|
||||
|
||||
impl Psar {
|
||||
/// Construct PSAR with explicit acceleration parameters.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`Error::NonPositiveMultiplier`] / [`Error::InvalidPeriod`] for invalid params.
|
||||
pub fn new(af_start: f64, af_step: f64, af_max: f64) -> Result<Self> {
|
||||
if !af_start.is_finite() || !af_step.is_finite() || !af_max.is_finite() {
|
||||
return Err(Error::NonPositiveMultiplier);
|
||||
}
|
||||
if af_start <= 0.0 || af_step <= 0.0 || af_max <= 0.0 {
|
||||
return Err(Error::NonPositiveMultiplier);
|
||||
}
|
||||
if af_start > af_max {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "af_start must be <= af_max",
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
af_start,
|
||||
af_step,
|
||||
af_max,
|
||||
initialised: false,
|
||||
prev_high: 0.0,
|
||||
prev_low: 0.0,
|
||||
trend: Trend::Up,
|
||||
sar: 0.0,
|
||||
ep: 0.0,
|
||||
af: af_start,
|
||||
})
|
||||
}
|
||||
|
||||
/// Wilder's defaults: `(0.02, 0.02, 0.20)`.
|
||||
pub fn classic() -> Self {
|
||||
Self::new(0.02, 0.02, 0.20).expect("classic PSAR params are valid")
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Psar {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
if !self.initialised {
|
||||
// Seed: the first emitted SAR comes on the second candle. Initial trend
|
||||
// is chosen by whether the second close is above or below the first.
|
||||
self.prev_high = candle.high;
|
||||
self.prev_low = candle.low;
|
||||
self.sar = candle.low;
|
||||
self.ep = candle.high;
|
||||
self.trend = Trend::Up;
|
||||
self.af = self.af_start;
|
||||
self.initialised = true;
|
||||
return None;
|
||||
}
|
||||
|
||||
// Predicted SAR for this period (before clamping to prior two extremes).
|
||||
let mut new_sar = self.sar + self.af * (self.ep - self.sar);
|
||||
|
||||
// Wilder rule: SAR cannot penetrate today's or yesterday's range.
|
||||
let prev_h = self.prev_high;
|
||||
let prev_l = self.prev_low;
|
||||
new_sar = match self.trend {
|
||||
Trend::Up => new_sar.min(prev_l).min(candle.low),
|
||||
Trend::Down => new_sar.max(prev_h).max(candle.high),
|
||||
};
|
||||
|
||||
let mut output_sar = new_sar;
|
||||
|
||||
// Check for trend reversal.
|
||||
let reversed = match self.trend {
|
||||
Trend::Up => candle.low <= new_sar,
|
||||
Trend::Down => candle.high >= new_sar,
|
||||
};
|
||||
|
||||
if reversed {
|
||||
// Flip trend, reset AF and EP, place SAR at prior EP.
|
||||
output_sar = self.ep;
|
||||
self.trend = match self.trend {
|
||||
Trend::Up => Trend::Down,
|
||||
Trend::Down => Trend::Up,
|
||||
};
|
||||
self.ep = match self.trend {
|
||||
Trend::Up => candle.high,
|
||||
Trend::Down => candle.low,
|
||||
};
|
||||
self.af = self.af_start;
|
||||
} else {
|
||||
// Update EP and AF if a new extreme has been reached.
|
||||
match self.trend {
|
||||
Trend::Up => {
|
||||
if candle.high > self.ep {
|
||||
self.ep = candle.high;
|
||||
self.af = (self.af + self.af_step).min(self.af_max);
|
||||
}
|
||||
}
|
||||
Trend::Down => {
|
||||
if candle.low < self.ep {
|
||||
self.ep = candle.low;
|
||||
self.af = (self.af + self.af_step).min(self.af_max);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.sar = output_sar;
|
||||
self.prev_high = candle.high;
|
||||
self.prev_low = candle.low;
|
||||
Some(output_sar)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.initialised = false;
|
||||
self.af = self.af_start;
|
||||
self.sar = 0.0;
|
||||
self.ep = 0.0;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
2
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.initialised
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"PSAR"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_candle_returns_none() {
|
||||
let mut psar = Psar::classic();
|
||||
assert_eq!(psar.update(c(11.0, 9.0, 10.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_sar_below_lows() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.map(|i| {
|
||||
let base = 100.0 + f64::from(i);
|
||||
c(base + 0.5, base - 0.5, base)
|
||||
})
|
||||
.collect();
|
||||
let mut psar = Psar::classic();
|
||||
for (i, sar) in psar.batch(&candles).into_iter().enumerate() {
|
||||
if let Some(s) = sar {
|
||||
assert!(
|
||||
s <= candles[i].low + 1e-9,
|
||||
"SAR {s} should be <= low {} at i={i}",
|
||||
candles[i].low
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_downtrend_sar_above_highs() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.rev()
|
||||
.map(|i| {
|
||||
let base = 100.0 + f64::from(i);
|
||||
c(base + 0.5, base - 0.5, base)
|
||||
})
|
||||
.collect();
|
||||
let mut psar = Psar::classic();
|
||||
let outs = psar.batch(&candles);
|
||||
// After the trend establishes downward, SAR should sit above highs.
|
||||
for (i, sar) in outs.into_iter().enumerate().skip(5) {
|
||||
if let Some(s) = sar {
|
||||
assert!(s >= candles[i].high - 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..60)
|
||||
.map(|i| {
|
||||
let m = 100.0 + (f64::from(i) * 0.3).sin() * 8.0;
|
||||
c(m + 1.0, m - 1.0, m)
|
||||
})
|
||||
.collect();
|
||||
let mut a = Psar::classic();
|
||||
let mut b = Psar::classic();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_params() {
|
||||
assert!(Psar::new(0.0, 0.02, 0.20).is_err());
|
||||
assert!(Psar::new(0.02, 0.0, 0.20).is_err());
|
||||
assert!(Psar::new(0.30, 0.02, 0.20).is_err());
|
||||
assert!(Psar::new(f64::NAN, 0.02, 0.20).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Rate of Change (ROC).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Rate of Change as a percentage: `(close - close[period]) / close[period] * 100`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Roc {
|
||||
period: usize,
|
||||
window: VecDeque<f64>,
|
||||
}
|
||||
|
||||
impl Roc {
|
||||
/// # 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 + 1),
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Roc {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if self.window.len() == self.period + 1 {
|
||||
self.window.pop_front();
|
||||
}
|
||||
self.window.push_back(input);
|
||||
if self.window.len() < self.period + 1 {
|
||||
return None;
|
||||
}
|
||||
let prev = *self.window.front().expect("non-empty");
|
||||
if prev == 0.0 {
|
||||
return Some(0.0);
|
||||
}
|
||||
Some((input - prev) / prev * 100.0)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period + 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.window.len() == self.period + 1
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"ROC"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
let mut roc = Roc::new(5).unwrap();
|
||||
let out = roc.batch(&[10.0_f64; 20]);
|
||||
for v in out.iter().skip(5).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_value() {
|
||||
// ROC(3) where prev = 100, now = 110 -> 10%
|
||||
let mut roc = Roc::new(3).unwrap();
|
||||
let out = roc.batch(&[100.0, 105.0, 108.0, 110.0]);
|
||||
assert_relative_eq!(out[3].unwrap(), 10.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=30).map(|i| f64::from(i) * 2.0).collect();
|
||||
let mut a = Roc::new(5).unwrap();
|
||||
let mut b = Roc::new(5).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut roc = Roc::new(5).unwrap();
|
||||
roc.batch(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
|
||||
assert!(roc.is_ready());
|
||||
roc.reset();
|
||||
assert!(!roc.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(Roc::new(0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Relative Strength Index using Wilder's smoothing.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Relative Strength Index (Wilder, 1978).
|
||||
///
|
||||
/// Uses Wilder's smoothing (an EMA with `alpha = 1 / period`). The first output
|
||||
/// is produced after `period + 1` inputs: the seed averages the first `period`
|
||||
/// gains and losses, and the first emitted RSI corresponds to the input at
|
||||
/// index `period`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Rsi {
|
||||
period: usize,
|
||||
prev_close: Option<f64>,
|
||||
// Wilder seeds with the simple average of the first `period` gains/losses,
|
||||
// then transitions to recursive smoothing.
|
||||
seed_buf_gains: Vec<f64>,
|
||||
seed_buf_losses: Vec<f64>,
|
||||
avg_gain: Option<f64>,
|
||||
avg_loss: Option<f64>,
|
||||
last_value: Option<f64>,
|
||||
}
|
||||
|
||||
impl Rsi {
|
||||
/// Construct an RSI with the given Wilder 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,
|
||||
prev_close: None,
|
||||
seed_buf_gains: Vec::with_capacity(period),
|
||||
seed_buf_losses: Vec::with_capacity(period),
|
||||
avg_gain: None,
|
||||
avg_loss: None,
|
||||
last_value: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.last_value
|
||||
}
|
||||
|
||||
fn rsi_from_avgs(avg_gain: f64, avg_loss: f64) -> f64 {
|
||||
if avg_loss == 0.0 {
|
||||
if avg_gain == 0.0 {
|
||||
// No movement at all -> RSI undefined; standard convention returns 50.
|
||||
50.0
|
||||
} else {
|
||||
100.0
|
||||
}
|
||||
} else {
|
||||
let rs = avg_gain / avg_loss;
|
||||
100.0 - 100.0 / (1.0 + rs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Rsi {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
return self.last_value;
|
||||
}
|
||||
|
||||
let Some(prev) = self.prev_close else {
|
||||
self.prev_close = Some(input);
|
||||
return None;
|
||||
};
|
||||
self.prev_close = Some(input);
|
||||
|
||||
let diff = input - prev;
|
||||
let gain = if diff > 0.0 { diff } else { 0.0 };
|
||||
let loss = if diff < 0.0 { -diff } else { 0.0 };
|
||||
|
||||
if let (Some(ag), Some(al)) = (self.avg_gain, self.avg_loss) {
|
||||
let n = self.period as f64;
|
||||
let new_ag = (ag * (n - 1.0) + gain) / n;
|
||||
let new_al = (al * (n - 1.0) + loss) / n;
|
||||
self.avg_gain = Some(new_ag);
|
||||
self.avg_loss = Some(new_al);
|
||||
let v = Self::rsi_from_avgs(new_ag, new_al);
|
||||
self.last_value = Some(v);
|
||||
return Some(v);
|
||||
}
|
||||
|
||||
self.seed_buf_gains.push(gain);
|
||||
self.seed_buf_losses.push(loss);
|
||||
if self.seed_buf_gains.len() == self.period {
|
||||
let ag = self.seed_buf_gains.iter().sum::<f64>() / self.period as f64;
|
||||
let al = self.seed_buf_losses.iter().sum::<f64>() / self.period as f64;
|
||||
self.avg_gain = Some(ag);
|
||||
self.avg_loss = Some(al);
|
||||
let v = Self::rsi_from_avgs(ag, al);
|
||||
self.last_value = Some(v);
|
||||
return Some(v);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev_close = None;
|
||||
self.seed_buf_gains.clear();
|
||||
self.seed_buf_losses.clear();
|
||||
self.avg_gain = None;
|
||||
self.avg_loss = None;
|
||||
self.last_value = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period + 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.last_value.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"RSI"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Rsi::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_period_is_period_plus_one() {
|
||||
let rsi = Rsi::new(14).unwrap();
|
||||
assert_eq!(rsi.warmup_period(), 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_at_index_period() {
|
||||
// RSI(14) needs 14 diffs => 15 inputs before first value.
|
||||
let prices: Vec<f64> = (1..=20).map(f64::from).collect();
|
||||
let mut rsi = Rsi::new(14).unwrap();
|
||||
let out = rsi.batch(&prices);
|
||||
// indices 0..14 -> None, index 14 -> first Some
|
||||
for x in &out[..14] {
|
||||
assert!(x.is_none());
|
||||
}
|
||||
assert!(out[14].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_yields_rsi_100() {
|
||||
let prices: Vec<f64> = (1..=20).map(f64::from).collect();
|
||||
let mut rsi = Rsi::new(14).unwrap();
|
||||
let out = rsi.batch(&prices);
|
||||
// All diffs are positive => avg_loss == 0 => RSI == 100
|
||||
for v in out.iter().filter_map(|x| x.as_ref()) {
|
||||
assert_relative_eq!(*v, 100.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_downtrend_yields_rsi_0() {
|
||||
let prices: Vec<f64> = (1..=20).rev().map(f64::from).collect();
|
||||
let mut rsi = Rsi::new(14).unwrap();
|
||||
let out = rsi.batch(&prices);
|
||||
for v in out.iter().filter_map(|x| x.as_ref()) {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_series_yields_rsi_50() {
|
||||
let prices = [10.0_f64; 30];
|
||||
let mut rsi = Rsi::new(14).unwrap();
|
||||
let out = rsi.batch(&prices);
|
||||
for v in out.iter().filter_map(|x| x.as_ref()) {
|
||||
assert_relative_eq!(*v, 50.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_wilder_textbook_values() {
|
||||
// Wilder's original example from "New Concepts in Technical Trading Systems",
|
||||
// 14-period RSI. We compute the first value at index 14 and compare to the
|
||||
// value Wilder publishes (~70.46).
|
||||
// Source: classic textbook table, reproduced in many references (e.g. Investopedia).
|
||||
let prices = [
|
||||
44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.10, 45.42, 45.84, 46.08, 45.89, 46.03,
|
||||
45.61, 46.28, 46.28,
|
||||
];
|
||||
let mut rsi = Rsi::new(14).unwrap();
|
||||
let out = rsi.batch(&prices);
|
||||
let first = out[14].expect("first RSI emitted at index period");
|
||||
assert_relative_eq!(first, 70.464, epsilon = 0.05);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rsi_stays_in_0_100_range() {
|
||||
let prices: Vec<f64> = (0..200)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.7).sin() * 10.0)
|
||||
.collect();
|
||||
let mut rsi = Rsi::new(14).unwrap();
|
||||
for x in rsi.batch(&prices).into_iter().flatten() {
|
||||
assert!((0.0..=100.0).contains(&x), "RSI out of range: {x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut rsi = Rsi::new(5).unwrap();
|
||||
rsi.batch(&[1.0, 2.0, 3.0, 2.0, 4.0, 5.0, 6.0]);
|
||||
assert!(rsi.is_ready());
|
||||
rsi.reset();
|
||||
assert!(!rsi.is_ready());
|
||||
assert_eq!(rsi.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=40)
|
||||
.map(|i| (f64::from(i) * 0.3).sin() * 5.0 + f64::from(i))
|
||||
.collect();
|
||||
let mut a = Rsi::new(7).unwrap();
|
||||
let mut b = Rsi::new(7).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Simple Moving Average.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Simple Moving Average over a fixed window.
|
||||
///
|
||||
/// Maintains a rolling sum so each update is O(1). Output equals
|
||||
/// `sum(last `period` prices) / period` once the window is full; `None` before.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Sma {
|
||||
period: usize,
|
||||
window: VecDeque<f64>,
|
||||
sum: f64,
|
||||
}
|
||||
|
||||
impl Sma {
|
||||
/// Construct a new SMA with the given window length.
|
||||
///
|
||||
/// # 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,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured window length.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub fn value(&self) -> Option<f64> {
|
||||
if self.window.len() == self.period {
|
||||
Some(self.sum / self.period as f64)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Sma {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
return self.value();
|
||||
}
|
||||
if self.window.len() == self.period {
|
||||
// Drop the oldest from the sum to keep numerical drift bounded by recomputing
|
||||
// the sum after each pop; a single subtract works in O(1) and is acceptable
|
||||
// here because we use f64 throughout.
|
||||
let old = self.window.pop_front().expect("window non-empty");
|
||||
self.sum -= old;
|
||||
}
|
||||
self.window.push_back(input);
|
||||
self.sum += input;
|
||||
self.value()
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.sum = 0.0;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.window.len() == self.period
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"SMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Sma::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_returns_none() {
|
||||
let mut sma = Sma::new(3).unwrap();
|
||||
assert_eq!(sma.update(1.0), None);
|
||||
assert_eq!(sma.update(2.0), None);
|
||||
assert_eq!(sma.update(3.0), Some(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rolls_window_after_full() {
|
||||
let mut sma = Sma::new(3).unwrap();
|
||||
let out: Vec<_> = [1.0, 2.0, 3.0, 4.0, 5.0]
|
||||
.iter()
|
||||
.map(|p| sma.update(*p))
|
||||
.collect();
|
||||
assert_eq!(out, vec![None, None, Some(2.0), Some(3.0), Some(4.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn period_one_is_pass_through() {
|
||||
let mut sma = Sma::new(1).unwrap();
|
||||
assert_eq!(sma.update(5.0), Some(5.0));
|
||||
assert_eq!(sma.update(10.0), Some(10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input_but_keeps_state() {
|
||||
let mut sma = Sma::new(3).unwrap();
|
||||
sma.update(1.0);
|
||||
sma.update(2.0);
|
||||
sma.update(3.0);
|
||||
assert_eq!(sma.update(f64::NAN), Some(2.0));
|
||||
assert_eq!(sma.update(f64::INFINITY), Some(2.0));
|
||||
// Non-finite inputs were not pushed; window still holds 1,2,3.
|
||||
assert_eq!(sma.update(6.0), Some((2.0 + 3.0 + 6.0) / 3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut sma = Sma::new(3).unwrap();
|
||||
sma.batch(&[1.0, 2.0, 3.0]);
|
||||
assert!(sma.is_ready());
|
||||
sma.reset();
|
||||
assert!(!sma.is_ready());
|
||||
assert_eq!(sma.update(10.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=20).map(f64::from).collect();
|
||||
let mut a = Sma::new(5).unwrap();
|
||||
let batch = a.batch(&prices);
|
||||
let mut b = Sma::new(5).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_reference_values() {
|
||||
// SMA(3) of [2, 4, 6, 8, 10] -> [_, _, 4, 6, 8]
|
||||
let mut sma = Sma::new(3).unwrap();
|
||||
let out = sma.batch(&[2.0, 4.0, 6.0, 8.0, 10.0]);
|
||||
assert_eq!(out[2], Some(4.0));
|
||||
assert_eq!(out[3], Some(6.0));
|
||||
assert_eq!(out[4], Some(8.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_constant_sma() {
|
||||
let mut sma = Sma::new(5).unwrap();
|
||||
let v = sma.batch(&[7.0; 10]);
|
||||
for x in v.iter().skip(4) {
|
||||
assert_relative_eq!(x.unwrap(), 7.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#![proptest_config(proptest::test_runner::Config::with_cases(64))]
|
||||
#[test]
|
||||
fn sma_matches_naive_definition(
|
||||
period in 1usize..20,
|
||||
prices in proptest::collection::vec(-1000.0_f64..1000.0, 0..200),
|
||||
) {
|
||||
let mut sma = Sma::new(period).unwrap();
|
||||
let stream: Vec<_> = prices.iter().map(|p| sma.update(*p)).collect();
|
||||
for (i, got) in stream.iter().enumerate() {
|
||||
if i + 1 < period {
|
||||
proptest::prop_assert!(got.is_none());
|
||||
} else {
|
||||
let window = &prices[i + 1 - period..=i];
|
||||
let expected = window.iter().sum::<f64>() / period as f64;
|
||||
let actual = got.expect("ready");
|
||||
proptest::prop_assert!(
|
||||
(actual - expected).abs() < 1e-9,
|
||||
"i={i} actual={actual} expected={expected}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
//! Stochastic Oscillator (%K and %D).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::indicators::sma::Sma;
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Stochastic Oscillator output.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct StochasticOutput {
|
||||
/// Raw %K: `100 * (close - LL) / (HH - LL)` over the lookback.
|
||||
pub k: f64,
|
||||
/// %D: SMA of %K over the smoothing period.
|
||||
pub d: f64,
|
||||
}
|
||||
|
||||
/// Fast Stochastic Oscillator.
|
||||
///
|
||||
/// Maintains rolling highest-high and lowest-low over the lookback period via a
|
||||
/// monotonic deque, giving O(1) amortized updates. %D is an SMA of the %K series.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Stochastic {
|
||||
k_period: usize,
|
||||
d_period: usize,
|
||||
candles: VecDeque<Candle>,
|
||||
// Monotonic deques over candle indices in the rolling window.
|
||||
hh_idx: VecDeque<usize>, // indices of candidates for highest high (front = current max)
|
||||
ll_idx: VecDeque<usize>, // indices of candidates for lowest low (front = current min)
|
||||
// Absolute count of candles ever ingested. Used so monotonic-deque indices stay unique.
|
||||
count: usize,
|
||||
d_sma: Sma,
|
||||
last_k: Option<f64>,
|
||||
}
|
||||
|
||||
impl Stochastic {
|
||||
/// Construct a stochastic with %K lookback and %D smoothing periods.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if either period is zero.
|
||||
pub fn new(k_period: usize, d_period: usize) -> Result<Self> {
|
||||
if k_period == 0 || d_period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
k_period,
|
||||
d_period,
|
||||
candles: VecDeque::with_capacity(k_period),
|
||||
hh_idx: VecDeque::with_capacity(k_period),
|
||||
ll_idx: VecDeque::with_capacity(k_period),
|
||||
count: 0,
|
||||
d_sma: Sma::new(d_period)?,
|
||||
last_k: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Classic fast stochastic: `%K = 14`, `%D = 3`.
|
||||
pub fn classic() -> Self {
|
||||
Self::new(14, 3).expect("classic stochastic periods are valid")
|
||||
}
|
||||
|
||||
/// Configured `(k_period, d_period)`.
|
||||
pub const fn periods(&self) -> (usize, usize) {
|
||||
(self.k_period, self.d_period)
|
||||
}
|
||||
|
||||
fn push_window(&mut self, candle: Candle) {
|
||||
let idx = self.count;
|
||||
self.count += 1;
|
||||
// Drop deque entries that are outside the window.
|
||||
let oldest_keep_idx = idx.saturating_sub(self.k_period - 1);
|
||||
while let Some(&front) = self.hh_idx.front() {
|
||||
if front < oldest_keep_idx {
|
||||
self.hh_idx.pop_front();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
while let Some(&front) = self.ll_idx.front() {
|
||||
if front < oldest_keep_idx {
|
||||
self.ll_idx.pop_front();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Maintain monotonic-decreasing deque for highs.
|
||||
while let Some(&back) = self.hh_idx.back() {
|
||||
let back_off = back - idx.saturating_sub(self.candles.len());
|
||||
if self.candles[back_off].high <= candle.high {
|
||||
self.hh_idx.pop_back();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.hh_idx.push_back(idx);
|
||||
// Maintain monotonic-increasing deque for lows.
|
||||
while let Some(&back) = self.ll_idx.back() {
|
||||
let back_off = back - idx.saturating_sub(self.candles.len());
|
||||
if self.candles[back_off].low >= candle.low {
|
||||
self.ll_idx.pop_back();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.ll_idx.push_back(idx);
|
||||
|
||||
if self.candles.len() == self.k_period {
|
||||
self.candles.pop_front();
|
||||
}
|
||||
self.candles.push_back(candle);
|
||||
}
|
||||
|
||||
fn current_extremes(&self) -> (f64, f64) {
|
||||
let base = self.count - self.candles.len();
|
||||
let hi = self.candles[self.hh_idx[0] - base].high;
|
||||
let lo = self.candles[self.ll_idx[0] - base].low;
|
||||
(hi, lo)
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Stochastic {
|
||||
type Input = Candle;
|
||||
type Output = StochasticOutput;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<StochasticOutput> {
|
||||
self.push_window(candle);
|
||||
if self.candles.len() < self.k_period {
|
||||
return None;
|
||||
}
|
||||
let (hh, ll) = self.current_extremes();
|
||||
let range = hh - ll;
|
||||
let k = if range == 0.0 {
|
||||
// Flat range; convention: 50 (neutral, like RSI on flat input).
|
||||
50.0
|
||||
} else {
|
||||
100.0 * (candle.close - ll) / range
|
||||
};
|
||||
self.last_k = Some(k);
|
||||
let d = self.d_sma.update(k)?;
|
||||
Some(StochasticOutput { k, d })
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.candles.clear();
|
||||
self.hh_idx.clear();
|
||||
self.ll_idx.clear();
|
||||
self.count = 0;
|
||||
self.d_sma.reset();
|
||||
self.last_k = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.k_period + self.d_period - 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.d_sma.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"Stochastic"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
/// Naive %K computation for cross-checks.
|
||||
fn naive_k(candles: &[Candle], k_period: usize) -> Vec<Option<f64>> {
|
||||
candles
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, _)| {
|
||||
if i + 1 < k_period {
|
||||
None
|
||||
} else {
|
||||
let w = &candles[i + 1 - k_period..=i];
|
||||
let hh = w.iter().map(|x| x.high).fold(f64::NEG_INFINITY, f64::max);
|
||||
let ll = w.iter().map(|x| x.low).fold(f64::INFINITY, f64::min);
|
||||
let range = hh - ll;
|
||||
let cl = candles[i].close;
|
||||
Some(if range == 0.0 {
|
||||
50.0
|
||||
} else {
|
||||
100.0 * (cl - ll) / range
|
||||
})
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_periods() {
|
||||
assert!(matches!(Stochastic::new(0, 3), Err(Error::PeriodZero)));
|
||||
assert!(matches!(Stochastic::new(14, 0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_at_high_yields_k_100() {
|
||||
let candles = vec![
|
||||
c(10.0, 8.0, 9.0),
|
||||
c(11.0, 9.0, 10.0),
|
||||
c(12.0, 10.0, 12.0), // close == high == HH
|
||||
];
|
||||
let mut s = Stochastic::new(3, 1).unwrap();
|
||||
let out = s.batch(&candles);
|
||||
assert_relative_eq!(out[2].unwrap().k, 100.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_at_low_yields_k_0() {
|
||||
let candles = vec![
|
||||
c(10.0, 8.0, 9.0),
|
||||
c(11.0, 9.0, 10.0),
|
||||
c(12.0, 8.0, 8.0), // close == LL
|
||||
];
|
||||
let mut s = Stochastic::new(3, 1).unwrap();
|
||||
let out = s.batch(&candles);
|
||||
assert_relative_eq!(out[2].unwrap().k, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_range_yields_k_50() {
|
||||
let candles: Vec<Candle> = (0..20).map(|_| c(10.0, 10.0, 10.0)).collect();
|
||||
let mut s = Stochastic::new(14, 3).unwrap();
|
||||
for o in s.batch(&candles).into_iter().flatten() {
|
||||
assert_relative_eq!(o.k, 50.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(o.d, 50.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn k_matches_naive() {
|
||||
let candles: Vec<Candle> = (0..60)
|
||||
.map(|i| {
|
||||
let mid = 50.0 + (f64::from(i) * 0.4).sin() * 10.0;
|
||||
c(mid + 2.0, mid - 2.0, mid + (f64::from(i) * 0.7).cos())
|
||||
})
|
||||
.collect();
|
||||
let mut s = Stochastic::new(14, 3).unwrap();
|
||||
let out = s.batch(&candles);
|
||||
let naive = naive_k(&candles, 14);
|
||||
for (i, got) in out.iter().enumerate() {
|
||||
if let Some(o) = got {
|
||||
let n = naive[i].expect("naive ready");
|
||||
assert_relative_eq!(o.k, n, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d_is_sma_of_k() {
|
||||
let candles: Vec<Candle> = (0..60)
|
||||
.map(|i| {
|
||||
let mid = 50.0 + f64::from(i).sin() * 5.0;
|
||||
c(mid + 1.5, mid - 1.5, mid)
|
||||
})
|
||||
.collect();
|
||||
let mut s = Stochastic::new(14, 3).unwrap();
|
||||
let out = s.batch(&candles);
|
||||
// The naive %K series gives us the ground-truth values that %D should average.
|
||||
let naive_ks = naive_k(&candles, 14);
|
||||
// The first emitted %D corresponds to the SMA of the first three valid %K values
|
||||
// (i.e. those at indices 13, 14, 15). At that point %D becomes ready, and the
|
||||
// first `Some(_)` output appears at index 15.
|
||||
let first_emit_idx = out
|
||||
.iter()
|
||||
.position(Option::is_some)
|
||||
.expect("d eventually emits");
|
||||
let first_d = out[first_emit_idx].unwrap().d;
|
||||
let k_window = &naive_ks[first_emit_idx - 2..=first_emit_idx];
|
||||
let want = k_window
|
||||
.iter()
|
||||
.map(|v| v.expect("naive K ready inside window"))
|
||||
.sum::<f64>()
|
||||
/ 3.0;
|
||||
assert_relative_eq!(first_d, want, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..50)
|
||||
.map(|i| {
|
||||
let mid = 100.0 + f64::from(i) * 0.5;
|
||||
c(mid + 2.0, mid - 2.0, mid)
|
||||
})
|
||||
.collect();
|
||||
let mut a = Stochastic::new(14, 3).unwrap();
|
||||
let mut b = Stochastic::new(14, 3).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut s = Stochastic::new(5, 3).unwrap();
|
||||
let candles: Vec<Candle> = (0..10).map(|i| c(10.0 + f64::from(i), 5.0, 7.0)).collect();
|
||||
s.batch(&candles);
|
||||
assert!(s.is_ready());
|
||||
s.reset();
|
||||
assert!(!s.is_ready());
|
||||
assert_eq!(s.update(candles[0]), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Triple Exponential Moving Average (TEMA).
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::indicators::ema::Ema;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Triple Exponential Moving Average: `3 * EMA1 - 3 * EMA2 + EMA3`,
|
||||
/// where `EMA2 = EMA(EMA1)` and `EMA3 = EMA(EMA2)`.
|
||||
///
|
||||
/// Reduces lag further than DEMA at the cost of more responsiveness to noise.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Tema {
|
||||
ema1: Ema,
|
||||
ema2: Ema,
|
||||
ema3: Ema,
|
||||
period: usize,
|
||||
}
|
||||
|
||||
impl Tema {
|
||||
/// # Errors
|
||||
/// Returns [`crate::Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
Ok(Self {
|
||||
ema1: Ema::new(period)?,
|
||||
ema2: Ema::new(period)?,
|
||||
ema3: Ema::new(period)?,
|
||||
period,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Tema {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
let e1 = self.ema1.update(input)?;
|
||||
let e2 = self.ema2.update(e1)?;
|
||||
let e3 = self.ema3.update(e2)?;
|
||||
Some(3.0 * e1 - 3.0 * e2 + e3)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.ema1.reset();
|
||||
self.ema2.reset();
|
||||
self.ema3.reset();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
3 * self.period - 2
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.ema3.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"TEMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_constant_tema() {
|
||||
let mut tema = Tema::new(5).unwrap();
|
||||
let out = tema.batch(&[42.0_f64; 80]);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert_relative_eq!(*last, 42.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=80)
|
||||
.map(|i| (f64::from(i) * 0.3).sin() * 10.0)
|
||||
.collect();
|
||||
let mut a = Tema::new(5).unwrap();
|
||||
let mut b = Tema::new(5).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut tema = Tema::new(5).unwrap();
|
||||
tema.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(tema.is_ready());
|
||||
tema.reset();
|
||||
assert!(!tema.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(Tema::new(0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! TRIX: triple-smoothed EMA percent rate of change.
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::indicators::ema::Ema;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// TRIX: the 1-period percent rate of change of a triple-smoothed EMA.
|
||||
///
|
||||
/// `TRIX = 100 * (TR_t - TR_{t-1}) / TR_{t-1}` where
|
||||
/// `TR_t = EMA(EMA(EMA(price)))`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Trix {
|
||||
ema1: Ema,
|
||||
ema2: Ema,
|
||||
ema3: Ema,
|
||||
prev_tr: Option<f64>,
|
||||
period: usize,
|
||||
}
|
||||
|
||||
impl Trix {
|
||||
/// # Errors
|
||||
/// Returns [`crate::Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
Ok(Self {
|
||||
ema1: Ema::new(period)?,
|
||||
ema2: Ema::new(period)?,
|
||||
ema3: Ema::new(period)?,
|
||||
prev_tr: None,
|
||||
period,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Trix {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
let e1 = self.ema1.update(input)?;
|
||||
let e2 = self.ema2.update(e1)?;
|
||||
let e3 = self.ema3.update(e2)?;
|
||||
match self.prev_tr {
|
||||
Some(prev) if prev != 0.0 => {
|
||||
let trix = 100.0 * (e3 - prev) / prev;
|
||||
self.prev_tr = Some(e3);
|
||||
Some(trix)
|
||||
}
|
||||
Some(_) => {
|
||||
self.prev_tr = Some(e3);
|
||||
Some(0.0)
|
||||
}
|
||||
None => {
|
||||
self.prev_tr = Some(e3);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.ema1.reset();
|
||||
self.ema2.reset();
|
||||
self.ema3.reset();
|
||||
self.prev_tr = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// Triple EMA seeds at 3*period-2; plus one extra for the rate of change.
|
||||
3 * self.period - 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.prev_tr.is_some() && self.ema3.is_ready()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"TRIX"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero_trix() {
|
||||
let mut trix = Trix::new(5).unwrap();
|
||||
let out = trix.batch(&[100.0_f64; 80]);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert_relative_eq!(*last, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rising_series_eventually_positive_trix() {
|
||||
let prices: Vec<f64> = (1..=200).map(f64::from).collect();
|
||||
let mut trix = Trix::new(5).unwrap();
|
||||
let last = trix.batch(&prices).into_iter().flatten().last().unwrap();
|
||||
assert!(last > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=80).map(|i| f64::from(i) * 1.3).collect();
|
||||
let mut a = Trix::new(7).unwrap();
|
||||
let mut b = Trix::new(7).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut trix = Trix::new(5).unwrap();
|
||||
trix.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(trix.is_ready());
|
||||
trix.reset();
|
||||
assert!(!trix.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(Trix::new(0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! Volume-Weighted Average Price (VWAP).
|
||||
//!
|
||||
//! Two variants are offered: a cumulative `Vwap` that runs forever (the
|
||||
//! intraday convention), and a rolling-window `RollingVwap` for streaming bots
|
||||
//! that need a finite-memory price benchmark.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Cumulative session VWAP. Call [`Indicator::reset`] at the start of each
|
||||
/// session (e.g. trading-day boundary) to restart the accumulation.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Vwap {
|
||||
sum_pv: f64,
|
||||
sum_v: f64,
|
||||
has_emitted: bool,
|
||||
}
|
||||
|
||||
impl Vwap {
|
||||
/// Construct a fresh cumulative VWAP.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
sum_pv: 0.0,
|
||||
sum_v: 0.0,
|
||||
has_emitted: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Current VWAP if at least one candle with non-zero volume has been observed.
|
||||
pub fn value(&self) -> Option<f64> {
|
||||
if self.sum_v == 0.0 {
|
||||
None
|
||||
} else {
|
||||
Some(self.sum_pv / self.sum_v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Vwap {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
let tp = candle.typical_price();
|
||||
self.sum_pv += tp * candle.volume;
|
||||
self.sum_v += candle.volume;
|
||||
if self.sum_v == 0.0 {
|
||||
return None;
|
||||
}
|
||||
self.has_emitted = true;
|
||||
Some(self.sum_pv / self.sum_v)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.sum_pv = 0.0;
|
||||
self.sum_v = 0.0;
|
||||
self.has_emitted = false;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.has_emitted
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"VWAP"
|
||||
}
|
||||
}
|
||||
|
||||
/// Rolling-window VWAP: a finite-memory variant for bots that don't want
|
||||
/// unbounded accumulation.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RollingVwap {
|
||||
period: usize,
|
||||
window: VecDeque<(f64, f64)>, // (typical_price * volume, volume)
|
||||
sum_pv: f64,
|
||||
sum_v: f64,
|
||||
}
|
||||
|
||||
impl RollingVwap {
|
||||
/// # 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,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured rolling window length.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for RollingVwap {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
let pv = candle.typical_price() * candle.volume;
|
||||
if self.window.len() == self.period {
|
||||
let (old_pv, old_v) = self.window.pop_front().expect("non-empty");
|
||||
self.sum_pv -= old_pv;
|
||||
self.sum_v -= old_v;
|
||||
}
|
||||
self.window.push_back((pv, candle.volume));
|
||||
self.sum_pv += pv;
|
||||
self.sum_v += candle.volume;
|
||||
if self.window.len() < self.period || self.sum_v == 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some(self.sum_pv / self.sum_v)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.sum_pv = 0.0;
|
||||
self.sum_v = 0.0;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.window.len() == self.period && self.sum_v > 0.0
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"RollingVWAP"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(price: f64, volume: f64) -> Candle {
|
||||
Candle::new(price, price, price, price, volume, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cumulative_vwap_equal_volumes_equals_mean() {
|
||||
let candles = vec![c(10.0, 1.0), c(20.0, 1.0), c(30.0, 1.0)];
|
||||
let mut v = Vwap::new();
|
||||
let out = v.batch(&candles);
|
||||
assert_relative_eq!(out[2].unwrap(), 20.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cumulative_vwap_weighted() {
|
||||
// Two candles: 10@1 and 20@3 -> (10*1 + 20*3) / (1+3) = 70/4 = 17.5
|
||||
let candles = vec![c(10.0, 1.0), c(20.0, 3.0)];
|
||||
let mut v = Vwap::new();
|
||||
let out = v.batch(&candles);
|
||||
assert_relative_eq!(out[1].unwrap(), 17.5, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rolling_vwap_window_slides() {
|
||||
let candles = vec![c(10.0, 1.0), c(20.0, 1.0), c(30.0, 1.0), c(40.0, 1.0)];
|
||||
let mut v = RollingVwap::new(3).unwrap();
|
||||
let out = v.batch(&candles);
|
||||
assert!(out[1].is_none());
|
||||
// index 2 -> (10+20+30)/3 = 20
|
||||
assert_relative_eq!(out[2].unwrap(), 20.0, epsilon = 1e-12);
|
||||
// index 3 -> (20+30+40)/3 = 30
|
||||
assert_relative_eq!(out[3].unwrap(), 30.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming_cumulative() {
|
||||
let candles: Vec<Candle> = (1..20).map(|i| c(f64::from(i), 1.0)).collect();
|
||||
let mut a = Vwap::new();
|
||||
let mut b = Vwap::new();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming_rolling() {
|
||||
let candles: Vec<Candle> = (1..30)
|
||||
.map(|i| c(f64::from(i), f64::from(i % 5 + 1)))
|
||||
.collect();
|
||||
let mut a = RollingVwap::new(10).unwrap();
|
||||
let mut b = RollingVwap::new(10).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rolling_rejects_zero_period() {
|
||||
assert!(RollingVwap::new(0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Williams %R.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Williams %R: `-100 * (HH - close) / (HH - LL)` over the lookback window.
|
||||
///
|
||||
/// Values lie in `[-100, 0]` and approximate the mirror image of the fast
|
||||
/// Stochastic %K.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WilliamsR {
|
||||
period: usize,
|
||||
candles: VecDeque<Candle>,
|
||||
}
|
||||
|
||||
impl WilliamsR {
|
||||
/// # Errors
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
candles: VecDeque::with_capacity(period),
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for WilliamsR {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
if self.candles.len() == self.period {
|
||||
self.candles.pop_front();
|
||||
}
|
||||
self.candles.push_back(candle);
|
||||
if self.candles.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let hh = self
|
||||
.candles
|
||||
.iter()
|
||||
.map(|c| c.high)
|
||||
.fold(f64::NEG_INFINITY, f64::max);
|
||||
let ll = self
|
||||
.candles
|
||||
.iter()
|
||||
.map(|c| c.low)
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
let range = hh - ll;
|
||||
if range == 0.0 {
|
||||
return Some(-50.0);
|
||||
}
|
||||
Some(-100.0 * (hh - candle.close) / range)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.candles.clear();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.candles.len() == self.period
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"WilliamsR"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn c(h: f64, l: f64, cl: f64) -> Candle {
|
||||
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_at_high_yields_zero() {
|
||||
let candles = vec![c(10.0, 8.0, 9.0), c(11.0, 9.0, 10.0), c(12.0, 10.0, 12.0)];
|
||||
let mut w = WilliamsR::new(3).unwrap();
|
||||
let out = w.batch(&candles);
|
||||
assert_relative_eq!(out[2].unwrap(), 0.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_at_low_yields_minus_100() {
|
||||
let candles = vec![c(12.0, 10.0, 11.0), c(11.0, 9.0, 10.0), c(10.0, 8.0, 8.0)];
|
||||
let mut w = WilliamsR::new(3).unwrap();
|
||||
let out = w.batch(&candles);
|
||||
assert_relative_eq!(out[2].unwrap(), -100.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn within_range() {
|
||||
let candles: Vec<Candle> = (0..100)
|
||||
.map(|i| {
|
||||
let m = 50.0 + (f64::from(i) * 0.3).sin() * 5.0;
|
||||
c(m + 1.0, m - 1.0, m)
|
||||
})
|
||||
.collect();
|
||||
let mut w = WilliamsR::new(14).unwrap();
|
||||
for v in w.batch(&candles).into_iter().flatten() {
|
||||
assert!((-100.0..=0.0).contains(&v), "%R out of range: {v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..30)
|
||||
.map(|i| c(f64::from(i) + 2.0, f64::from(i), f64::from(i) + 1.0))
|
||||
.collect();
|
||||
let mut a = WilliamsR::new(5).unwrap();
|
||||
let mut b = WilliamsR::new(5).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_period() {
|
||||
assert!(WilliamsR::new(0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Weighted Moving Average (linear weights).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Weighted Moving Average with linear weights `1, 2, ..., period`.
|
||||
///
|
||||
/// Output is `sum(weight_i * price_i) / sum(weights)`. Maintained incrementally in
|
||||
/// O(1) by keeping the rolling sum of values and the rolling weighted sum.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Wma {
|
||||
period: usize,
|
||||
window: VecDeque<f64>,
|
||||
weight_sum: f64, // sum_i (weight_i * value_i)
|
||||
value_sum: f64, // sum_i (value_i)
|
||||
weights_total: f64,
|
||||
}
|
||||
|
||||
impl Wma {
|
||||
/// Construct a new WMA with the given window length.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
let n = period as f64;
|
||||
let weights_total = n * (n + 1.0) / 2.0;
|
||||
Ok(Self {
|
||||
period,
|
||||
window: VecDeque::with_capacity(period),
|
||||
weight_sum: 0.0,
|
||||
value_sum: 0.0,
|
||||
weights_total,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub fn value(&self) -> Option<f64> {
|
||||
if self.window.len() == self.period {
|
||||
Some(self.weight_sum / self.weights_total)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Wma {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
return self.value();
|
||||
}
|
||||
if self.window.len() < self.period {
|
||||
// Warmup. Just accumulate; compute weight_sum once when the window first
|
||||
// becomes full to avoid having to track changing weights during warmup.
|
||||
self.window.push_back(input);
|
||||
self.value_sum += input;
|
||||
if self.window.len() == self.period {
|
||||
self.weight_sum = self
|
||||
.window
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, v)| (i as f64 + 1.0) * v)
|
||||
.sum();
|
||||
}
|
||||
return self.value();
|
||||
}
|
||||
// Steady state: slide the window. With weights [1, 2, ..., period],
|
||||
// new_weight_sum = old_weight_sum - old_value_sum + period * new_input
|
||||
// because every retained element's weight drops by one and the newcomer
|
||||
// enters at weight = period. Order matters: subtract `value_sum` BEFORE
|
||||
// updating it.
|
||||
let oldest = self.window.pop_front().expect("window non-empty");
|
||||
self.weight_sum = self.weight_sum - self.value_sum + self.period as f64 * input;
|
||||
self.value_sum = self.value_sum - oldest + input;
|
||||
self.window.push_back(input);
|
||||
self.value()
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.weight_sum = 0.0;
|
||||
self.value_sum = 0.0;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.window.len() == self.period
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"WMA"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
/// Reference implementation: explicit weighted average over a window.
|
||||
fn wma_naive(prices: &[f64], period: usize) -> Vec<Option<f64>> {
|
||||
let weights_total = (period as f64) * (period as f64 + 1.0) / 2.0;
|
||||
prices
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, _)| {
|
||||
if i + 1 < period {
|
||||
None
|
||||
} else {
|
||||
let window = &prices[i + 1 - period..=i];
|
||||
let s: f64 = window
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(j, p)| (j as f64 + 1.0) * p)
|
||||
.sum();
|
||||
Some(s / weights_total)
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Wma::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_returns_none() {
|
||||
let mut wma = Wma::new(3).unwrap();
|
||||
assert_eq!(wma.update(1.0), None);
|
||||
assert_eq!(wma.update(2.0), None);
|
||||
// WMA(3) of [1,2,3]: oldest = 1 (weight 1), middle = 2 (weight 2), newest = 3 (weight 3)
|
||||
// -> (1*1 + 2*2 + 3*3) / (1+2+3) = 14/6
|
||||
assert_relative_eq!(wma.update(3.0).unwrap(), 14.0 / 6.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_values_period_4() {
|
||||
// WMA(4) weights 1,2,3,4 (total 10); inputs [1,2,3,4]:
|
||||
// (1*1 + 2*2 + 3*3 + 4*4) / 10 = (1+4+9+16)/10 = 30/10 = 3.0
|
||||
let mut wma = Wma::new(4).unwrap();
|
||||
let v = wma.batch(&[1.0, 2.0, 3.0, 4.0]);
|
||||
assert_relative_eq!(v[3].unwrap(), 3.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_naive_over_random_inputs() {
|
||||
let prices: Vec<f64> = (1..=30).map(|i| f64::from(i) * 1.7 - 5.0).collect();
|
||||
let mut wma = Wma::new(7).unwrap();
|
||||
let got = wma.batch(&prices);
|
||||
let want = wma_naive(&prices, 7);
|
||||
for (g, w) in got.iter().zip(want.iter()) {
|
||||
match (g, w) {
|
||||
(None, None) => {}
|
||||
(Some(a), Some(b)) => assert_relative_eq!(*a, *b, epsilon = 1e-9),
|
||||
_ => panic!("warmup mismatch"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn period_one_is_pass_through() {
|
||||
let mut wma = Wma::new(1).unwrap();
|
||||
assert_relative_eq!(wma.update(5.5).unwrap(), 5.5, epsilon = 1e-12);
|
||||
assert_relative_eq!(wma.update(7.5).unwrap(), 7.5, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut wma = Wma::new(4).unwrap();
|
||||
wma.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
assert!(wma.is_ready());
|
||||
wma.reset();
|
||||
assert!(!wma.is_ready());
|
||||
assert_eq!(wma.update(10.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=20).map(|i| f64::from(i) * 0.5).collect();
|
||||
let mut a = Wma::new(5).unwrap();
|
||||
let mut b = Wma::new(5).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#![proptest_config(proptest::test_runner::Config::with_cases(48))]
|
||||
#[test]
|
||||
fn proptest_matches_naive(
|
||||
period in 1usize..15,
|
||||
prices in proptest::collection::vec(-500.0_f64..500.0, 0..120),
|
||||
) {
|
||||
let mut wma = Wma::new(period).unwrap();
|
||||
let got = wma.batch(&prices);
|
||||
let want = wma_naive(&prices, period);
|
||||
proptest::prop_assert_eq!(got.len(), want.len());
|
||||
for (g, w) in got.iter().zip(want.iter()) {
|
||||
match (g, w) {
|
||||
(None, None) => {}
|
||||
(Some(a), Some(b)) => proptest::prop_assert!(
|
||||
(a - b).abs() < 1e-7,
|
||||
"got={a} want={b}"
|
||||
),
|
||||
_ => proptest::prop_assert!(false, "warmup mismatch"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user