F7: add NATR, StdDev, Ulcer Index and Historical Volatility
Completes the F7 family (Volatility) end to end: - Rust core: natr.rs (ATR as a percentage of close), std_dev.rs (rolling population standard deviation), ulcer_index.rs (RMS of trailing-high drawdowns — downside-only risk), historical_volatility.rs (annualised sample stddev of log returns). Each with a full Indicator impl, runnable doctest and reference / constant-series / warmup / reset / batch==streaming tests. - Python: PyNatr / PyStdDev / PyUlcerIndex / PyHistoricalVolatility PyO3 classes + module registration + .pyi stubs. - Node: StdDevNode / UlcerIndexNode via the scalar macro, explicit NatrNode and HistoricalVolatilityNode; index.d.ts and index.js updated. - WASM: WasmStdDev / WasmUlcerIndex / WasmHistoricalVolatility via the scalar macro, explicit WasmNatr. - Wiki: Indicator-Natr/StdDev/UlcerIndex/HistoricalVolatility.md plus rows in Indicators-Overview.md and entries in Home.md. cargo fmt + clippy (core/wickra/data/wasm/node) clean; 350 core tests, 25 data tests and 49 doctests green.
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
//! Historical Volatility.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Historical Volatility — the annualised standard deviation of log returns.
|
||||
///
|
||||
/// This is the realised (backward-looking) volatility used to price options
|
||||
/// and size risk:
|
||||
///
|
||||
/// ```text
|
||||
/// r_t = ln(price_t / price_{t−1})
|
||||
/// HV = stddev_sample(r over period) · √trading_periods · 100
|
||||
/// ```
|
||||
///
|
||||
/// The log returns over the window are measured with the **sample** standard
|
||||
/// deviation (divisor `n − 1`, the unbiased estimator), then scaled to an
|
||||
/// annual figure by `√trading_periods` — `252` for daily bars, `52` for
|
||||
/// weekly, `12` for monthly — and expressed as a percentage.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, HistoricalVolatility};
|
||||
///
|
||||
/// // 20-bar window, 252 trading days per year.
|
||||
/// let mut indicator = HistoricalVolatility::new(20, 252).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(100.0 + (f64::from(i) * 0.3).sin() * 5.0);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HistoricalVolatility {
|
||||
period: usize,
|
||||
trading_periods: usize,
|
||||
prev_price: Option<f64>,
|
||||
/// Rolling window of the last `period` log returns.
|
||||
window: VecDeque<f64>,
|
||||
sum: f64,
|
||||
sum_sq: f64,
|
||||
last: Option<f64>,
|
||||
}
|
||||
|
||||
impl HistoricalVolatility {
|
||||
/// Construct a new Historical Volatility indicator.
|
||||
///
|
||||
/// `period` is the number of log returns in the rolling window;
|
||||
/// `trading_periods` is the annualisation factor (`252` daily, `52`
|
||||
/// weekly, `12` monthly).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if `period` or `trading_periods` is `0`,
|
||||
/// or [`Error::InvalidPeriod`] if `period == 1` (the sample standard
|
||||
/// deviation needs at least two returns).
|
||||
pub fn new(period: usize, trading_periods: usize) -> Result<Self> {
|
||||
if period == 0 || trading_periods == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if period < 2 {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "historical volatility period must be >= 2",
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
period,
|
||||
trading_periods,
|
||||
prev_price: None,
|
||||
window: VecDeque::with_capacity(period),
|
||||
sum: 0.0,
|
||||
sum_sq: 0.0,
|
||||
last: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured `(period, trading_periods)`.
|
||||
pub const fn periods(&self) -> (usize, usize) {
|
||||
(self.period, self.trading_periods)
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.last
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for HistoricalVolatility {
|
||||
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.last;
|
||||
}
|
||||
let Some(prev) = self.prev_price else {
|
||||
self.prev_price = Some(input);
|
||||
return None;
|
||||
};
|
||||
self.prev_price = Some(input);
|
||||
|
||||
let log_return = if prev <= 0.0 || input <= 0.0 {
|
||||
// Log return is undefined for non-positive prices.
|
||||
0.0
|
||||
} else {
|
||||
(input / prev).ln()
|
||||
};
|
||||
if self.window.len() == self.period {
|
||||
let old = self.window.pop_front().expect("window is non-empty");
|
||||
self.sum -= old;
|
||||
self.sum_sq -= old * old;
|
||||
}
|
||||
self.window.push_back(log_return);
|
||||
self.sum += log_return;
|
||||
self.sum_sq += log_return * log_return;
|
||||
if self.window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let n = self.period as f64;
|
||||
let mean = self.sum / n;
|
||||
// Sample variance (Bessel's correction): Σ(x−mean)² / (n−1).
|
||||
let variance = ((self.sum_sq - n * mean * mean) / (n - 1.0)).max(0.0);
|
||||
let hv = variance.sqrt() * (self.trading_periods as f64).sqrt() * 100.0;
|
||||
self.last = Some(hv);
|
||||
Some(hv)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prev_price = None;
|
||||
self.window.clear();
|
||||
self.sum = 0.0;
|
||||
self.sum_sq = 0.0;
|
||||
self.last = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// The first log return needs a previous price, then the window fills.
|
||||
self.period + 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.last.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"HistoricalVolatility"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(
|
||||
HistoricalVolatility::new(0, 252),
|
||||
Err(Error::PeriodZero)
|
||||
));
|
||||
assert!(matches!(
|
||||
HistoricalVolatility::new(20, 0),
|
||||
Err(Error::PeriodZero)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_period_one() {
|
||||
assert!(matches!(
|
||||
HistoricalVolatility::new(1, 252),
|
||||
Err(Error::InvalidPeriod { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_at_warmup_period() {
|
||||
let mut hv = HistoricalVolatility::new(5, 252).unwrap();
|
||||
assert_eq!(hv.warmup_period(), 6);
|
||||
let out = hv.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().take(5) {
|
||||
assert!(v.is_none());
|
||||
}
|
||||
assert!(out[5].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
// Flat prices -> all log returns are 0 -> zero volatility.
|
||||
let mut hv = HistoricalVolatility::new(10, 252).unwrap();
|
||||
let out = hv.batch(&[100.0; 40]);
|
||||
for v in out.iter().skip(10).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometric_series_yields_zero() {
|
||||
// A constant growth factor gives a constant log return -> zero stddev.
|
||||
let mut hv = HistoricalVolatility::new(10, 252).unwrap();
|
||||
let prices: Vec<f64> = (0..40).map(|i| 100.0 * 1.01_f64.powi(i)).collect();
|
||||
let out = hv.batch(&prices);
|
||||
for v in out.iter().skip(10).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_is_non_negative() {
|
||||
let mut hv = HistoricalVolatility::new(20, 252).unwrap();
|
||||
let prices: Vec<f64> = (1..=200)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 12.0)
|
||||
.collect();
|
||||
for v in hv.batch(&prices).into_iter().flatten() {
|
||||
assert!(v >= 0.0, "volatility must be non-negative, got {v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut hv = HistoricalVolatility::new(5, 252).unwrap();
|
||||
let out = hv.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
|
||||
let last = *out.last().unwrap();
|
||||
assert!(last.is_some());
|
||||
assert_eq!(hv.update(f64::NAN), last);
|
||||
assert_eq!(hv.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut hv = HistoricalVolatility::new(5, 252).unwrap();
|
||||
hv.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(hv.is_ready());
|
||||
hv.reset();
|
||||
assert!(!hv.is_ready());
|
||||
assert_eq!(hv.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() * 9.0)
|
||||
.collect();
|
||||
let batch = HistoricalVolatility::new(20, 252).unwrap().batch(&prices);
|
||||
let mut b = HistoricalVolatility::new(20, 252).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ mod dema;
|
||||
mod donchian;
|
||||
mod dpo;
|
||||
mod ema;
|
||||
mod historical_volatility;
|
||||
mod hma;
|
||||
mod kama;
|
||||
mod keltner;
|
||||
@@ -24,6 +25,7 @@ mod macd;
|
||||
mod mass_index;
|
||||
mod mfi;
|
||||
mod mom;
|
||||
mod natr;
|
||||
mod obv;
|
||||
mod pmo;
|
||||
mod ppo;
|
||||
@@ -32,6 +34,7 @@ mod roc;
|
||||
mod rsi;
|
||||
mod sma;
|
||||
mod smma;
|
||||
mod std_dev;
|
||||
mod stoch_rsi;
|
||||
mod stochastic;
|
||||
mod t3;
|
||||
@@ -39,6 +42,7 @@ mod tema;
|
||||
mod trima;
|
||||
mod trix;
|
||||
mod tsi;
|
||||
mod ulcer_index;
|
||||
mod ultimate_oscillator;
|
||||
mod vortex;
|
||||
mod vwap;
|
||||
@@ -60,6 +64,7 @@ pub use dema::Dema;
|
||||
pub use donchian::{Donchian, DonchianOutput};
|
||||
pub use dpo::Dpo;
|
||||
pub use ema::Ema;
|
||||
pub use historical_volatility::HistoricalVolatility;
|
||||
pub use hma::Hma;
|
||||
pub use kama::Kama;
|
||||
pub use keltner::{Keltner, KeltnerOutput};
|
||||
@@ -67,6 +72,7 @@ pub use macd::{MacdIndicator, MacdOutput};
|
||||
pub use mass_index::MassIndex;
|
||||
pub use mfi::Mfi;
|
||||
pub use mom::Mom;
|
||||
pub use natr::Natr;
|
||||
pub use obv::Obv;
|
||||
pub use pmo::Pmo;
|
||||
pub use ppo::Ppo;
|
||||
@@ -75,6 +81,7 @@ pub use roc::Roc;
|
||||
pub use rsi::Rsi;
|
||||
pub use sma::Sma;
|
||||
pub use smma::Smma;
|
||||
pub use std_dev::StdDev;
|
||||
pub use stoch_rsi::StochRsi;
|
||||
pub use stochastic::{Stochastic, StochasticOutput};
|
||||
pub use t3::T3;
|
||||
@@ -82,6 +89,7 @@ pub use tema::Tema;
|
||||
pub use trima::Trima;
|
||||
pub use trix::Trix;
|
||||
pub use tsi::Tsi;
|
||||
pub use ulcer_index::UlcerIndex;
|
||||
pub use ultimate_oscillator::UltimateOscillator;
|
||||
pub use vortex::{Vortex, VortexOutput};
|
||||
pub use vwap::{RollingVwap, Vwap};
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
//! Normalized Average True Range.
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
use super::Atr;
|
||||
|
||||
/// Normalized Average True Range — [`Atr`] expressed as a percentage of price.
|
||||
///
|
||||
/// `Atr` reports volatility in raw price units, which makes its readings
|
||||
/// impossible to compare across instruments at different price levels. NATR
|
||||
/// fixes that by dividing by the current close:
|
||||
///
|
||||
/// ```text
|
||||
/// NATR = 100 · ATR / close
|
||||
/// ```
|
||||
///
|
||||
/// A NATR of `2.0` always means "the average true range is 2 % of price",
|
||||
/// whether the instrument trades at $10 or $10 000 — so NATR values are
|
||||
/// directly comparable, and stop distances or position sizes expressed as a
|
||||
/// NATR multiple behave consistently across a portfolio.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Candle, Indicator, Natr};
|
||||
///
|
||||
/// let mut indicator = Natr::new(14).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// let base = 100.0 + f64::from(i);
|
||||
/// let candle =
|
||||
/// Candle::new(base, base + 2.0, base - 2.0, base, 10.0, i64::from(i)).unwrap();
|
||||
/// last = indicator.update(candle);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Natr {
|
||||
atr: Atr,
|
||||
last: Option<f64>,
|
||||
}
|
||||
|
||||
impl Natr {
|
||||
/// Construct a new NATR with the given ATR period.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`crate::Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
Ok(Self {
|
||||
atr: Atr::new(period)?,
|
||||
last: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.atr.period()
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.last
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Natr {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
let atr = self.atr.update(candle)?;
|
||||
let natr = if candle.close == 0.0 {
|
||||
// NATR is undefined against a zero close.
|
||||
0.0
|
||||
} else {
|
||||
100.0 * atr / candle.close
|
||||
};
|
||||
self.last = Some(natr);
|
||||
Some(natr)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.atr.reset();
|
||||
self.last = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.atr.warmup_period()
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.last.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"NATR"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn candle(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
|
||||
Candle::new(open, high, low, close, 1.0, ts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(Natr::new(0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warmup_period_matches_atr() {
|
||||
let natr = Natr::new(14).unwrap();
|
||||
assert_eq!(natr.warmup_period(), 14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn natr_is_atr_over_close_as_percent() {
|
||||
// NATR must equal 100 * ATR / close, bar for bar.
|
||||
let candles: Vec<Candle> = (0..60)
|
||||
.map(|i| {
|
||||
let mid = 100.0 + (i as f64 * 0.3).sin() * 10.0;
|
||||
candle(mid, mid + 3.0, mid - 3.0, mid + 1.0, i)
|
||||
})
|
||||
.collect();
|
||||
let natr_out = Natr::new(14).unwrap().batch(&candles);
|
||||
let atr_out = Atr::new(14).unwrap().batch(&candles);
|
||||
for (i, (n, a)) in natr_out.iter().zip(atr_out.iter()).enumerate() {
|
||||
match (n, a) {
|
||||
(Some(nv), Some(av)) => {
|
||||
let want = 100.0 * av / candles[i].close;
|
||||
assert_relative_eq!(*nv, want, epsilon = 1e-9);
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => panic!("warmup mismatch at {i}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_market_yields_zero() {
|
||||
// No range -> ATR is 0 -> NATR is 0.
|
||||
let mut natr = Natr::new(5).unwrap();
|
||||
let candles: Vec<Candle> = (0..30)
|
||||
.map(|i| candle(100.0, 100.0, 100.0, 100.0, i))
|
||||
.collect();
|
||||
for v in natr.batch(&candles).into_iter().flatten() {
|
||||
assert_relative_eq!(v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut natr = Natr::new(5).unwrap();
|
||||
let candles: Vec<Candle> = (0..20)
|
||||
.map(|i| candle(100.0, 102.0, 98.0, 101.0, i))
|
||||
.collect();
|
||||
natr.batch(&candles);
|
||||
assert!(natr.is_ready());
|
||||
natr.reset();
|
||||
assert!(!natr.is_ready());
|
||||
assert_eq!(natr.update(candles[0]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..80)
|
||||
.map(|i| {
|
||||
let mid = 100.0 + (i as f64 * 0.35).sin() * 9.0;
|
||||
candle(mid, mid + 2.5, mid - 2.5, mid + 0.5, i)
|
||||
})
|
||||
.collect();
|
||||
let batch = Natr::new(14).unwrap().batch(&candles);
|
||||
let mut b = Natr::new(14).unwrap();
|
||||
let streamed: Vec<_> = candles.iter().map(|c| b.update(*c)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Rolling population standard deviation.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Rolling population standard deviation over the last `period` values.
|
||||
///
|
||||
/// ```text
|
||||
/// mean = (1/n) · Σ price
|
||||
/// variance = (1/n) · Σ price² − mean²
|
||||
/// StdDev = √variance
|
||||
/// ```
|
||||
///
|
||||
/// This is the **population** standard deviation (divisor `n`, not `n − 1`) —
|
||||
/// the same dispersion measure that drives [`BollingerBands`](crate::BollingerBands).
|
||||
/// It is maintained as an O(1) rolling state machine: a running sum and a
|
||||
/// running sum-of-squares, updated by one add and one subtract per bar. Tiny
|
||||
/// negative variances from floating-point cancellation are clamped to zero
|
||||
/// before the square root.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, StdDev};
|
||||
///
|
||||
/// let mut indicator = StdDev::new(20).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(100.0 + (f64::from(i) * 0.3).sin() * 5.0);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StdDev {
|
||||
period: usize,
|
||||
window: VecDeque<f64>,
|
||||
sum: f64,
|
||||
sum_sq: f64,
|
||||
last: Option<f64>,
|
||||
}
|
||||
|
||||
impl StdDev {
|
||||
/// Construct a new rolling standard deviation 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,
|
||||
window: VecDeque::with_capacity(period),
|
||||
sum: 0.0,
|
||||
sum_sq: 0.0,
|
||||
last: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured 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 StdDev {
|
||||
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 {
|
||||
let old = self.window.pop_front().expect("window is non-empty");
|
||||
self.sum -= old;
|
||||
self.sum_sq -= old * old;
|
||||
}
|
||||
self.window.push_back(input);
|
||||
self.sum += input;
|
||||
self.sum_sq += input * input;
|
||||
if self.window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let n = self.period as f64;
|
||||
let mean = self.sum / n;
|
||||
// Clamp floating-point cancellation noise: variance is never negative.
|
||||
let variance = (self.sum_sq / n - mean * mean).max(0.0);
|
||||
let sd = variance.sqrt();
|
||||
self.last = Some(sd);
|
||||
Some(sd)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.sum = 0.0;
|
||||
self.sum_sq = 0.0;
|
||||
self.last = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.last.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"StdDev"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(StdDev::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value() {
|
||||
// StdDev(3) of [2, 4, 6]: mean = 4, variance = (4+0+4)/3 = 8/3.
|
||||
let mut sd = StdDev::new(3).unwrap();
|
||||
let out = sd.batch(&[2.0, 4.0, 6.0]);
|
||||
assert_eq!(out[0], None);
|
||||
assert_eq!(out[1], None);
|
||||
assert_relative_eq!(out[2].unwrap(), (8.0_f64 / 3.0).sqrt(), epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
let mut sd = StdDev::new(5).unwrap();
|
||||
let out = sd.batch(&[42.0; 20]);
|
||||
for v in out.iter().skip(4).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_naive_definition() {
|
||||
let prices: Vec<f64> = (1..=60)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.4).sin() * 8.0)
|
||||
.collect();
|
||||
let period = 10;
|
||||
let got = StdDev::new(period).unwrap().batch(&prices);
|
||||
for (i, g) in got.iter().enumerate() {
|
||||
if let Some(value) = g {
|
||||
let window = &prices[i + 1 - period..=i];
|
||||
let mean = window.iter().sum::<f64>() / period as f64;
|
||||
let var = window.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / period as f64;
|
||||
assert_relative_eq!(*value, var.sqrt(), epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut sd = StdDev::new(3).unwrap();
|
||||
let out = sd.batch(&[2.0, 4.0, 6.0]);
|
||||
let last = out[2];
|
||||
assert!(last.is_some());
|
||||
assert_eq!(sd.update(f64::NAN), last);
|
||||
assert_eq!(sd.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut sd = StdDev::new(3).unwrap();
|
||||
sd.batch(&[1.0, 2.0, 3.0, 4.0]);
|
||||
assert!(sd.is_ready());
|
||||
sd.reset();
|
||||
assert!(!sd.is_ready());
|
||||
assert_eq!(sd.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=60)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.3).cos() * 7.0)
|
||||
.collect();
|
||||
let batch = StdDev::new(14).unwrap().batch(&prices);
|
||||
let mut b = StdDev::new(14).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Ulcer Index.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Ulcer Index — Peter Martin's downside-only volatility / risk measure.
|
||||
///
|
||||
/// Standard deviation punishes upside and downside moves equally; the Ulcer
|
||||
/// Index measures only the **pain of drawdowns**. For each bar it computes the
|
||||
/// percentage drop from the highest price of the trailing window, squares it,
|
||||
/// and reports the root-mean-square over the window:
|
||||
///
|
||||
/// ```text
|
||||
/// drawdown_t = 100 · (price_t − max(price, period)_t) / max(price, period)_t
|
||||
/// UlcerIndex = √( mean( drawdown² over period ) )
|
||||
/// ```
|
||||
///
|
||||
/// A pure up-trend never trades below its own running high, so its Ulcer Index
|
||||
/// is `0`; the deeper and longer the drawdowns, the higher the reading. It is
|
||||
/// the volatility measure of choice for risk-adjusted return ratios (the
|
||||
/// "Martin ratio" / UPI).
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, UlcerIndex};
|
||||
///
|
||||
/// let mut indicator = UlcerIndex::new(14).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(100.0 + (f64::from(i) * 0.3).sin() * 8.0);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UlcerIndex {
|
||||
period: usize,
|
||||
/// Rolling window of the last `period` prices (for the trailing maximum).
|
||||
prices: VecDeque<f64>,
|
||||
/// Rolling window of the last `period` squared percentage drawdowns.
|
||||
drawdowns_sq: VecDeque<f64>,
|
||||
sum_sq: f64,
|
||||
last: Option<f64>,
|
||||
}
|
||||
|
||||
impl UlcerIndex {
|
||||
/// Construct a new Ulcer Index 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,
|
||||
prices: VecDeque::with_capacity(period),
|
||||
drawdowns_sq: VecDeque::with_capacity(period),
|
||||
sum_sq: 0.0,
|
||||
last: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured 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 UlcerIndex {
|
||||
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.last;
|
||||
}
|
||||
if self.prices.len() == self.period {
|
||||
self.prices.pop_front();
|
||||
}
|
||||
self.prices.push_back(input);
|
||||
if self.prices.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let max_price = self
|
||||
.prices
|
||||
.iter()
|
||||
.copied()
|
||||
.fold(f64::NEG_INFINITY, f64::max);
|
||||
let drawdown = if max_price == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
100.0 * (input - max_price) / max_price
|
||||
};
|
||||
let sq = drawdown * drawdown;
|
||||
|
||||
if self.drawdowns_sq.len() == self.period {
|
||||
self.sum_sq -= self.drawdowns_sq.pop_front().expect("window is non-empty");
|
||||
}
|
||||
self.drawdowns_sq.push_back(sq);
|
||||
self.sum_sq += sq;
|
||||
if self.drawdowns_sq.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let ui = (self.sum_sq / self.period as f64).sqrt();
|
||||
self.last = Some(ui);
|
||||
Some(ui)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.prices.clear();
|
||||
self.drawdowns_sq.clear();
|
||||
self.sum_sq = 0.0;
|
||||
self.last = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// `period` prices fill the trailing-max window, then `period` squared
|
||||
// drawdowns fill the RMS window.
|
||||
2 * self.period - 1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.last.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"UlcerIndex"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(UlcerIndex::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_values() {
|
||||
// UlcerIndex(2): warmup = 3.
|
||||
// [10, 8, 12, 9]:
|
||||
// bar 3: window [8,12], max 12, drawdown 0; sq window [400, 0]
|
||||
// -> UI = sqrt(200).
|
||||
// bar 4: window [12,9], max 12, drawdown -25, sq 625; sq window [0, 625]
|
||||
// -> UI = sqrt(312.5).
|
||||
let mut ui = UlcerIndex::new(2).unwrap();
|
||||
let out = ui.batch(&[10.0, 8.0, 12.0, 9.0]);
|
||||
assert_eq!(ui.warmup_period(), 3);
|
||||
assert_eq!(out[0], None);
|
||||
assert_eq!(out[1], None);
|
||||
assert_relative_eq!(out[2].unwrap(), 200.0_f64.sqrt(), epsilon = 1e-12);
|
||||
assert_relative_eq!(out[3].unwrap(), 312.5_f64.sqrt(), epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_uptrend_yields_zero() {
|
||||
// Price never trades below its own running high: no drawdown at all.
|
||||
let mut ui = UlcerIndex::new(5).unwrap();
|
||||
let out = ui.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().skip(ui.warmup_period() - 1).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
let mut ui = UlcerIndex::new(5).unwrap();
|
||||
let out = ui.batch(&[50.0; 30]);
|
||||
for v in out.iter().skip(ui.warmup_period() - 1).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_is_non_negative() {
|
||||
let mut ui = UlcerIndex::new(14).unwrap();
|
||||
let prices: Vec<f64> = (1..=120)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.25).sin() * 15.0)
|
||||
.collect();
|
||||
for v in ui.batch(&prices).into_iter().flatten() {
|
||||
assert!(v >= 0.0, "Ulcer Index must be non-negative, got {v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut ui = UlcerIndex::new(2).unwrap();
|
||||
let out = ui.batch(&[10.0, 8.0, 12.0, 9.0]);
|
||||
let last = *out.last().unwrap();
|
||||
assert!(last.is_some());
|
||||
assert_eq!(ui.update(f64::NAN), last);
|
||||
assert_eq!(ui.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut ui = UlcerIndex::new(3).unwrap();
|
||||
ui.batch(&[10.0, 8.0, 12.0, 9.0, 11.0, 7.0]);
|
||||
assert!(ui.is_ready());
|
||||
ui.reset();
|
||||
assert!(!ui.is_ready());
|
||||
assert_eq!(ui.update(10.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=80)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 10.0)
|
||||
.collect();
|
||||
let batch = UlcerIndex::new(14).unwrap().batch(&prices);
|
||||
let mut b = UlcerIndex::new(14).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user