From e24e7726ce35ad922d9cf5b584c4c8232613240e Mon Sep 17 00:00:00 2001 From: kingchenc Date: Fri, 22 May 2026 18:02:44 +0200 Subject: [PATCH] F4: add StochRSI and Ultimate Oscillator Completes the F4 family (Stochastic oscillators) end to end: - Rust core: stoch_rsi.rs (Stochastic Oscillator applied to the RSI series, bounded [0,100]) and ultimate_oscillator.rs (Larry Williams' weighted three-timeframe buying-pressure oscillator). Each with a full Indicator impl, runnable doctest and reference / saturation / bounds / warmup / reset / batch==streaming tests. - Python: PyStochRsi / PyUltimateOscillator PyO3 classes + module registration + .pyi stubs (defaults StochRSI=(14,14), UO=(7,14,28)). - Node: explicit StochRsiNode and UltimateOscillatorNode; index.d.ts and index.js updated. - WASM: WasmStochRsi via the scalar macro, explicit WasmUltimateOscillator. - Wiki: Indicator-StochRsi.md and Indicator-UltimateOscillator.md plus rows in Indicators-Overview.md and entries in Home.md. cargo fmt + clippy (core/wickra/data/wasm/node) clean; 278 core tests, 25 data tests and 39 doctests green. --- bindings/node/index.js | 4 +- bindings/node/src/lib.rs | 94 ++++++ bindings/python/python/wickra/__init__.pyi | 29 ++ bindings/python/src/lib.rs | 128 ++++++++ bindings/wasm/src/lib.rs | 39 +++ crates/wickra-core/src/indicators/mod.rs | 4 + .../wickra-core/src/indicators/stoch_rsi.rs | 227 +++++++++++++ .../src/indicators/ultimate_oscillator.rs | 306 ++++++++++++++++++ crates/wickra-core/src/lib.rs | 3 +- docs/wiki/Home.md | 2 + docs/wiki/Indicators-Overview.md | 4 +- .../indicators/momentum/Indicator-StochRsi.md | 165 ++++++++++ .../momentum/Indicator-UltimateOscillator.md | 179 ++++++++++ 13 files changed, 1181 insertions(+), 3 deletions(-) create mode 100644 crates/wickra-core/src/indicators/stoch_rsi.rs create mode 100644 crates/wickra-core/src/indicators/ultimate_oscillator.rs create mode 100644 docs/wiki/indicators/momentum/Indicator-StochRsi.md create mode 100644 docs/wiki/indicators/momentum/Indicator-UltimateOscillator.md diff --git a/bindings/node/index.js b/bindings/node/index.js index 4cdb91ab..2474e4b2 100644 --- a/bindings/node/index.js +++ b/bindings/node/index.js @@ -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, MOM, CMO, TSI, PMO, 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, StochRSI, UltimateOscillator, 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 @@ -331,6 +331,8 @@ module.exports.MOM = MOM module.exports.CMO = CMO module.exports.TSI = TSI module.exports.PMO = PMO +module.exports.StochRSI = StochRSI +module.exports.UltimateOscillator = UltimateOscillator module.exports.MACD = MACD module.exports.BollingerBands = BollingerBands module.exports.ATR = ATR diff --git a/bindings/node/src/lib.rs b/bindings/node/src/lib.rs index d308b742..8d91b254 100644 --- a/bindings/node/src/lib.rs +++ b/bindings/node/src/lib.rs @@ -1144,6 +1144,100 @@ impl PmoNode { // ============================== VWMA ============================== +// ============================== StochRSI ============================== + +#[napi(js_name = "StochRSI")] +pub struct StochRsiNode { + inner: wc::StochRsi, +} + +#[napi] +impl StochRsiNode { + #[napi(constructor)] + pub fn new(rsi_period: u32, stoch_period: u32) -> napi::Result { + Ok(Self { + inner: wc::StochRsi::new(rsi_period as usize, stoch_period as usize) + .map_err(map_err)?, + }) + } + #[napi] + pub fn update(&mut self, value: f64) -> Option { + self.inner.update(value) + } + #[napi] + pub fn batch(&mut self, prices: Vec) -> Vec { + 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 + } +} + +// ============================== Ultimate Oscillator ============================== + +#[napi(js_name = "UltimateOscillator")] +pub struct UltimateOscillatorNode { + inner: wc::UltimateOscillator, +} + +#[napi] +impl UltimateOscillatorNode { + #[napi(constructor)] + pub fn new(short: u32, mid: u32, long: u32) -> napi::Result { + Ok(Self { + inner: wc::UltimateOscillator::new(short as usize, mid as usize, long as usize) + .map_err(map_err)?, + }) + } + #[napi] + pub fn update(&mut self, high: f64, low: f64, close: f64) -> napi::Result> { + Ok(self.inner.update(cnd(high, low, close, 0.0)?)) + } + #[napi] + pub fn batch( + &mut self, + high: Vec, + low: Vec, + close: Vec, + ) -> napi::Result> { + if high.len() != low.len() || low.len() != close.len() { + return Err(NapiError::from_reason( + "high, low, close must be equal length".to_string(), + )); + } + let mut out = Vec::with_capacity(high.len()); + for i in 0..high.len() { + out.push( + self.inner + .update(cnd(high[i], low[i], close[i], 0.0)?) + .unwrap_or(f64::NAN), + ); + } + Ok(out) + } + #[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 + } +} + #[napi(js_name = "VWMA")] pub struct VwmaNode { inner: wc::Vwma, diff --git a/bindings/python/python/wickra/__init__.pyi b/bindings/python/python/wickra/__init__.pyi index 2a8a2922..15739908 100644 --- a/bindings/python/python/wickra/__init__.pyi +++ b/bindings/python/python/wickra/__init__.pyi @@ -76,6 +76,35 @@ class TRIMA: @property def value(self) -> Optional[float]: ... +class StochRSI: + def __init__(self, rsi_period: int = 14, stoch_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 periods(self) -> Tuple[int, int]: ... + @property + def value(self) -> Optional[float]: ... + +class UltimateOscillator: + def __init__(self, short: int = 7, mid: int = 14, long: int = 28) -> None: ... + def update(self, candle: CandleLike) -> Optional[float]: ... + def batch( + self, + high: NDArray[np.float64], + low: NDArray[np.float64], + close: 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, int]: ... + @property + def value(self) -> Optional[float]: ... + class MOM: def __init__(self, period: int = 10) -> None: ... def update(self, value: float) -> Optional[float]: ... diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 3397d111..49e78946 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -1519,6 +1519,132 @@ impl PyAroon { } } +// ============================== StochRSI ============================== + +#[pyclass(name = "StochRSI", module = "wickra._wickra")] +#[derive(Clone)] +struct PyStochRsi { + inner: wc::StochRsi, +} + +#[pymethods] +impl PyStochRsi { + #[new] + #[pyo3(signature = (rsi_period=14, stoch_period=14))] + fn new(rsi_period: usize, stoch_period: usize) -> PyResult { + Ok(Self { + inner: wc::StochRsi::new(rsi_period, stoch_period).map_err(map_err)?, + }) + } + fn update(&mut self, value: f64) -> Option { + self.inner.update(value) + } + fn batch<'py>( + &mut self, + py: Python<'py>, + prices: PyReadonlyArray1<'py, f64>, + ) -> PyResult>> { + 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 { + 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 (r, s) = self.inner.periods(); + format!("StochRSI(rsi_period={r}, stoch_period={s})") + } +} + +// ============================== Ultimate Oscillator ============================== + +#[pyclass(name = "UltimateOscillator", module = "wickra._wickra")] +#[derive(Clone)] +struct PyUltimateOscillator { + inner: wc::UltimateOscillator, +} + +#[pymethods] +impl PyUltimateOscillator { + #[new] + #[pyo3(signature = (short=7, mid=14, long=28))] + fn new(short: usize, mid: usize, long: usize) -> PyResult { + Ok(Self { + inner: wc::UltimateOscillator::new(short, mid, long).map_err(map_err)?, + }) + } + fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult> { + let c = extract_candle(candle)?; + Ok(self.inner.update(c)) + } + /// Batch over numpy columns: high, low, close (all 1-D, equal length). + fn batch<'py>( + &mut self, + py: Python<'py>, + high: PyReadonlyArray1<'py, f64>, + low: PyReadonlyArray1<'py, f64>, + close: PyReadonlyArray1<'py, f64>, + ) -> PyResult>> { + let h = high + .as_slice() + .map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?; + let l = low + .as_slice() + .map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?; + let c = close + .as_slice() + .map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?; + if h.len() != l.len() || l.len() != c.len() { + return Err(PyValueError::new_err( + "high, low, close must be equal length", + )); + } + let mut out = Vec::with_capacity(h.len()); + for i in 0..h.len() { + let candle = wc::Candle::new(c[i], h[i], l[i], c[i], 0.0, 0).map_err(map_err)?; + out.push(self.inner.update(candle).unwrap_or(f64::NAN)); + } + Ok(out.into_pyarray_bound(py)) + } + #[getter] + fn periods(&self) -> (usize, usize, usize) { + self.inner.periods() + } + #[getter] + fn value(&self) -> Option { + 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 (s, m, l) = self.inner.periods(); + format!("UltimateOscillator(short={s}, mid={m}, long={l})") + } +} + // ============================== MOM ============================== #[pyclass(name = "MOM", module = "wickra._wickra")] @@ -2052,5 +2178,7 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; Ok(()) } diff --git a/bindings/wasm/src/lib.rs b/bindings/wasm/src/lib.rs index e88ca529..62ee94a8 100644 --- a/bindings/wasm/src/lib.rs +++ b/bindings/wasm/src/lib.rs @@ -83,6 +83,7 @@ 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); +wasm_scalar_indicator!(WasmStochRsi, "StochRSI", wc::StochRsi, rsi_period: usize, stoch_period: usize); // ---------- KAMA (three params) ---------- @@ -330,6 +331,44 @@ impl WasmObv { } } +#[wasm_bindgen(js_name = UltimateOscillator)] +pub struct WasmUltimateOscillator { + inner: wc::UltimateOscillator, +} + +#[wasm_bindgen(js_class = UltimateOscillator)] +impl WasmUltimateOscillator { + #[wasm_bindgen(constructor)] + pub fn new(short: usize, mid: usize, long: usize) -> Result { + Ok(Self { + inner: wc::UltimateOscillator::new(short, mid, long).map_err(map_err)?, + }) + } + pub fn update(&mut self, high: f64, low: f64, close: f64) -> Result, JsError> { + let c = make_candle(high, low, close, 0.0)?; + Ok(self.inner.update(c)) + } + pub fn batch( + &mut self, + high: &[f64], + low: &[f64], + close: &[f64], + ) -> Result { + if high.len() != low.len() || low.len() != close.len() { + return Err(JsError::new("high, low, close must be equal length")); + } + let mut out = Vec::with_capacity(high.len()); + for i in 0..high.len() { + let c = make_candle(high[i], low[i], close[i], 0.0)?; + out.push(self.inner.update(c).unwrap_or(f64::NAN)); + } + Ok(Float64Array::from(out.as_slice())) + } + pub fn reset(&mut self) { + self.inner.reset(); + } +} + #[wasm_bindgen(js_name = VWMA)] pub struct WasmVwma { inner: wc::Vwma, diff --git a/crates/wickra-core/src/indicators/mod.rs b/crates/wickra-core/src/indicators/mod.rs index 1f530f05..31abb838 100644 --- a/crates/wickra-core/src/indicators/mod.rs +++ b/crates/wickra-core/src/indicators/mod.rs @@ -27,12 +27,14 @@ mod roc; mod rsi; mod sma; mod smma; +mod stoch_rsi; mod stochastic; mod t3; mod tema; mod trima; mod trix; mod tsi; +mod ultimate_oscillator; mod vwap; mod vwma; mod williams_r; @@ -62,12 +64,14 @@ pub use roc::Roc; pub use rsi::Rsi; pub use sma::Sma; pub use smma::Smma; +pub use stoch_rsi::StochRsi; pub use stochastic::{Stochastic, StochasticOutput}; pub use t3::T3; pub use tema::Tema; pub use trima::Trima; pub use trix::Trix; pub use tsi::Tsi; +pub use ultimate_oscillator::UltimateOscillator; pub use vwap::{RollingVwap, Vwap}; pub use vwma::Vwma; pub use williams_r::WilliamsR; diff --git a/crates/wickra-core/src/indicators/stoch_rsi.rs b/crates/wickra-core/src/indicators/stoch_rsi.rs new file mode 100644 index 00000000..63d4c7c6 --- /dev/null +++ b/crates/wickra-core/src/indicators/stoch_rsi.rs @@ -0,0 +1,227 @@ +//! Stochastic RSI. + +use std::collections::VecDeque; + +use crate::error::{Error, Result}; +use crate::traits::Indicator; + +use super::Rsi; + +/// Stochastic RSI — the Stochastic Oscillator formula applied to the RSI series +/// instead of to price. +/// +/// RSI itself rarely reaches its `[0, 100]` extremes, so it spends most of its +/// life bunched in the middle of the range. `StochRSI` re-scales it: it reports +/// where the *current* RSI sits within its own high/low range over the last +/// `stoch_period` bars, which makes overbought/oversold turns far easier to +/// see. +/// +/// ```text +/// StochRSI = 100 · (RSI − min(RSI, stoch_period)) / (max(RSI, …) − min(RSI, …)) +/// ``` +/// +/// The output is bounded in `[0, 100]`. A flat RSI window (zero range) is +/// reported as the neutral `50.0`, matching the [`Stochastic`](crate::Stochastic) +/// convention. +/// +/// # Example +/// +/// ``` +/// use wickra_core::{Indicator, StochRsi}; +/// +/// let mut indicator = StochRsi::new(14, 14).unwrap(); +/// let mut last = None; +/// for i in 0..80 { +/// last = indicator.update(100.0 + (f64::from(i) * 0.5).sin() * 10.0); +/// } +/// assert!(last.is_some()); +/// ``` +#[derive(Debug, Clone)] +pub struct StochRsi { + rsi_period: usize, + stoch_period: usize, + rsi: Rsi, + /// Rolling window of the last `stoch_period` RSI values. + window: VecDeque, + last: Option, +} + +impl StochRsi { + /// Construct a new `StochRSI` with the RSI period and the stochastic lookback. + /// + /// # Errors + /// + /// Returns [`Error::PeriodZero`] if either period is `0`. + pub fn new(rsi_period: usize, stoch_period: usize) -> Result { + if rsi_period == 0 || stoch_period == 0 { + return Err(Error::PeriodZero); + } + Ok(Self { + rsi_period, + stoch_period, + rsi: Rsi::new(rsi_period)?, + window: VecDeque::with_capacity(stoch_period), + last: None, + }) + } + + /// The `(rsi_period, stoch_period)` pair. + pub const fn periods(&self) -> (usize, usize) { + (self.rsi_period, self.stoch_period) + } + + /// Current value if available. + pub const fn value(&self) -> Option { + self.last + } +} + +impl Indicator for StochRsi { + type Input = f64; + type Output = f64; + + fn update(&mut self, input: f64) -> Option { + if !input.is_finite() { + // Non-finite input is ignored; state is left untouched. + return self.last; + } + let rsi_value = self.rsi.update(input)?; + + if self.window.len() == self.stoch_period { + self.window.pop_front(); + } + self.window.push_back(rsi_value); + if self.window.len() < self.stoch_period { + return None; + } + + let max = self + .window + .iter() + .copied() + .fold(f64::NEG_INFINITY, f64::max); + let min = self.window.iter().copied().fold(f64::INFINITY, f64::min); + let range = max - min; + let stoch = if range == 0.0 { + // Flat RSI window: report the neutral midpoint. + 50.0 + } else { + 100.0 * (rsi_value - min) / range + }; + self.last = Some(stoch); + Some(stoch) + } + + fn reset(&mut self) { + self.rsi.reset(); + self.window.clear(); + self.last = None; + } + + fn warmup_period(&self) -> usize { + // RSI emits its first value at input `rsi_period + 1`; the stochastic + // window then needs `stoch_period` RSI values. + self.rsi_period + self.stoch_period + } + + fn is_ready(&self) -> bool { + self.last.is_some() + } + + fn name(&self) -> &'static str { + "StochRSI" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::traits::BatchExt; + use approx::assert_relative_eq; + + #[test] + fn new_rejects_zero_period() { + assert!(matches!(StochRsi::new(0, 14), Err(Error::PeriodZero))); + assert!(matches!(StochRsi::new(14, 0), Err(Error::PeriodZero))); + } + + #[test] + fn first_emission_at_warmup_period() { + let mut sr = StochRsi::new(5, 4).unwrap(); + assert_eq!(sr.warmup_period(), 9); + let prices: Vec = (1..=40) + .map(|i| 100.0 + (f64::from(i) * 0.6).sin() * 8.0) + .collect(); + let out = sr.batch(&prices); + for v in out.iter().take(8) { + assert!(v.is_none()); + } + assert!(out[8].is_some()); + } + + #[test] + fn flat_rsi_window_yields_50() { + // A constant price series gives a constant RSI (50.0), so the StochRSI + // window has zero range and reports the neutral midpoint. + let mut sr = StochRsi::new(5, 4).unwrap(); + let out = sr.batch(&[100.0; 40]); + for v in out.iter().skip(9).flatten() { + assert_relative_eq!(*v, 50.0, epsilon = 1e-12); + } + } + + #[test] + fn pure_uptrend_yields_50() { + // A pure uptrend pins RSI at 100, so its window is again flat. + let mut sr = StochRsi::new(5, 4).unwrap(); + let out = sr.batch(&(1..=40).map(f64::from).collect::>()); + for v in out.iter().skip(9).flatten() { + assert_relative_eq!(*v, 50.0, epsilon = 1e-12); + } + } + + #[test] + fn output_stays_within_0_100() { + let mut sr = StochRsi::new(14, 14).unwrap(); + let prices: Vec = (1..=200) + .map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 15.0 + (f64::from(i) * 0.07).cos() * 6.0) + .collect(); + for v in sr.batch(&prices).into_iter().flatten() { + assert!((0.0..=100.0).contains(&v), "StochRSI out of range: {v}"); + } + } + + #[test] + fn ignores_non_finite_input() { + let mut sr = StochRsi::new(5, 4).unwrap(); + let prices: Vec = (1..=40) + .map(|i| 100.0 + (f64::from(i) * 0.6).sin() * 8.0) + .collect(); + let out = sr.batch(&prices); + let last = *out.last().unwrap(); + assert!(last.is_some()); + assert_eq!(sr.update(f64::NAN), last); + assert_eq!(sr.update(f64::INFINITY), last); + } + + #[test] + fn reset_clears_state() { + let mut sr = StochRsi::new(5, 4).unwrap(); + sr.batch(&(1..=40).map(f64::from).collect::>()); + assert!(sr.is_ready()); + sr.reset(); + assert!(!sr.is_ready()); + assert_eq!(sr.update(1.0), None); + } + + #[test] + fn batch_equals_streaming() { + let prices: Vec = (1..=120) + .map(|i| 100.0 + (f64::from(i) * 0.25).sin() * 12.0) + .collect(); + let batch = StochRsi::new(14, 14).unwrap().batch(&prices); + let mut b = StochRsi::new(14, 14).unwrap(); + let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect(); + assert_eq!(batch, streamed); + } +} diff --git a/crates/wickra-core/src/indicators/ultimate_oscillator.rs b/crates/wickra-core/src/indicators/ultimate_oscillator.rs new file mode 100644 index 00000000..30a76d3b --- /dev/null +++ b/crates/wickra-core/src/indicators/ultimate_oscillator.rs @@ -0,0 +1,306 @@ +//! Ultimate Oscillator. + +use std::collections::VecDeque; + +use crate::error::{Error, Result}; +use crate::ohlcv::Candle; +use crate::traits::Indicator; + +/// Ultimate Oscillator — Larry Williams' three-timeframe momentum oscillator. +/// +/// A single-timeframe oscillator can give false divergence signals when the +/// chosen lookback does not match the swing being measured. The Ultimate +/// Oscillator blends *three* lookbacks into one bounded `[0, 100]` reading, +/// weighting the fastest most heavily: +/// +/// ```text +/// true_low_t = min(low_t, close_{t−1}) +/// BP_t = close_t − true_low_t (buying pressure) +/// TR_t = max(high_t, close_{t−1}) − true_low_t (true range) +/// avg_n = Σ BP over n / Σ TR over n +/// UO = 100 · (4·avg_short + 2·avg_mid + avg_long) / 7 +/// ``` +/// +/// The conventional periods are `7`, `14` and `28`. A fully flat window (zero +/// true range) contributes the neutral ratio `0.5`, so a flat market reads +/// `50`. +/// +/// # Example +/// +/// ``` +/// use wickra_core::{Candle, Indicator, UltimateOscillator}; +/// +/// let mut indicator = UltimateOscillator::new(7, 14, 28).unwrap(); +/// let mut last = None; +/// for i in 0..80 { +/// let p = 100.0 + f64::from(i); +/// let candle = Candle::new(p, p + 1.0, p - 1.0, p, 10.0, i64::from(i)).unwrap(); +/// last = indicator.update(candle); +/// } +/// assert!(last.is_some()); +/// ``` +#[derive(Debug, Clone)] +pub struct UltimateOscillator { + short: usize, + mid: usize, + long: usize, + longest: usize, + prev_close: Option, + /// Rolling window of `(buying_pressure, true_range)` pairs. + window: VecDeque<(f64, f64)>, + sum_bp_short: f64, + sum_tr_short: f64, + sum_bp_mid: f64, + sum_tr_mid: f64, + sum_bp_long: f64, + sum_tr_long: f64, + pairs: usize, + last: Option, +} + +impl UltimateOscillator { + /// Construct a new Ultimate Oscillator with the three lookback periods. + /// + /// # Errors + /// + /// Returns [`Error::PeriodZero`] if any period is `0`. + pub fn new(short: usize, mid: usize, long: usize) -> Result { + if short == 0 || mid == 0 || long == 0 { + return Err(Error::PeriodZero); + } + let longest = short.max(mid).max(long); + Ok(Self { + short, + mid, + long, + longest, + prev_close: None, + window: VecDeque::with_capacity(longest + 1), + sum_bp_short: 0.0, + sum_tr_short: 0.0, + sum_bp_mid: 0.0, + sum_tr_mid: 0.0, + sum_bp_long: 0.0, + sum_tr_long: 0.0, + pairs: 0, + last: None, + }) + } + + /// Classic Ultimate Oscillator: periods `7`, `14`, `28`. + pub fn classic() -> Self { + Self::new(7, 14, 28).expect("classic Ultimate Oscillator periods are valid") + } + + /// The `(short, mid, long)` periods. + pub const fn periods(&self) -> (usize, usize, usize) { + (self.short, self.mid, self.long) + } + + /// Current value if available. + pub const fn value(&self) -> Option { + self.last + } +} + +impl Indicator for UltimateOscillator { + type Input = Candle; + type Output = f64; + + fn update(&mut self, candle: Candle) -> Option { + let Some(prev_close) = self.prev_close else { + // The first bar has no previous close, so no BP/TR can be formed. + self.prev_close = Some(candle.close); + return None; + }; + self.prev_close = Some(candle.close); + + let true_low = candle.low.min(prev_close); + let bp = candle.close - true_low; + let tr = candle.high.max(prev_close) - true_low; + + self.window.push_back((bp, tr)); + let n = self.window.len(); + self.sum_bp_short += bp; + self.sum_tr_short += tr; + self.sum_bp_mid += bp; + self.sum_tr_mid += tr; + self.sum_bp_long += bp; + self.sum_tr_long += tr; + if n > self.short { + let (b, t) = self.window[n - 1 - self.short]; + self.sum_bp_short -= b; + self.sum_tr_short -= t; + } + if n > self.mid { + let (b, t) = self.window[n - 1 - self.mid]; + self.sum_bp_mid -= b; + self.sum_tr_mid -= t; + } + if n > self.long { + let (b, t) = self.window[n - 1 - self.long]; + self.sum_bp_long -= b; + self.sum_tr_long -= t; + } + if self.window.len() > self.longest { + self.window.pop_front(); + } + + self.pairs += 1; + if self.pairs < self.longest { + return None; + } + + let avg = |bp_sum: f64, tr_sum: f64| { + if tr_sum == 0.0 { + // A fully flat window has no range; contribute the midpoint. + 0.5 + } else { + bp_sum / tr_sum + } + }; + let avg_short = avg(self.sum_bp_short, self.sum_tr_short); + let avg_mid = avg(self.sum_bp_mid, self.sum_tr_mid); + let avg_long = avg(self.sum_bp_long, self.sum_tr_long); + let uo = 100.0 * (4.0 * avg_short + 2.0 * avg_mid + avg_long) / 7.0; + self.last = Some(uo); + Some(uo) + } + + fn reset(&mut self) { + self.prev_close = None; + self.window.clear(); + self.sum_bp_short = 0.0; + self.sum_tr_short = 0.0; + self.sum_bp_mid = 0.0; + self.sum_tr_mid = 0.0; + self.sum_bp_long = 0.0; + self.sum_tr_long = 0.0; + self.pairs = 0; + self.last = None; + } + + fn warmup_period(&self) -> usize { + // The first BP/TR pair needs a previous close, then the longest window + // must fill. + self.longest + 1 + } + + fn is_ready(&self) -> bool { + self.last.is_some() + } + + fn name(&self) -> &'static str { + "UltimateOscillator" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::traits::BatchExt; + use approx::assert_relative_eq; + + /// Build a flat candle (open = high = low = close). + fn flat(price: f64, ts: i64) -> Candle { + Candle::new(price, price, price, price, 1.0, ts).unwrap() + } + + #[test] + fn new_rejects_zero_period() { + assert!(matches!( + UltimateOscillator::new(0, 14, 28), + Err(Error::PeriodZero) + )); + assert!(matches!( + UltimateOscillator::new(7, 0, 28), + Err(Error::PeriodZero) + )); + assert!(matches!( + UltimateOscillator::new(7, 14, 0), + Err(Error::PeriodZero) + )); + } + + #[test] + fn first_emission_at_warmup_period() { + let mut uo = UltimateOscillator::new(2, 3, 5).unwrap(); + assert_eq!(uo.warmup_period(), 6); + let candles: Vec = (0..20).map(|i| flat(100.0 + i as f64, i)).collect(); + let out = uo.batch(&candles); + for v in out.iter().take(5) { + assert!(v.is_none()); + } + assert!(out[5].is_some()); + } + + #[test] + fn pure_uptrend_saturates_at_100() { + // Each flat candle closes higher: BP == TR every bar, so every ratio + // is 1 and UO is 100. + let mut uo = UltimateOscillator::new(2, 3, 5).unwrap(); + let candles: Vec = (0..30).map(|i| flat(100.0 + i as f64, i)).collect(); + for v in uo.batch(&candles).into_iter().flatten() { + assert_relative_eq!(v, 100.0, epsilon = 1e-9); + } + } + + #[test] + fn pure_downtrend_saturates_at_0() { + // Each flat candle closes lower: BP is 0 every bar, so UO is 0. + let mut uo = UltimateOscillator::new(2, 3, 5).unwrap(); + let candles: Vec = (0..30).map(|i| flat(100.0 - i as f64, i)).collect(); + for v in uo.batch(&candles).into_iter().flatten() { + assert_relative_eq!(v, 0.0, epsilon = 1e-9); + } + } + + #[test] + fn flat_market_reads_50() { + // Every bar identical: zero true range everywhere -> neutral 50. + let mut uo = UltimateOscillator::new(2, 3, 5).unwrap(); + let candles: Vec = (0..30).map(|i| flat(100.0, i)).collect(); + for v in uo.batch(&candles).into_iter().flatten() { + assert_relative_eq!(v, 50.0, epsilon = 1e-9); + } + } + + #[test] + fn output_stays_within_0_100() { + let mut uo = UltimateOscillator::classic(); + let candles: Vec = (0..200) + .map(|i| { + let mid = 100.0 + (i as f64 * 0.2).sin() * 12.0; + Candle::new(mid, mid + 3.0, mid - 3.0, mid + 1.0, 10.0, i).unwrap() + }) + .collect(); + for v in uo.batch(&candles).into_iter().flatten() { + assert!((0.0..=100.0).contains(&v), "UO out of range: {v}"); + } + } + + #[test] + fn reset_clears_state() { + let mut uo = UltimateOscillator::new(2, 3, 5).unwrap(); + let candles: Vec = (0..20).map(|i| flat(100.0 + i as f64, i)).collect(); + uo.batch(&candles); + assert!(uo.is_ready()); + uo.reset(); + assert!(!uo.is_ready()); + assert_eq!(uo.update(candles[0]), None); + } + + #[test] + fn batch_equals_streaming() { + let candles: Vec = (0..120) + .map(|i| { + let mid = 100.0 + (i as f64 * 0.3).sin() * 10.0; + Candle::new(mid, mid + 2.0, mid - 2.0, mid + 0.5, 10.0, i).unwrap() + }) + .collect(); + let batch = UltimateOscillator::classic().batch(&candles); + let mut b = UltimateOscillator::classic(); + let streamed: Vec<_> = candles.iter().map(|c| b.update(*c)).collect(); + assert_eq!(batch, streamed); + } +} diff --git a/crates/wickra-core/src/lib.rs b/crates/wickra-core/src/lib.rs index 22a4d49a..9d464b80 100644 --- a/crates/wickra-core/src/lib.rs +++ b/crates/wickra-core/src/lib.rs @@ -47,7 +47,8 @@ pub use indicators::{ Adx, AdxOutput, Aroon, AroonOutput, Atr, AwesomeOscillator, BollingerBands, BollingerOutput, 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, + StochRsi, Stochastic, StochasticOutput, Tema, Trima, Trix, Tsi, UltimateOscillator, Vwap, Vwma, + WilliamsR, Wma, Zlema, T3, }; pub use ohlcv::{Candle, Tick}; pub use traits::{BatchExt, Chain, Indicator}; diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 7fa78a23..62f86737 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -102,6 +102,8 @@ Rust / Python / Node examples. They are grouped by family, mirroring the - [Indicator-Cmo.md](indicators/momentum/Indicator-Cmo.md) - [Indicator-Tsi.md](indicators/momentum/Indicator-Tsi.md) - [Indicator-Pmo.md](indicators/momentum/Indicator-Pmo.md) +- [Indicator-StochRsi.md](indicators/momentum/Indicator-StochRsi.md) +- [Indicator-UltimateOscillator.md](indicators/momentum/Indicator-UltimateOscillator.md) **Volatility** — envelope width and per-bar dispersion measures. diff --git a/docs/wiki/Indicators-Overview.md b/docs/wiki/Indicators-Overview.md index 408ec47d..d10d89ba 100644 --- a/docs/wiki/Indicators-Overview.md +++ b/docs/wiki/Indicators-Overview.md @@ -1,6 +1,6 @@ # Indicators Overview -Wickra ships 34 indicators, organised in source under the four classical +Wickra ships 36 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 @@ -84,6 +84,8 @@ mental model, though the exact thresholds differ in the literature. | `Stochastic` | `%K = (close − low_n)/(high_n − low_n) × 100`, smoothed into `%D`. | `Candle` | `(k, d)` | each in `[0, 100]` | `(k_period=14, d_period=3)` (Python) | `k_period + d_period − 1` | [Indicator-Stochastic.md](indicators/momentum/Indicator-Stochastic.md) | | `Mfi` | "Volume-weighted RSI": Wilder smoothing of money-flow ratios. | `Candle` | `f64` | `[0, 100]` | `period = 14` (Python) | `period` | [Indicator-Mfi.md](indicators/momentum/Indicator-Mfi.md) | | `Aroon` | Bars-since-high and bars-since-low scaled to `[0, 100]`. | `Candle` | `(up, down)` | each in `[0, 100]` | `period = 14` (Python) | `period + 1` | [Indicator-Aroon.md](indicators/momentum/Indicator-Aroon.md) | +| `StochRsi` | Stochastic Oscillator applied to the RSI series; sharpens RSI extremes. | `f64` | `f64` | `[0, 100]` | `(rsi_period=14, stoch_period=14)` (Python) | `rsi_period + stoch_period` | [Indicator-StochRsi.md](indicators/momentum/Indicator-StochRsi.md) | +| `UltimateOscillator` | Larry Williams' weighted three-timeframe buying-pressure oscillator. | `Candle` | `f64` | `[0, 100]` | `(short=7, mid=14, long=28)` (Python) | `max(short,mid,long) + 1` | [Indicator-UltimateOscillator.md](indicators/momentum/Indicator-UltimateOscillator.md) | ### Unbounded oscillators diff --git a/docs/wiki/indicators/momentum/Indicator-StochRsi.md b/docs/wiki/indicators/momentum/Indicator-StochRsi.md new file mode 100644 index 00000000..6387e723 --- /dev/null +++ b/docs/wiki/indicators/momentum/Indicator-StochRsi.md @@ -0,0 +1,165 @@ +# StochRSI + +> Stochastic RSI — the Stochastic Oscillator formula applied to the RSI +> series, sharpening RSI's overbought/oversold turns. + +## Quick reference + +| Field | Value | +|-------|-------| +| Family | Momentum | +| Sub-category | Bounded oscillators (0 … 100) | +| Input type | `f64` (single close) | +| Output type | `f64` | +| Output range | `[0, 100]` | +| Default parameters | `(rsi_period = 14, stoch_period = 14)` (Python) | +| Warmup period | `rsi_period + stoch_period` | +| Interpretation | Where RSI sits in its own recent range; near `0`/`100` = extremes. | + +## Formula + +``` +RSI_t = Rsi(rsi_period) of price +StochRSI = 100 · (RSI_t − min(RSI, stoch_period)) / (max(RSI, …) − min(RSI, …)) +``` + +RSI rarely visits its `0`/`100` extremes — it spends most of its life +bunched around the middle. StochRSI re-normalises it: it asks where the +*current* RSI sits within its own high/low range over the last +`stoch_period` bars. The result swings the full `[0, 100]` width far more +often than raw RSI, so reversals are easier to spot. + +## Parameters + +| Name | Type | Default | Valid range | Description | +|----------------|---------|---------------|-------------|-------------| +| `rsi_period` | `usize` | `14` (Python) | `>= 1` | Period of the underlying RSI. `0` errors with `Error::PeriodZero`. | +| `stoch_period` | `usize` | `14` (Python) | `>= 1` | Lookback for the high/low range of RSI. `0` errors with `Error::PeriodZero`. | + +The Python binding defaults the pair to `(14, 14)` via +`#[pyo3(signature = (rsi_period=14, stoch_period=14))]`. Node and WASM +take both explicitly. The `periods` property returns +`(rsi_period, stoch_period)`. + +## Inputs / Outputs + +From `crates/wickra-core/src/indicators/stoch_rsi.rs`: + +```rust +impl Indicator for StochRsi { + type Input = f64; + type Output = f64; + // update(&mut self, input: f64) -> Option +} +``` + +A single `f64` close in, an `Option` out. Python maps this to +`float | None` / `numpy.ndarray` (NaN warmup); Node to `number | null` / +`Array` (NaN warmup). + +## Warmup + +`StochRsi::new(rsi_period, stoch_period).warmup_period() +== rsi_period + stoch_period`. The inner RSI emits its first value on +input `rsi_period + 1`; the stochastic window then needs `stoch_period` +RSI values, so the first non-`None` output lands on input +`rsi_period + stoch_period`. + +## Edge cases + +- **Flat RSI window.** When every RSI value in the window is equal — for + example a constant price (RSI pinned at `50`) or a pure trend (RSI + pinned at `100`) — the range is zero and StochRSI reports the neutral + `50.0` (`flat_rsi_window_yields_50` and `pure_uptrend_yields_50` pin + this). +- **Bounds.** The output is always within `[0, 100]` + (`output_stays_within_0_100` pins this). +- **NaN / infinity inputs.** Non-finite inputs are silently dropped; the + RSI and the window are not advanced. +- **Reset.** `stoch_rsi.reset()` clears the inner RSI and the window. + +## Examples + +### Rust + +```rust +use wickra::{BatchExt, Indicator, StochRsi}; + +fn main() -> Result<(), Box> { + let mut sr = StochRsi::new(14, 14)?; + let prices: Vec = (1..=60) + .map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 10.0) + .collect(); + let out = sr.batch(&prices); + println!("warmup_period = {}", sr.warmup_period()); + println!("ready values: {}", out.iter().flatten().count()); + Ok(()) +} +``` + +Output: + +``` +warmup_period = 28 +ready values: 33 +``` + +The first 27 inputs return `None`; from input 28 onward every output is a +defined `[0, 100]` value. + +### Python + +```python +import numpy as np +import wickra as ta + +sr = ta.StochRSI() # (rsi_period=14, stoch_period=14) +prices = np.full(40, 100.0) # constant series +print(sr.batch(prices)[-1]) # flat RSI window -> neutral 50 +``` + +Output: + +``` +50.0 +``` + +### Node + +```javascript +const ta = require('wickra'); +const sr = new ta.StochRSI(14, 14); +const prices = Array.from({ length: 60 }, (_, i) => 100 + Math.sin(i * 0.3) * 10); +console.log('warmupPeriod:', sr.warmupPeriod()); +``` + +## Interpretation + +`StochRsi` is read like any `[0, 100]` oscillator, but with tighter +thresholds because it saturates so readily: above `80` is overbought, +below `20` oversold, and the `50` line is the midpoint. Because it is two +oscillators deep, it is *fast and noisy* — excellent for spotting +short-term turns, poor as a standalone trend filter. Many traders smooth +it further (an SMA of StochRSI) and trade the crossover. + +## Common pitfalls + +- **Using it as a trend filter.** `StochRsi` whipsaws; confirm with a + slower indicator before acting on a raw threshold cross. +- **Forgetting the stacked warmup.** Warmup is `rsi_period + stoch_period` + — for the default `(14, 14)` that is 28 bars. +- **Expecting raw-RSI values.** `StochRsi` is a *position within range*, + not RSI itself; the two are not interchangeable. + +## References + +Tushar Chande and Stanley Kroll, *The New Technical Trader* (1994). The +implementation is the standard Stochastic-of-RSI; the flat-window +convention (`50`) matches this library's [`Stochastic`](Indicator-Stochastic.md). + +## See also + +- [Indicator-Rsi.md](Indicator-Rsi.md) — the underlying oscillator. +- [Indicator-Stochastic.md](Indicator-Stochastic.md) — the same formula on + price instead of RSI. +- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy. diff --git a/docs/wiki/indicators/momentum/Indicator-UltimateOscillator.md b/docs/wiki/indicators/momentum/Indicator-UltimateOscillator.md new file mode 100644 index 00000000..d2cfb999 --- /dev/null +++ b/docs/wiki/indicators/momentum/Indicator-UltimateOscillator.md @@ -0,0 +1,179 @@ +# UltimateOscillator + +> Ultimate Oscillator — Larry Williams' momentum oscillator that blends +> three lookback periods into one bounded `[0, 100]` reading. + +## Quick reference + +| Field | Value | +|-------|-------| +| Family | Momentum | +| Sub-category | Bounded oscillators (0 … 100) | +| Input type | `Candle` (uses `high`, `low`, `close`) | +| Output type | `f64` | +| Output range | `[0, 100]` | +| Default parameters | `(short = 7, mid = 14, long = 28)` (Python) | +| Warmup period | `max(short, mid, long) + 1` | +| Interpretation | Weighted three-timeframe buying pressure; `50` is neutral. | + +## Formula + +``` +true_low_t = min(low_t, close_{t−1}) +BP_t = close_t − true_low_t (buying pressure) +TR_t = max(high_t, close_{t−1}) − true_low_t (true range) +avg_n = Σ BP over n / Σ TR over n +UO = 100 · (4·avg_short + 2·avg_mid + avg_long) / 7 +``` + +A single-timeframe momentum oscillator can show false divergences when +its lookback does not match the swing being measured. The Ultimate +Oscillator averages buying pressure over *three* windows and weights the +fastest (`4×`) above the medium (`2×`) and slow (`1×`), which damps those +false signals while keeping the response quick. + +## Parameters + +| Name | Type | Default | Valid range | Description | +|---------|---------|---------------|-------------|-------------| +| `short` | `usize` | `7` (Python) | `>= 1` | Fast lookback (weight `4`). `0` errors with `Error::PeriodZero`. | +| `mid` | `usize` | `14` (Python) | `>= 1` | Medium lookback (weight `2`). | +| `long` | `usize` | `28` (Python) | `>= 1` | Slow lookback (weight `1`). | + +The Python binding defaults the trio to `(7, 14, 28)` via +`#[pyo3(signature = (short=7, mid=14, long=28))]`. Node and WASM take all +three explicitly. The `periods` property returns `(short, mid, long)`. +`UltimateOscillator::classic()` is the conventional `(7, 14, 28)`. + +## Inputs / Outputs + +From `crates/wickra-core/src/indicators/ultimate_oscillator.rs`: + +```rust +impl Indicator for UltimateOscillator { + type Input = Candle; + type Output = f64; + // update(&mut self, input: Candle) -> Option +} +``` + +`UltimateOscillator` is a **candle-input** indicator: it reads `high`, +`low` and `close`. In Python the streaming `update` accepts a 6-tuple or +a dict; the batch helper takes `high`, `low`, `close` numpy arrays. Node +and WASM expose `update(high, low, close)` and `batch(high, low, close)`. + +## Warmup + +`warmup_period() == max(short, mid, long) + 1`. The first bar has no +previous close, so the first `BP`/`TR` pair forms on bar 2; the longest +window must then fill, so the first non-`None` output lands on input +`max(short, mid, long) + 1`. + +## Edge cases + +- **Pure uptrend.** Bars that each close higher have `BP == TR`, so every + ratio is `1` and UO saturates at `100` + (`pure_uptrend_saturates_at_100` pins this). +- **Pure downtrend.** Bars that each close lower have `BP == 0`, so UO is + `0` (`pure_downtrend_saturates_at_0` pins this). +- **Flat market.** Identical bars have zero true range; each window + contributes the neutral ratio `0.5`, so UO reads `50` + (`flat_market_reads_50` pins this). +- **Bounds.** The output is always within `[0, 100]` + (`output_stays_within_0_100` pins this). +- **Candle validation.** `Candle::new` rejects NaN/infinite fields, so + `update` never sees an invalid bar. +- **Reset.** `uo.reset()` clears the previous close, the rolling window + and all six running sums. + +## Examples + +### Rust + +```rust +use wickra::{BatchExt, Candle, Indicator, UltimateOscillator}; + +fn main() -> Result<(), Box> { + let mut uo = UltimateOscillator::classic(); // (7, 14, 28) + // 30 flat candles, each closing one tick higher than the last. + let candles: Vec = (0..40) + .map(|i| { + let p = 100.0 + f64::from(i); + Candle::new(p, p, p, p, 1.0, i64::from(i)).unwrap() + }) + .collect(); + let out = uo.batch(&candles); + println!("warmup_period = {}", uo.warmup_period()); + println!("last = {:?}", out.last().unwrap()); + Ok(()) +} +``` + +Output: + +``` +warmup_period = 29 +last = Some(100.0) +``` + +Every bar closes higher with `BP == TR`, so UO saturates at `100`. This +matches the `pure_uptrend_saturates_at_100` test in +`crates/wickra-core/src/indicators/ultimate_oscillator.rs`. + +### Python + +```python +import numpy as np +import wickra as ta + +uo = ta.UltimateOscillator() # (7, 14, 28) +high = np.full(40, 100.0) +low = np.full(40, 100.0) +close = np.full(40, 100.0) # perfectly flat market +print(uo.batch(high, low, close)[-1]) +``` + +Output: + +``` +50.0 +``` + +### Node + +```javascript +const ta = require('wickra'); +const uo = new ta.UltimateOscillator(7, 14, 28); +const flat = Array.from({ length: 40 }, () => 100); +console.log(uo.batch(flat, flat, flat).at(-1)); // 50 +``` + +## Interpretation + +`UltimateOscillator` is read with the usual overbought/oversold lens — +above `70` is stretched, below `30` is washed out — but Larry Williams' +canonical signal is *divergence with confirmation*: price makes a new +extreme while UO does not, then UO breaks the level of the divergence. +The three-timeframe blend makes those divergences more reliable than a +single-period oscillator. + +## Common pitfalls + +- **Feeding it scalar prices.** It needs `high`/`low`/`close`; it takes a + `Candle`, not an `f64`. +- **Reordering the periods.** The `4 / 2 / 1` weights assume `short` is + the fastest window — keep `short < mid < long`. Any positive periods + are accepted, but mis-ordering them inverts the intended weighting. + +## References + +Larry Williams, "The Ultimate Oscillator", *Technical Analysis of Stocks +& Commodities* (1985). The buying-pressure / true-range definition and the +`4 / 2 / 1` weighting follow Williams' original. + +## See also + +- [Indicator-Stochastic.md](Indicator-Stochastic.md) — single-timeframe + bounded oscillator. +- [Indicator-Rsi.md](Indicator-Rsi.md) — the canonical momentum oscillator. +- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.