F3: add MOM, CMO, TSI and PMO momentum indicators
Completes the F3 family (Momentum) end to end: - Rust core: mom.rs (raw price-difference momentum), cmo.rs (Chande Momentum Oscillator — unsmoothed gain/loss sum, bounded [-100,100]), tsi.rs (True Strength Index — double-EMA-smoothed momentum ratio), pmo.rs (DecisionPoint Price Momentum Oscillator — doubly-smoothed ROC with the 2/period custom smoothing). Each with a full Indicator impl, runnable doctest and reference-value / saturation / warmup / reset / batch==streaming / non-finite tests. - Python: PyMom / PyCmo / PyTsi / PyPmo PyO3 classes + module registration + .pyi stubs (defaults MOM=10, CMO=14, TSI=(25,13), PMO=(35,20)). - Node: MomNode / CmoNode via the scalar macro, explicit TsiNode and PmoNode; index.d.ts and index.js updated. - WASM: WasmMom / WasmCmo / WasmTsi / WasmPmo via the scalar macro. - Wiki: Indicator-Mom/Cmo/Tsi/Pmo.md plus rows in Indicators-Overview.md and entries in Home.md. cargo fmt + clippy (core/wickra/data/wasm/node) clean; 262 core tests, 25 data tests and 37 doctests green.
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
//! Chande Momentum Oscillator.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Chande Momentum Oscillator — Tushar Chande's bounded momentum gauge.
|
||||
///
|
||||
/// Over the last `period` price *changes* it sums the gains and the losses
|
||||
/// separately and reports:
|
||||
///
|
||||
/// ```text
|
||||
/// CMO = 100 · (Σ gains − Σ losses) / (Σ gains + Σ losses)
|
||||
/// ```
|
||||
///
|
||||
/// The result is bounded in `[−100, 100]`: `+100` is a window of pure gains,
|
||||
/// `−100` a window of pure losses, `0` a perfect balance. Unlike RSI the sums
|
||||
/// are *unsmoothed* — every change in the window carries equal weight — so CMO
|
||||
/// reacts faster and swings wider.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, Cmo};
|
||||
///
|
||||
/// let mut indicator = Cmo::new(14).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert_eq!(last, Some(100.0)); // pure uptrend saturates at +100
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Cmo {
|
||||
period: usize,
|
||||
prev_price: Option<f64>,
|
||||
/// Rolling window of `(gain, loss)` pairs, oldest at the front.
|
||||
window: VecDeque<(f64, f64)>,
|
||||
sum_gain: f64,
|
||||
sum_loss: f64,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
impl Cmo {
|
||||
/// Construct a new CMO with the given period.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
prev_price: None,
|
||||
window: VecDeque::with_capacity(period),
|
||||
sum_gain: 0.0,
|
||||
sum_loss: 0.0,
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Cmo {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
// Non-finite input is ignored; state is left untouched.
|
||||
return self.current;
|
||||
}
|
||||
let Some(prev) = self.prev_price else {
|
||||
self.prev_price = Some(input);
|
||||
return None;
|
||||
};
|
||||
self.prev_price = Some(input);
|
||||
|
||||
let change = input - prev;
|
||||
let gain = change.max(0.0);
|
||||
let loss = (-change).max(0.0);
|
||||
|
||||
if self.window.len() == self.period {
|
||||
let (old_gain, old_loss) = self.window.pop_front().expect("window is non-empty");
|
||||
self.sum_gain -= old_gain;
|
||||
self.sum_loss -= old_loss;
|
||||
}
|
||||
self.window.push_back((gain, loss));
|
||||
self.sum_gain += gain;
|
||||
self.sum_loss += loss;
|
||||
|
||||
if self.window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let denom = self.sum_gain + self.sum_loss;
|
||||
let cmo = if denom == 0.0 {
|
||||
// A flat window (no gains and no losses): momentum is exactly zero.
|
||||
0.0
|
||||
} else {
|
||||
100.0 * (self.sum_gain - self.sum_loss) / denom
|
||||
};
|
||||
self.current = Some(cmo);
|
||||
Some(cmo)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev_price = None;
|
||||
self.window.clear();
|
||||
self.sum_gain = 0.0;
|
||||
self.sum_loss = 0.0;
|
||||
self.current = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period + 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"CMO"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Cmo::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value() {
|
||||
// CMO(3) over [10, 11, 10, 12]: changes +1, −1, +2.
|
||||
// Σgain = 3, Σloss = 1 -> 100·(3−1)/(3+1) = 50.
|
||||
let mut cmo = Cmo::new(3).unwrap();
|
||||
let out = cmo.batch(&[10.0, 11.0, 10.0, 12.0]);
|
||||
assert_eq!(cmo.warmup_period(), 4);
|
||||
assert_eq!(out[0], None);
|
||||
assert_eq!(out[2], None);
|
||||
assert_relative_eq!(out[3].unwrap(), 50.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_saturates_at_plus_100() {
|
||||
let mut cmo = Cmo::new(5).unwrap();
|
||||
let out = cmo.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().skip(6).flatten() {
|
||||
assert_relative_eq!(*v, 100.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_downtrend_saturates_at_minus_100() {
|
||||
let mut cmo = Cmo::new(5).unwrap();
|
||||
let out = cmo.batch(&(1..=20).rev().map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().skip(6).flatten() {
|
||||
assert_relative_eq!(*v, -100.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
let mut cmo = Cmo::new(5).unwrap();
|
||||
let out = cmo.batch(&[42.0; 20]);
|
||||
for v in out.iter().skip(6).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut cmo = Cmo::new(3).unwrap();
|
||||
let out = cmo.batch(&[10.0, 11.0, 10.0, 12.0]);
|
||||
let ready = out[3].expect("CMO(3) ready after four inputs");
|
||||
assert_eq!(cmo.update(f64::NAN), Some(ready));
|
||||
assert_eq!(cmo.update(f64::INFINITY), Some(ready));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut cmo = Cmo::new(3).unwrap();
|
||||
cmo.batch(&[10.0, 11.0, 12.0, 13.0, 14.0]);
|
||||
assert!(cmo.is_ready());
|
||||
cmo.reset();
|
||||
assert!(!cmo.is_ready());
|
||||
assert_eq!(cmo.update(10.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=60)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.4).sin() * 6.0)
|
||||
.collect();
|
||||
let batch = Cmo::new(9).unwrap().batch(&prices);
|
||||
let mut b = Cmo::new(9).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ mod atr;
|
||||
mod awesome_oscillator;
|
||||
mod bollinger;
|
||||
mod cci;
|
||||
mod cmo;
|
||||
mod dema;
|
||||
mod donchian;
|
||||
mod ema;
|
||||
@@ -18,7 +19,9 @@ mod kama;
|
||||
mod keltner;
|
||||
mod macd;
|
||||
mod mfi;
|
||||
mod mom;
|
||||
mod obv;
|
||||
mod pmo;
|
||||
mod psar;
|
||||
mod roc;
|
||||
mod rsi;
|
||||
@@ -29,6 +32,7 @@ mod t3;
|
||||
mod tema;
|
||||
mod trima;
|
||||
mod trix;
|
||||
mod tsi;
|
||||
mod vwap;
|
||||
mod vwma;
|
||||
mod williams_r;
|
||||
@@ -41,6 +45,7 @@ pub use atr::Atr;
|
||||
pub use awesome_oscillator::AwesomeOscillator;
|
||||
pub use bollinger::{BollingerBands, BollingerOutput};
|
||||
pub use cci::Cci;
|
||||
pub use cmo::Cmo;
|
||||
pub use dema::Dema;
|
||||
pub use donchian::{Donchian, DonchianOutput};
|
||||
pub use ema::Ema;
|
||||
@@ -49,7 +54,9 @@ pub use kama::Kama;
|
||||
pub use keltner::{Keltner, KeltnerOutput};
|
||||
pub use macd::{MacdIndicator, MacdOutput};
|
||||
pub use mfi::Mfi;
|
||||
pub use mom::Mom;
|
||||
pub use obv::Obv;
|
||||
pub use pmo::Pmo;
|
||||
pub use psar::Psar;
|
||||
pub use roc::Roc;
|
||||
pub use rsi::Rsi;
|
||||
@@ -60,6 +67,7 @@ pub use t3::T3;
|
||||
pub use tema::Tema;
|
||||
pub use trima::Trima;
|
||||
pub use trix::Trix;
|
||||
pub use tsi::Tsi;
|
||||
pub use vwap::{RollingVwap, Vwap};
|
||||
pub use vwma::Vwma;
|
||||
pub use williams_r::WilliamsR;
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Momentum (absolute price change over a fixed lookback).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Momentum: the raw price change over `period` bars, `price_t − price_{t−period}`.
|
||||
///
|
||||
/// Unlike [`Roc`](crate::Roc), which divides by the old price to give a
|
||||
/// percentage, `Mom` reports the change in absolute price units. It is the
|
||||
/// simplest momentum primitive: positive values mean price is higher than it
|
||||
/// was `period` bars ago, negative values mean lower.
|
||||
///
|
||||
/// Non-finite inputs are ignored and leave the window untouched; the last
|
||||
/// computed value is returned instead.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, Mom};
|
||||
///
|
||||
/// let mut indicator = Mom::new(3).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Mom {
|
||||
period: usize,
|
||||
/// Rolling buffer of the last `period + 1` inputs, oldest at the front.
|
||||
window: VecDeque<f64>,
|
||||
last: Option<f64>,
|
||||
}
|
||||
|
||||
impl Mom {
|
||||
/// Construct a new momentum indicator with the given lookback period.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
window: VecDeque::with_capacity(period + 1),
|
||||
last: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured lookback period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.last
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Mom {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
// Non-finite input is ignored; the window is left untouched.
|
||||
return self.last;
|
||||
}
|
||||
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("window is non-empty");
|
||||
let mom = input - prev;
|
||||
self.last = Some(mom);
|
||||
Some(mom)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.last = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period + 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.window.len() == self.period + 1
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"MOM"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Mom::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_values() {
|
||||
// MOM(3): price_t − price_{t-3}.
|
||||
let mut mom = Mom::new(3).unwrap();
|
||||
let out = mom.batch(&[1.0, 2.0, 3.0, 4.0, 7.0]);
|
||||
assert_eq!(mom.warmup_period(), 4);
|
||||
assert_eq!(out[0], None);
|
||||
assert_eq!(out[2], None);
|
||||
assert_relative_eq!(out[3].unwrap(), 4.0 - 1.0, epsilon = 1e-12);
|
||||
assert_relative_eq!(out[4].unwrap(), 7.0 - 2.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
let mut mom = Mom::new(5).unwrap();
|
||||
let out = mom.batch(&[10.0; 20]);
|
||||
for v in out.iter().skip(5).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut mom = Mom::new(3).unwrap();
|
||||
let out = mom.batch(&[1.0, 2.0, 3.0, 4.0]);
|
||||
let ready = out[3].expect("MOM(3) ready after four inputs");
|
||||
assert_eq!(mom.update(f64::NAN), Some(ready));
|
||||
assert_eq!(mom.update(f64::INFINITY), Some(ready));
|
||||
// Window untouched: the next finite input still references price 2.
|
||||
assert_relative_eq!(mom.update(10.0).unwrap(), 10.0 - 2.0, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut mom = Mom::new(3).unwrap();
|
||||
mom.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
assert!(mom.is_ready());
|
||||
mom.reset();
|
||||
assert!(!mom.is_ready());
|
||||
assert_eq!(mom.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=40).map(|i| f64::from(i) * 1.5).collect();
|
||||
let batch = Mom::new(7).unwrap().batch(&prices);
|
||||
let mut b = Mom::new(7).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! Price Momentum Oscillator (`DecisionPoint`).
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
use super::Ema;
|
||||
|
||||
/// Price Momentum Oscillator — Carl Swenlin's `DecisionPoint` PMO line.
|
||||
///
|
||||
/// PMO is a doubly-smoothed rate of change. The 1-bar percentage change is
|
||||
/// smoothed once, scaled by `10`, then smoothed again:
|
||||
///
|
||||
/// ```text
|
||||
/// roc_t = (price_t / price_{t−1} − 1) · 100
|
||||
/// smoothed_t = customEMA(roc, smoothing1)_t
|
||||
/// PMO_t = customEMA(10 · smoothed, smoothing2)_t
|
||||
/// ```
|
||||
///
|
||||
/// `customEMA` is the `DecisionPoint` smoothing: an exponential average whose
|
||||
/// smoothing constant is `2 / period` (not the textbook `2 / (period + 1)`),
|
||||
/// seeded from the very first value. The conventional periods are `35` and
|
||||
/// `20`. The classic PMO **signal line** is simply a 10-period EMA of this
|
||||
/// PMO line — compose it with [`Chain`](crate::Chain) and an [`Ema`] if you
|
||||
/// need it.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, Pmo};
|
||||
///
|
||||
/// let mut indicator = Pmo::new(35, 20).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..120 {
|
||||
/// last = indicator.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Pmo {
|
||||
smoothing1: usize,
|
||||
smoothing2: usize,
|
||||
prev_price: Option<f64>,
|
||||
ema1: Ema,
|
||||
ema2: Ema,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
impl Pmo {
|
||||
/// Construct a new PMO with the two smoothing periods.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if either period is `0`, or
|
||||
/// [`Error::InvalidPeriod`] if either is `1` (the smoothing constant
|
||||
/// `2 / period` must not exceed `1`).
|
||||
pub fn new(smoothing1: usize, smoothing2: usize) -> Result<Self> {
|
||||
if smoothing1 == 0 || smoothing2 == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if smoothing1 < 2 || smoothing2 < 2 {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "PMO smoothing periods must be >= 2",
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
smoothing1,
|
||||
smoothing2,
|
||||
prev_price: None,
|
||||
ema1: Ema::with_alpha(2.0 / smoothing1 as f64)?,
|
||||
ema2: Ema::with_alpha(2.0 / smoothing2 as f64)?,
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `(smoothing1, smoothing2)` periods.
|
||||
pub const fn periods(&self) -> (usize, usize) {
|
||||
(self.smoothing1, self.smoothing2)
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Pmo {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
// Non-finite input is ignored; state is left untouched.
|
||||
return self.current;
|
||||
}
|
||||
let Some(prev) = self.prev_price else {
|
||||
self.prev_price = Some(input);
|
||||
return None;
|
||||
};
|
||||
self.prev_price = Some(input);
|
||||
|
||||
let roc = if prev == 0.0 {
|
||||
// Undefined ratio against a zero price: treat momentum as flat.
|
||||
0.0
|
||||
} else {
|
||||
(input / prev - 1.0) * 100.0
|
||||
};
|
||||
let smoothed = self.ema1.update(roc)?;
|
||||
let pmo = self.ema2.update(10.0 * smoothed)?;
|
||||
self.current = Some(pmo);
|
||||
Some(pmo)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev_price = None;
|
||||
self.ema1.reset();
|
||||
self.ema2.reset();
|
||||
self.current = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// The first ROC needs a previous price; both customEMAs seed from
|
||||
// their first input, so the first PMO lands on the second update.
|
||||
2
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"PMO"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Pmo::new(0, 20), Err(Error::PeriodZero)));
|
||||
assert!(matches!(Pmo::new(35, 0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_period_one() {
|
||||
assert!(matches!(Pmo::new(1, 20), Err(Error::InvalidPeriod { .. })));
|
||||
assert!(matches!(Pmo::new(35, 1), Err(Error::InvalidPeriod { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_at_second_update() {
|
||||
let mut pmo = Pmo::new(35, 20).unwrap();
|
||||
assert_eq!(pmo.warmup_period(), 2);
|
||||
assert_eq!(pmo.update(100.0), None);
|
||||
assert!(pmo.update(101.0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
// Flat prices -> ROC is always 0 -> both smoothings stay at 0.
|
||||
let mut pmo = Pmo::new(35, 20).unwrap();
|
||||
let out = pmo.batch(&[100.0; 60]);
|
||||
for v in out.iter().skip(2).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steady_uptrend_is_positive() {
|
||||
let mut pmo = Pmo::new(35, 20).unwrap();
|
||||
let prices: Vec<f64> = (1..=120).map(|i| 100.0 * 1.01_f64.powi(i)).collect();
|
||||
let out = pmo.batch(&prices);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert!(
|
||||
*last > 0.0,
|
||||
"steady uptrend PMO should be positive, got {last}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut pmo = Pmo::new(35, 20).unwrap();
|
||||
let out = pmo.batch(&(1..=60).map(f64::from).collect::<Vec<_>>());
|
||||
let last = *out.last().unwrap();
|
||||
assert!(last.is_some());
|
||||
assert_eq!(pmo.update(f64::NAN), last);
|
||||
assert_eq!(pmo.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut pmo = Pmo::new(35, 20).unwrap();
|
||||
pmo.batch(&(1..=60).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(pmo.is_ready());
|
||||
pmo.reset();
|
||||
assert!(!pmo.is_ready());
|
||||
assert_eq!(pmo.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=120)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.25).sin() * 8.0)
|
||||
.collect();
|
||||
let batch = Pmo::new(35, 20).unwrap().batch(&prices);
|
||||
let mut b = Pmo::new(35, 20).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! True Strength Index.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
use super::Ema;
|
||||
|
||||
/// True Strength Index — William Blau's double-smoothed momentum oscillator.
|
||||
///
|
||||
/// The 1-bar momentum `price_t − price_{t−1}` and its absolute value are each
|
||||
/// smoothed twice — first with an EMA of length `long`, then with an EMA of
|
||||
/// length `short` — and the indicator reports their ratio scaled to a
|
||||
/// percentage:
|
||||
///
|
||||
/// ```text
|
||||
/// TSI = 100 · EMA_short(EMA_long(momentum)) / EMA_short(EMA_long(|momentum|))
|
||||
/// ```
|
||||
///
|
||||
/// The double smoothing strips most of the noise while the ratio normalises
|
||||
/// the result into a roughly `[−100, 100]` oscillator centred on zero:
|
||||
/// positive means net upward pressure, negative net downward.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, Tsi};
|
||||
///
|
||||
/// let mut indicator = Tsi::new(25, 13).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert_eq!(last, Some(100.0)); // pure uptrend saturates at +100
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Tsi {
|
||||
long: usize,
|
||||
short: usize,
|
||||
prev_price: Option<f64>,
|
||||
ema_long_mom: Ema,
|
||||
ema_short_mom: Ema,
|
||||
ema_long_abs: Ema,
|
||||
ema_short_abs: Ema,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
impl Tsi {
|
||||
/// Construct a new TSI with the `long` and `short` smoothing periods.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if either period is `0`.
|
||||
pub fn new(long: usize, short: usize) -> Result<Self> {
|
||||
if long == 0 || short == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
long,
|
||||
short,
|
||||
prev_price: None,
|
||||
ema_long_mom: Ema::new(long)?,
|
||||
ema_short_mom: Ema::new(short)?,
|
||||
ema_long_abs: Ema::new(long)?,
|
||||
ema_short_abs: Ema::new(short)?,
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `(long, short)` smoothing periods.
|
||||
pub const fn periods(&self) -> (usize, usize) {
|
||||
(self.long, self.short)
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Tsi {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
// Non-finite input is ignored; state is left untouched.
|
||||
return self.current;
|
||||
}
|
||||
let Some(prev) = self.prev_price else {
|
||||
self.prev_price = Some(input);
|
||||
return None;
|
||||
};
|
||||
self.prev_price = Some(input);
|
||||
|
||||
let momentum = input - prev;
|
||||
let ds_mom = self
|
||||
.ema_long_mom
|
||||
.update(momentum)
|
||||
.and_then(|v| self.ema_short_mom.update(v));
|
||||
let ds_abs = self
|
||||
.ema_long_abs
|
||||
.update(momentum.abs())
|
||||
.and_then(|v| self.ema_short_abs.update(v));
|
||||
|
||||
match (ds_mom, ds_abs) {
|
||||
(Some(m), Some(a)) => {
|
||||
let tsi = if a == 0.0 {
|
||||
// Flat double-smoothed range: there is no momentum at all.
|
||||
0.0
|
||||
} else {
|
||||
100.0 * m / a
|
||||
};
|
||||
self.current = Some(tsi);
|
||||
Some(tsi)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev_price = None;
|
||||
self.ema_long_mom.reset();
|
||||
self.ema_short_mom.reset();
|
||||
self.ema_long_abs.reset();
|
||||
self.ema_short_abs.reset();
|
||||
self.current = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.long + self.short
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"TSI"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Tsi::new(0, 13), Err(Error::PeriodZero)));
|
||||
assert!(matches!(Tsi::new(25, 0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_at_warmup_period() {
|
||||
let mut tsi = Tsi::new(5, 3).unwrap();
|
||||
assert_eq!(tsi.warmup_period(), 8);
|
||||
let out = tsi.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().take(7) {
|
||||
assert!(v.is_none());
|
||||
}
|
||||
assert!(out[7].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_saturates_at_plus_100() {
|
||||
// Every momentum is +1, so |momentum| == momentum and the ratio is 1.
|
||||
let mut tsi = Tsi::new(5, 3).unwrap();
|
||||
let out = tsi.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().skip(8).flatten() {
|
||||
assert_relative_eq!(*v, 100.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_downtrend_saturates_at_minus_100() {
|
||||
let mut tsi = Tsi::new(5, 3).unwrap();
|
||||
let out = tsi.batch(&(1..=40).rev().map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().skip(8).flatten() {
|
||||
assert_relative_eq!(*v, -100.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
let mut tsi = Tsi::new(5, 3).unwrap();
|
||||
let out = tsi.batch(&[50.0; 40]);
|
||||
for v in out.iter().skip(8).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut tsi = Tsi::new(5, 3).unwrap();
|
||||
let out = tsi.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
let last = *out.last().unwrap();
|
||||
assert!(last.is_some());
|
||||
assert_eq!(tsi.update(f64::NAN), last);
|
||||
assert_eq!(tsi.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut tsi = Tsi::new(5, 3).unwrap();
|
||||
tsi.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(tsi.is_ready());
|
||||
tsi.reset();
|
||||
assert!(!tsi.is_ready());
|
||||
assert_eq!(tsi.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=80)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 9.0)
|
||||
.collect();
|
||||
let batch = Tsi::new(13, 7).unwrap().batch(&prices);
|
||||
let mut b = Tsi::new(13, 7).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -45,9 +45,9 @@ pub mod indicators;
|
||||
pub use error::{Error, Result};
|
||||
pub use indicators::{
|
||||
Adx, AdxOutput, Aroon, AroonOutput, Atr, AwesomeOscillator, BollingerBands, BollingerOutput,
|
||||
Cci, Dema, Donchian, DonchianOutput, Ema, Hma, Kama, Keltner, KeltnerOutput, MacdIndicator,
|
||||
MacdOutput, Mfi, Obv, Psar, Roc, RollingVwap, Rsi, Sma, Smma, Stochastic, StochasticOutput,
|
||||
Tema, Trima, Trix, Vwap, Vwma, WilliamsR, Wma, Zlema, T3,
|
||||
Cci, Cmo, Dema, Donchian, DonchianOutput, Ema, Hma, Kama, Keltner, KeltnerOutput,
|
||||
MacdIndicator, MacdOutput, Mfi, Mom, Obv, Pmo, Psar, Roc, RollingVwap, Rsi, Sma, Smma,
|
||||
Stochastic, StochasticOutput, Tema, Trima, Trix, Tsi, Vwap, Vwma, WilliamsR, Wma, Zlema, T3,
|
||||
};
|
||||
pub use ohlcv::{Candle, Tick};
|
||||
pub use traits::{BatchExt, Chain, Indicator};
|
||||
|
||||
Reference in New Issue
Block a user