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:
@@ -310,7 +310,7 @@ if (!nativeBinding) {
|
||||
throw new Error(`Failed to load native binding`)
|
||||
}
|
||||
|
||||
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, T3, VWMA, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, AwesomeOscillator, Aroon, KAMA } = nativeBinding
|
||||
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, T3, VWMA, MOM, CMO, TSI, PMO, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, AwesomeOscillator, Aroon, KAMA } = nativeBinding
|
||||
|
||||
module.exports.version = version
|
||||
module.exports.SMA = SMA
|
||||
@@ -327,6 +327,10 @@ module.exports.TRIMA = TRIMA
|
||||
module.exports.ZLEMA = ZLEMA
|
||||
module.exports.T3 = T3
|
||||
module.exports.VWMA = VWMA
|
||||
module.exports.MOM = MOM
|
||||
module.exports.CMO = CMO
|
||||
module.exports.TSI = TSI
|
||||
module.exports.PMO = PMO
|
||||
module.exports.MACD = MACD
|
||||
module.exports.BollingerBands = BollingerBands
|
||||
module.exports.ATR = ATR
|
||||
|
||||
@@ -105,6 +105,8 @@ node_scalar_indicator!(TrixNode, "TRIX", wc::Trix);
|
||||
node_scalar_indicator!(SmmaNode, "SMMA", wc::Smma);
|
||||
node_scalar_indicator!(TrimaNode, "TRIMA", wc::Trima);
|
||||
node_scalar_indicator!(ZlemaNode, "ZLEMA", wc::Zlema);
|
||||
node_scalar_indicator!(MomNode, "MOM", wc::Mom);
|
||||
node_scalar_indicator!(CmoNode, "CMO", wc::Cmo);
|
||||
|
||||
// ============================== MACD ==============================
|
||||
|
||||
@@ -1066,6 +1068,80 @@ impl T3Node {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== TSI ==============================
|
||||
|
||||
#[napi(js_name = "TSI")]
|
||||
pub struct TsiNode {
|
||||
inner: wc::Tsi,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl TsiNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(long: u32, short: u32) -> napi::Result<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::Tsi::new(long as usize, short as usize).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
#[napi]
|
||||
pub fn update(&mut self, value: f64) -> Option<f64> {
|
||||
self.inner.update(value)
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(&mut self, prices: Vec<f64>) -> Vec<f64> {
|
||||
flatten(self.inner.batch(&prices))
|
||||
}
|
||||
#[napi]
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
#[napi(js_name = "isReady")]
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
#[napi(js_name = "warmupPeriod")]
|
||||
pub fn warmup_period(&self) -> u32 {
|
||||
self.inner.warmup_period() as u32
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== PMO ==============================
|
||||
|
||||
#[napi(js_name = "PMO")]
|
||||
pub struct PmoNode {
|
||||
inner: wc::Pmo,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl PmoNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(smoothing1: u32, smoothing2: u32) -> napi::Result<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::Pmo::new(smoothing1 as usize, smoothing2 as usize).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
#[napi]
|
||||
pub fn update(&mut self, value: f64) -> Option<f64> {
|
||||
self.inner.update(value)
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(&mut self, prices: Vec<f64>) -> Vec<f64> {
|
||||
flatten(self.inner.batch(&prices))
|
||||
}
|
||||
#[napi]
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
#[napi(js_name = "isReady")]
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
#[napi(js_name = "warmupPeriod")]
|
||||
pub fn warmup_period(&self) -> u32 {
|
||||
self.inner.warmup_period() as u32
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== VWMA ==============================
|
||||
|
||||
#[napi(js_name = "VWMA")]
|
||||
|
||||
@@ -76,6 +76,54 @@ class TRIMA:
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
|
||||
class MOM:
|
||||
def __init__(self, period: int = 10) -> None: ...
|
||||
def update(self, value: float) -> Optional[float]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def period(self) -> int: ...
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
|
||||
class CMO:
|
||||
def __init__(self, period: int = 14) -> None: ...
|
||||
def update(self, value: float) -> Optional[float]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def period(self) -> int: ...
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
|
||||
class TSI:
|
||||
def __init__(self, long: int = 25, short: int = 13) -> None: ...
|
||||
def update(self, value: float) -> Optional[float]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def periods(self) -> Tuple[int, int]: ...
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
|
||||
class PMO:
|
||||
def __init__(self, smoothing1: int = 35, smoothing2: int = 20) -> None: ...
|
||||
def update(self, value: float) -> Optional[float]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def periods(self) -> Tuple[int, int]: ...
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
|
||||
class ZLEMA:
|
||||
def __init__(self, period: int) -> None: ...
|
||||
def update(self, value: float) -> Optional[float]: ...
|
||||
|
||||
@@ -1519,6 +1519,216 @@ impl PyAroon {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== MOM ==============================
|
||||
|
||||
#[pyclass(name = "MOM", module = "wickra._wickra")]
|
||||
#[derive(Clone)]
|
||||
struct PyMom {
|
||||
inner: wc::Mom,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PyMom {
|
||||
#[new]
|
||||
#[pyo3(signature = (period=10))]
|
||||
fn new(period: usize) -> PyResult<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::Mom::new(period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
fn update(&mut self, value: f64) -> Option<f64> {
|
||||
self.inner.update(value)
|
||||
}
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
prices: PyReadonlyArray1<'py, f64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let slice = prices
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
Ok(flatten(self.inner.batch(slice)).into_pyarray_bound(py))
|
||||
}
|
||||
#[getter]
|
||||
fn period(&self) -> usize {
|
||||
self.inner.period()
|
||||
}
|
||||
#[getter]
|
||||
fn value(&self) -> Option<f64> {
|
||||
self.inner.value()
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.inner.warmup_period()
|
||||
}
|
||||
fn __repr__(&self) -> String {
|
||||
format!("MOM(period={})", self.inner.period())
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== CMO ==============================
|
||||
|
||||
#[pyclass(name = "CMO", module = "wickra._wickra")]
|
||||
#[derive(Clone)]
|
||||
struct PyCmo {
|
||||
inner: wc::Cmo,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PyCmo {
|
||||
#[new]
|
||||
#[pyo3(signature = (period=14))]
|
||||
fn new(period: usize) -> PyResult<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::Cmo::new(period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
fn update(&mut self, value: f64) -> Option<f64> {
|
||||
self.inner.update(value)
|
||||
}
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
prices: PyReadonlyArray1<'py, f64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let slice = prices
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
Ok(flatten(self.inner.batch(slice)).into_pyarray_bound(py))
|
||||
}
|
||||
#[getter]
|
||||
fn period(&self) -> usize {
|
||||
self.inner.period()
|
||||
}
|
||||
#[getter]
|
||||
fn value(&self) -> Option<f64> {
|
||||
self.inner.value()
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.inner.warmup_period()
|
||||
}
|
||||
fn __repr__(&self) -> String {
|
||||
format!("CMO(period={})", self.inner.period())
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== TSI ==============================
|
||||
|
||||
#[pyclass(name = "TSI", module = "wickra._wickra")]
|
||||
#[derive(Clone)]
|
||||
struct PyTsi {
|
||||
inner: wc::Tsi,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PyTsi {
|
||||
#[new]
|
||||
#[pyo3(signature = (long=25, short=13))]
|
||||
fn new(long: usize, short: usize) -> PyResult<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::Tsi::new(long, short).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
fn update(&mut self, value: f64) -> Option<f64> {
|
||||
self.inner.update(value)
|
||||
}
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
prices: PyReadonlyArray1<'py, f64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let slice = prices
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
Ok(flatten(self.inner.batch(slice)).into_pyarray_bound(py))
|
||||
}
|
||||
#[getter]
|
||||
fn periods(&self) -> (usize, usize) {
|
||||
self.inner.periods()
|
||||
}
|
||||
#[getter]
|
||||
fn value(&self) -> Option<f64> {
|
||||
self.inner.value()
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.inner.warmup_period()
|
||||
}
|
||||
fn __repr__(&self) -> String {
|
||||
let (l, s) = self.inner.periods();
|
||||
format!("TSI(long={l}, short={s})")
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== PMO ==============================
|
||||
|
||||
#[pyclass(name = "PMO", module = "wickra._wickra")]
|
||||
#[derive(Clone)]
|
||||
struct PyPmo {
|
||||
inner: wc::Pmo,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PyPmo {
|
||||
#[new]
|
||||
#[pyo3(signature = (smoothing1=35, smoothing2=20))]
|
||||
fn new(smoothing1: usize, smoothing2: usize) -> PyResult<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::Pmo::new(smoothing1, smoothing2).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
fn update(&mut self, value: f64) -> Option<f64> {
|
||||
self.inner.update(value)
|
||||
}
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
prices: PyReadonlyArray1<'py, f64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let slice = prices
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
Ok(flatten(self.inner.batch(slice)).into_pyarray_bound(py))
|
||||
}
|
||||
#[getter]
|
||||
fn periods(&self) -> (usize, usize) {
|
||||
self.inner.periods()
|
||||
}
|
||||
#[getter]
|
||||
fn value(&self) -> Option<f64> {
|
||||
self.inner.value()
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.inner.warmup_period()
|
||||
}
|
||||
fn __repr__(&self) -> String {
|
||||
let (s1, s2) = self.inner.periods();
|
||||
format!("PMO(smoothing1={s1}, smoothing2={s2})")
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== ZLEMA ==============================
|
||||
|
||||
#[pyclass(name = "ZLEMA", module = "wickra._wickra")]
|
||||
@@ -1838,5 +2048,9 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<PyZlema>()?;
|
||||
m.add_class::<PyT3>()?;
|
||||
m.add_class::<PyVwma>()?;
|
||||
m.add_class::<PyMom>()?;
|
||||
m.add_class::<PyCmo>()?;
|
||||
m.add_class::<PyTsi>()?;
|
||||
m.add_class::<PyPmo>()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -79,6 +79,10 @@ wasm_scalar_indicator!(WasmSmma, "SMMA", wc::Smma, period: usize);
|
||||
wasm_scalar_indicator!(WasmTrima, "TRIMA", wc::Trima, period: usize);
|
||||
wasm_scalar_indicator!(WasmZlema, "ZLEMA", wc::Zlema, period: usize);
|
||||
wasm_scalar_indicator!(WasmT3, "T3", wc::T3, period: usize, v: f64);
|
||||
wasm_scalar_indicator!(WasmMom, "MOM", wc::Mom, period: usize);
|
||||
wasm_scalar_indicator!(WasmCmo, "CMO", wc::Cmo, period: usize);
|
||||
wasm_scalar_indicator!(WasmTsi, "TSI", wc::Tsi, long: usize, short: usize);
|
||||
wasm_scalar_indicator!(WasmPmo, "PMO", wc::Pmo, smoothing1: usize, smoothing2: usize);
|
||||
|
||||
// ---------- KAMA (three params) ----------
|
||||
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -98,6 +98,10 @@ Rust / Python / Node examples. They are grouped by family, mirroring the
|
||||
- [Indicator-Trix.md](indicators/momentum/Indicator-Trix.md)
|
||||
- [Indicator-AwesomeOscillator.md](indicators/momentum/Indicator-AwesomeOscillator.md)
|
||||
- [Indicator-Aroon.md](indicators/momentum/Indicator-Aroon.md)
|
||||
- [Indicator-Mom.md](indicators/momentum/Indicator-Mom.md)
|
||||
- [Indicator-Cmo.md](indicators/momentum/Indicator-Cmo.md)
|
||||
- [Indicator-Tsi.md](indicators/momentum/Indicator-Tsi.md)
|
||||
- [Indicator-Pmo.md](indicators/momentum/Indicator-Pmo.md)
|
||||
|
||||
**Volatility** — envelope width and per-bar dispersion measures.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Indicators Overview
|
||||
|
||||
Wickra ships 30 indicators, organised in source under the four classical
|
||||
Wickra ships 34 indicators, organised in source under the four classical
|
||||
families — trend, momentum, volatility, volume — that map directly to the
|
||||
directory structure of `crates/wickra-core/src/indicators/`. The same family
|
||||
labels are used here, plus a second-level grouping that reflects how the
|
||||
@@ -97,6 +97,10 @@ Centered on zero or driven by raw price differences; no fixed cap.
|
||||
| `AwesomeOscillator` | `SMA(median, fast) − SMA(median, slow)`; Bill Williams' zero-line crossover oscillator. | `Candle` | `f64` | unbounded around zero | `(fast=5, slow=34)` (Python) | `slow_period` | [Indicator-AwesomeOscillator.md](indicators/momentum/Indicator-AwesomeOscillator.md) |
|
||||
| `WilliamsR` | `−100 × (high_n − close) / (high_n − low_n)`; same family as Stochastic but inverted to `[−100, 0]`. | `Candle` | `f64` | `[−100, 0]` | `period = 14` (Python) | `period` | [Indicator-WilliamsR.md](indicators/momentum/Indicator-WilliamsR.md) |
|
||||
| `Trix` | `(EMA(EMA(EMA(price))).pct_change × 10000)`; oscillator built from a triple-smoothed EMA. | `f64` | `f64` | unbounded around zero | `period = 15` (Python) | `3·period − 1` | [Indicator-Trix.md](indicators/momentum/Indicator-Trix.md) |
|
||||
| `Mom` | `price − price[period]`; raw price-difference momentum. | `f64` | `f64` | unbounded around zero | `period = 10` (Python) | `period + 1` | [Indicator-Mom.md](indicators/momentum/Indicator-Mom.md) |
|
||||
| `Cmo` | Chande Momentum Oscillator; `100·(Σgain − Σloss)/(Σgain + Σloss)` over `period` changes. | `f64` | `f64` | `[−100, 100]` | `period = 14` (Python) | `period + 1` | [Indicator-Cmo.md](indicators/momentum/Indicator-Cmo.md) |
|
||||
| `Tsi` | True Strength Index; ratio of double-EMA-smoothed momentum to its absolute value. | `f64` | `f64` | ≈ `[−100, 100]` around zero | `(long=25, short=13)` (Python) | `long + short` | [Indicator-Tsi.md](indicators/momentum/Indicator-Tsi.md) |
|
||||
| `Pmo` | DecisionPoint Price Momentum Oscillator; doubly-smoothed rate of change. | `f64` | `f64` | unbounded around zero | `(smoothing1=35, smoothing2=20)` (Python) | `2` | [Indicator-Pmo.md](indicators/momentum/Indicator-Pmo.md) |
|
||||
|
||||
### Directional
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# CMO
|
||||
|
||||
> Chande Momentum Oscillator — a bounded `[−100, 100]` momentum gauge from
|
||||
> the unsmoothed sum of gains versus losses.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Family | Momentum |
|
||||
| Sub-category | Bounded oscillators (−100 … 100) |
|
||||
| Input type | `f64` (single close) |
|
||||
| Output type | `f64` |
|
||||
| Output range | `[−100, 100]` |
|
||||
| Default parameters | `period = 14` (Python) |
|
||||
| Warmup period | `period + 1` |
|
||||
| Interpretation | `+100` pure gains, `−100` pure losses, `0` balanced. |
|
||||
|
||||
## Formula
|
||||
|
||||
Over the last `period` price *changes*, sum the gains and the losses
|
||||
separately:
|
||||
|
||||
```
|
||||
gain_t = max(price_t − price_{t−1}, 0)
|
||||
loss_t = max(price_{t−1} − price_t, 0)
|
||||
CMO = 100 · (Σ gain − Σ loss) / (Σ gain + Σ loss)
|
||||
```
|
||||
|
||||
Unlike RSI — which Wilder-smooths the gain/loss averages — CMO sums them
|
||||
raw, with equal weight on every change in the window. That makes it
|
||||
faster and wider-swinging than RSI at the same period.
|
||||
|
||||
## Parameters
|
||||
|
||||
| Name | Type | Default | Valid range | Description |
|
||||
|----------|---------|---------------|-------------|-------------|
|
||||
| `period` | `usize` | `14` (Python) | `>= 1` | Number of price changes summed. `period = 0` errors with `Error::PeriodZero`. |
|
||||
|
||||
The Python binding defaults `period` to `14` via `#[pyo3(signature = (period=14))]`.
|
||||
|
||||
## Inputs / Outputs
|
||||
|
||||
From `crates/wickra-core/src/indicators/cmo.rs`:
|
||||
|
||||
```rust
|
||||
impl Indicator for Cmo {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
// update(&mut self, input: f64) -> Option<f64>
|
||||
}
|
||||
```
|
||||
|
||||
A single `f64` close in, an `Option<f64>` out. Python maps this to
|
||||
`float | None` / `numpy.ndarray` (NaN warmup); Node to `number | null` /
|
||||
`Array<number>` (NaN warmup).
|
||||
|
||||
## Warmup
|
||||
|
||||
`Cmo::new(period).warmup_period() == period + 1`. The first price change
|
||||
needs two inputs, and the gain/loss window must hold `period` changes, so
|
||||
the first non-`None` output lands on input `period + 1`.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- **Pure trend.** A window of only gains returns `+100`; only losses,
|
||||
`−100` (`pure_uptrend_saturates_at_plus_100` /
|
||||
`pure_downtrend_saturates_at_minus_100` pin this).
|
||||
- **Constant series.** A flat series has no gains and no losses; the
|
||||
`0 / 0` is guarded and the output is `0.0`
|
||||
(`constant_series_yields_zero` pins this).
|
||||
- **NaN / infinity inputs.** Non-finite inputs are silently dropped; state
|
||||
is left untouched.
|
||||
- **Reset.** `cmo.reset()` clears the previous price, the gain/loss window
|
||||
and both running sums.
|
||||
|
||||
## Examples
|
||||
|
||||
### Rust
|
||||
|
||||
```rust
|
||||
use wickra::{BatchExt, Indicator, Cmo};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut cmo = Cmo::new(3)?;
|
||||
let out: Vec<Option<f64>> = cmo.batch(&[10.0, 11.0, 10.0, 12.0]);
|
||||
println!("{:?}", out);
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[None, None, None, Some(50.0)]
|
||||
```
|
||||
|
||||
The three changes are `+1, −1, +2`: `Σ gain = 3`, `Σ loss = 1`, so
|
||||
`CMO = 100·(3 − 1)/(3 + 1) = 50`. This matches the `reference_value` test
|
||||
in `crates/wickra-core/src/indicators/cmo.rs`.
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import wickra as ta
|
||||
|
||||
cmo = ta.CMO(3)
|
||||
print(cmo.batch(np.array([10.0, 11.0, 10.0, 12.0])))
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[nan nan nan 50.]
|
||||
```
|
||||
|
||||
### Node
|
||||
|
||||
```javascript
|
||||
const ta = require('wickra');
|
||||
const cmo = new ta.CMO(3);
|
||||
console.log(cmo.batch([10, 11, 10, 12]));
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[ NaN, NaN, NaN, 50 ]
|
||||
```
|
||||
|
||||
## Interpretation
|
||||
|
||||
`Cmo` is read like other bounded oscillators: readings near `+50` and
|
||||
above flag overbought conditions, near `−50` and below oversold, and the
|
||||
zero line marks the gain/loss balance point. Because it is unsmoothed it
|
||||
reacts a bar or two sooner than RSI but is noisier — pair it with a slower
|
||||
filter, or use it for divergence rather than raw threshold triggers.
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
- **Expecting the `[0, 100]` RSI scale.** `Cmo` is centred on zero and
|
||||
spans `[−100, 100]`; an RSI of `30` corresponds to a `Cmo` near `−40`.
|
||||
- **Treating it as a smoothed average.** `Cmo` sums raw changes — it is
|
||||
deliberately not Wilder-smoothed.
|
||||
|
||||
## References
|
||||
|
||||
Tushar Chande, *The New Technical Trader* (1994). The unsmoothed
|
||||
gain/loss sum here matches the original definition and TA-Lib's `CMO`.
|
||||
|
||||
## See also
|
||||
|
||||
- [Indicator-Rsi.md](Indicator-Rsi.md) — the Wilder-smoothed relative.
|
||||
- [Indicator-Mom.md](Indicator-Mom.md) — raw price-difference momentum.
|
||||
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
|
||||
@@ -0,0 +1,152 @@
|
||||
# MOM
|
||||
|
||||
> Momentum — the raw price change over a fixed lookback,
|
||||
> `price_t − price_{t−period}`, in absolute price units.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Family | Momentum |
|
||||
| Sub-category | Unbounded oscillators |
|
||||
| Input type | `f64` (single close) |
|
||||
| Output type | `f64` |
|
||||
| Output range | unbounded around zero (price-difference scale) |
|
||||
| Default parameters | `period = 10` (Python) |
|
||||
| Warmup period | `period + 1` |
|
||||
| Interpretation | Sign and size of the move over the last `period` bars. |
|
||||
|
||||
## Formula
|
||||
|
||||
```
|
||||
MOM_t = price_t − price_{t−period}
|
||||
```
|
||||
|
||||
The simplest momentum primitive. Positive output means price is higher
|
||||
than it was `period` bars ago, negative means lower, and the magnitude is
|
||||
the change in raw price units. [`Roc`](Indicator-Roc.md) is the same idea
|
||||
expressed as a percentage of the old price.
|
||||
|
||||
## Parameters
|
||||
|
||||
| Name | Type | Default | Valid range | Description |
|
||||
|----------|---------|----------------|-------------|-------------|
|
||||
| `period` | `usize` | `10` (Python) | `>= 1` | Lookback distance in bars. `period = 0` errors with `Error::PeriodZero`. |
|
||||
|
||||
The Python binding defaults `period` to `10` via `#[pyo3(signature = (period=10))]`.
|
||||
|
||||
## Inputs / Outputs
|
||||
|
||||
From `crates/wickra-core/src/indicators/mom.rs`:
|
||||
|
||||
```rust
|
||||
impl Indicator for Mom {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
// update(&mut self, input: f64) -> Option<f64>
|
||||
}
|
||||
```
|
||||
|
||||
A single `f64` close in, an `Option<f64>` out. Python maps this to
|
||||
`float | None` / `numpy.ndarray` (NaN warmup); Node to `number | null` /
|
||||
`Array<number>` (NaN warmup).
|
||||
|
||||
## Warmup
|
||||
|
||||
`Mom::new(period).warmup_period() == period + 1`. The output needs both
|
||||
the current price and the price `period` bars back, so the window must
|
||||
hold `period + 1` values — the first non-`None` output lands on input
|
||||
`period + 1`.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- **Constant series.** A flat series yields `0.0` from input `period + 1`
|
||||
onward (`constant_series_yields_zero` pins this).
|
||||
- **NaN / infinity inputs.** Non-finite inputs are silently dropped: the
|
||||
rolling window is not advanced and the previous value is returned. The
|
||||
next finite input still references the correct historical price.
|
||||
- **Reset.** `mom.reset()` clears the window and restarts the warmup.
|
||||
|
||||
## Examples
|
||||
|
||||
### Rust
|
||||
|
||||
```rust
|
||||
use wickra::{BatchExt, Indicator, Mom};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut mom = Mom::new(3)?;
|
||||
let out: Vec<Option<f64>> = mom.batch(&[1.0, 2.0, 3.0, 4.0, 7.0]);
|
||||
println!("{:?}", out);
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[None, None, None, Some(3.0), Some(5.0)]
|
||||
```
|
||||
|
||||
`MOM(3)` first emits on input 4: `4 − 1 = 3`. The fifth input gives
|
||||
`7 − 2 = 5`. This matches the `reference_values` test in
|
||||
`crates/wickra-core/src/indicators/mom.rs`.
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import wickra as ta
|
||||
|
||||
mom = ta.MOM(3)
|
||||
print(mom.batch(np.array([1.0, 2.0, 3.0, 4.0, 7.0])))
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[nan nan nan 3. 5.]
|
||||
```
|
||||
|
||||
### Node
|
||||
|
||||
```javascript
|
||||
const ta = require('wickra');
|
||||
const mom = new ta.MOM(3);
|
||||
console.log(mom.batch([1, 2, 3, 4, 7]));
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[ NaN, NaN, NaN, 3, 5 ]
|
||||
```
|
||||
|
||||
## Interpretation
|
||||
|
||||
`Mom` is a zero-centred oscillator. The textbook reads are the zero-line
|
||||
cross (momentum flipping sign) and divergence (price making a new high
|
||||
while `Mom` makes a lower high — a stalling trend). Because the output is
|
||||
in price units, `Mom` values are not comparable across instruments at
|
||||
different price levels; use [`Roc`](Indicator-Roc.md) when you need a
|
||||
scale-free percentage instead.
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
- **Comparing `Mom` across instruments.** A `Mom` of `5` means very
|
||||
different things on a $10 stock and a $5000 index. Normalise with `Roc`
|
||||
for cross-asset work.
|
||||
- **Forgetting the `+1` warmup.** `warmup_period()` is `period + 1`, not
|
||||
`period`.
|
||||
|
||||
## References
|
||||
|
||||
Momentum is one of the oldest technical studies; the implementation here
|
||||
is the standard `price − price[period]` difference, matching TA-Lib's
|
||||
`MOM`.
|
||||
|
||||
## See also
|
||||
|
||||
- [Indicator-Roc.md](Indicator-Roc.md) — the percentage-scaled counterpart.
|
||||
- [Indicator-Cmo.md](Indicator-Cmo.md) — bounded momentum from summed changes.
|
||||
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
|
||||
@@ -0,0 +1,170 @@
|
||||
# PMO
|
||||
|
||||
> Price Momentum Oscillator — Carl Swenlin's DecisionPoint PMO line: a
|
||||
> doubly-smoothed rate of change.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Family | Momentum |
|
||||
| Sub-category | Unbounded oscillators |
|
||||
| Input type | `f64` (single close) |
|
||||
| Output type | `f64` |
|
||||
| Output range | unbounded around zero |
|
||||
| Default parameters | `(smoothing1 = 35, smoothing2 = 20)` (Python) |
|
||||
| Warmup period | `2` |
|
||||
| Interpretation | Smoothed momentum; zero-line and signal-line crosses are the signals. |
|
||||
|
||||
## Formula
|
||||
|
||||
```
|
||||
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 its first input. The 1-bar percentage change is smoothed once,
|
||||
scaled by `10`, then smoothed again.
|
||||
|
||||
The classic PMO **signal line** is a 10-period EMA of this PMO line. It is
|
||||
deliberately not bundled in — compose it yourself with
|
||||
[`Chain`](../Indicator-Chaining.md) and an `Ema(10)`.
|
||||
|
||||
## Parameters
|
||||
|
||||
| Name | Type | Default | Valid range | Description |
|
||||
|--------------|---------|---------------|-------------|-------------|
|
||||
| `smoothing1` | `usize` | `35` (Python) | `>= 2` | First smoothing period (applied to ROC). `0` errors with `Error::PeriodZero`; `1` with `Error::InvalidPeriod`. |
|
||||
| `smoothing2` | `usize` | `20` (Python) | `>= 2` | Second smoothing period (applied to `10 · smoothed`). Same error rules. |
|
||||
|
||||
`smoothing = 1` is rejected because the smoothing constant `2 / 1 = 2`
|
||||
would exceed `1`. The Python binding defaults the pair to `(35, 20)` via
|
||||
`#[pyo3(signature = (smoothing1=35, smoothing2=20))]`. The `periods`
|
||||
property returns `(smoothing1, smoothing2)`.
|
||||
|
||||
## Inputs / Outputs
|
||||
|
||||
From `crates/wickra-core/src/indicators/pmo.rs`:
|
||||
|
||||
```rust
|
||||
impl Indicator for Pmo {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
// update(&mut self, input: f64) -> Option<f64>
|
||||
}
|
||||
```
|
||||
|
||||
A single `f64` close in, an `Option<f64>` out. Python maps this to
|
||||
`float | None` / `numpy.ndarray` (NaN warmup); Node to `number | null` /
|
||||
`Array<number>` (NaN warmup).
|
||||
|
||||
## Warmup
|
||||
|
||||
`Pmo::new(s1, s2).warmup_period() == 2`. The first ROC needs a previous
|
||||
price, and both `customEMA`s seed from their very first input, so the
|
||||
first non-`None` output lands on the **second** `update()`. Note this is
|
||||
the first *defined* value; the doubly-smoothed series only stabilises
|
||||
after many more bars, so treat early readings as unsettled.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- **Constant series.** A flat series gives `roc = 0` on every bar, so both
|
||||
smoothings stay at `0` and PMO is `0.0`
|
||||
(`constant_series_yields_zero` pins this).
|
||||
- **Zero previous price.** A ratio against a `0.0` prior price is
|
||||
undefined; `roc` is treated as `0` for that bar.
|
||||
- **NaN / infinity inputs.** Non-finite inputs are silently dropped; the
|
||||
smoothing chains are not advanced.
|
||||
- **Reset.** `pmo.reset()` clears the previous price and both EMAs.
|
||||
|
||||
## Examples
|
||||
|
||||
### Rust
|
||||
|
||||
```rust
|
||||
use wickra::{Indicator, Pmo};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut pmo = Pmo::new(35, 20)?;
|
||||
println!("{:?}", pmo.update(100.0)); // no previous price yet
|
||||
println!("{:?}", pmo.update(101.0)); // first defined PMO
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
None
|
||||
Some(10.0)
|
||||
```
|
||||
|
||||
The first `update` only records the price. The second produces
|
||||
`roc = 1.0%`; each `customEMA` seeds from its first input, so the inner
|
||||
EMA emits `1.0`, the `×10` scaling gives `10.0`, and the outer EMA seeds
|
||||
at `10.0` — hence `PMO = 10.0` on the first defined bar. Early values are
|
||||
seed artefacts: the double smoothing only settles after many more bars.
|
||||
This matches the `first_emission_at_second_update` test in
|
||||
`crates/wickra-core/src/indicators/pmo.rs`.
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import wickra as ta
|
||||
|
||||
pmo = ta.PMO() # (smoothing1=35, smoothing2=20)
|
||||
prices = 100.0 * 1.01 ** np.arange(120) # steady uptrend
|
||||
out = pmo.batch(prices)
|
||||
print("last > 0:", out[-1] > 0)
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
last > 0: True
|
||||
```
|
||||
|
||||
### Node
|
||||
|
||||
```javascript
|
||||
const ta = require('wickra');
|
||||
const pmo = new ta.PMO(35, 20);
|
||||
const prices = Array.from({ length: 120 }, (_, i) => 100 * 1.01 ** i);
|
||||
console.log('last:', pmo.batch(prices).at(-1));
|
||||
```
|
||||
|
||||
## Interpretation
|
||||
|
||||
`Pmo` is a smoothed momentum line. The DecisionPoint reads are: PMO
|
||||
crossing its zero line (momentum changing sign), PMO crossing its signal
|
||||
line (a 10-EMA of PMO — build it with `Chain`), and PMO turning up/down
|
||||
from an extreme. Because the rate of change is taken in percentage terms,
|
||||
PMO values *are* comparable across instruments — unlike raw
|
||||
[`Mom`](Indicator-Mom.md).
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
- **Trusting the first few values.** `warmup_period()` is `2`, but that is
|
||||
only the first *defined* output — the double smoothing needs many bars
|
||||
to settle. Discard the early ramp.
|
||||
- **Expecting a bundled signal line.** PMO here is the single PMO line;
|
||||
add `Ema(10)` via `Chain` for the signal.
|
||||
|
||||
## References
|
||||
|
||||
Carl Swenlin, DecisionPoint Price Momentum Oscillator. The
|
||||
`2 / period` "custom smoothing", the `×10` scaling and the conventional
|
||||
`(35, 20)` periods follow the published DecisionPoint definition.
|
||||
|
||||
## See also
|
||||
|
||||
- [Indicator-Roc.md](Indicator-Roc.md) — the raw rate of change PMO smooths.
|
||||
- [Indicator-Tsi.md](Indicator-Tsi.md) — another double-smoothed momentum
|
||||
oscillator.
|
||||
- [Indicator-Chaining.md](../Indicator-Chaining.md) — how to add the
|
||||
signal-line EMA.
|
||||
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
|
||||
@@ -0,0 +1,160 @@
|
||||
# TSI
|
||||
|
||||
> True Strength Index — a double-smoothed momentum oscillator that strips
|
||||
> noise while keeping a clean, zero-centred read on trend pressure.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Family | Momentum |
|
||||
| Sub-category | Unbounded oscillators |
|
||||
| Input type | `f64` (single close) |
|
||||
| Output type | `f64` |
|
||||
| Output range | roughly `[−100, 100]`, centred on zero |
|
||||
| Default parameters | `(long = 25, short = 13)` (Python) |
|
||||
| Warmup period | `long + short` |
|
||||
| Interpretation | Positive = net upward pressure, negative = net downward. |
|
||||
|
||||
## Formula
|
||||
|
||||
```
|
||||
momentum_t = price_t − price_{t−1}
|
||||
TSI = 100 · EMA_short(EMA_long(momentum)) / EMA_short(EMA_long(|momentum|))
|
||||
```
|
||||
|
||||
The 1-bar momentum and its absolute value are each smoothed twice — first
|
||||
with an EMA of length `long`, then with an EMA of length `short`. The
|
||||
ratio of the two double-smoothed series normalises the result: when every
|
||||
recent move is up, numerator and denominator are equal and TSI saturates
|
||||
at `+100`; when every move is down, at `−100`.
|
||||
|
||||
## Parameters
|
||||
|
||||
| Name | Type | Default | Valid range | Description |
|
||||
|---------|---------|---------------|-------------|-------------|
|
||||
| `long` | `usize` | `25` (Python) | `>= 1` | First (slow) smoothing length. `0` errors with `Error::PeriodZero`. |
|
||||
| `short` | `usize` | `13` (Python) | `>= 1` | Second (fast) smoothing length. `0` errors with `Error::PeriodZero`. |
|
||||
|
||||
The Python binding defaults the pair to `(25, 13)` via
|
||||
`#[pyo3(signature = (long=25, short=13))]`. Node and WASM take both
|
||||
explicitly. The `periods` property returns `(long, short)`.
|
||||
|
||||
## Inputs / Outputs
|
||||
|
||||
From `crates/wickra-core/src/indicators/tsi.rs`:
|
||||
|
||||
```rust
|
||||
impl Indicator for Tsi {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
// update(&mut self, input: f64) -> Option<f64>
|
||||
}
|
||||
```
|
||||
|
||||
A single `f64` close in, an `Option<f64>` out. Python maps this to
|
||||
`float | None` / `numpy.ndarray` (NaN warmup); Node to `number | null` /
|
||||
`Array<number>` (NaN warmup).
|
||||
|
||||
## Warmup
|
||||
|
||||
`Tsi::new(long, short).warmup_period() == long + short`. The momentum
|
||||
series starts on input 2; the SMA-seeded `long` EMA seeds at input
|
||||
`long + 1`, and the `short` EMA stacked on top seeds `short − 1` inputs
|
||||
later, so the first non-`None` output lands on input `long + short`.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- **Pure trend.** A monotone rising series saturates at `+100`, a falling
|
||||
one at `−100` — `|momentum|` equals `momentum` (or its negative), so the
|
||||
ratio is `±1` (`pure_uptrend_saturates_at_plus_100` /
|
||||
`pure_downtrend_saturates_at_minus_100` pin this).
|
||||
- **Constant series.** Every momentum is `0`; the `0 / 0` is guarded and
|
||||
the output is `0.0` (`constant_series_yields_zero` pins this).
|
||||
- **NaN / infinity inputs.** Non-finite inputs are silently dropped; the
|
||||
smoothing chains are not advanced.
|
||||
- **Reset.** `tsi.reset()` clears the previous price and all four EMAs.
|
||||
|
||||
## Examples
|
||||
|
||||
### Rust
|
||||
|
||||
```rust
|
||||
use wickra::{BatchExt, Indicator, Tsi};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let prices: Vec<f64> = (1..=40).map(f64::from).collect();
|
||||
let mut tsi = Tsi::new(5, 3)?;
|
||||
let out = tsi.batch(&prices);
|
||||
println!("warmup_period = {}", tsi.warmup_period());
|
||||
println!("last = {:?}", out.last().unwrap());
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
warmup_period = 8
|
||||
last = Some(100.0)
|
||||
```
|
||||
|
||||
A pure ramp has a constant `+1` momentum, so the double-smoothed ratio is
|
||||
exactly `1` and TSI saturates at `+100`. This matches the
|
||||
`pure_uptrend_saturates_at_plus_100` test in
|
||||
`crates/wickra-core/src/indicators/tsi.rs`.
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import wickra as ta
|
||||
|
||||
tsi = ta.TSI() # (long=25, short=13)
|
||||
prices = np.linspace(100.0, 80.0, 60) # steady downtrend
|
||||
out = tsi.batch(prices)
|
||||
print("last =", out[-1])
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
last = -100.0
|
||||
```
|
||||
|
||||
### Node
|
||||
|
||||
```javascript
|
||||
const ta = require('wickra');
|
||||
const tsi = new ta.TSI(25, 13);
|
||||
const prices = Array.from({ length: 60 }, (_, i) => 100 + i);
|
||||
console.log('last:', tsi.batch(prices).at(-1));
|
||||
```
|
||||
|
||||
## Interpretation
|
||||
|
||||
`Tsi` is a low-noise momentum oscillator. The standard signals are the
|
||||
zero-line cross (momentum changing sign), overbought/oversold extremes
|
||||
near `±25` for the default settings, and a signal-line cross — many
|
||||
traders overlay an EMA of TSI and trade the crossover. The double
|
||||
smoothing makes divergences unusually clean compared with raw momentum.
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
- **Reading it as a `[0, 100]` oscillator.** TSI is centred on zero and
|
||||
signed; `+25` is "strong up", not "mid-range".
|
||||
- **Under-budgeting warmup.** Warmup is `long + short` — for the default
|
||||
`(25, 13)` that is 38 bars.
|
||||
|
||||
## References
|
||||
|
||||
William Blau, "True Strength Index", *Technical Analysis of Stocks &
|
||||
Commodities* (1991), and *Momentum, Direction, and Divergence* (1995).
|
||||
The double-EMA-of-momentum definition here follows Blau's original.
|
||||
|
||||
## See also
|
||||
|
||||
- [Indicator-Mom.md](Indicator-Mom.md) — the raw momentum TSI smooths.
|
||||
- [Indicator-MacdIndicator.md](Indicator-MacdIndicator.md) — another
|
||||
EMA-difference momentum oscillator with a signal line.
|
||||
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
|
||||
Reference in New Issue
Block a user