Skip to main content

quantwave_core/indicators/
volatility.rs

1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::indicators::smoothing::EMA;
3use crate::traits::Next;
4use serde::{Deserialize, Serialize};
5
6pub use crate::indicators::incremental::ta_atr::TaATR;
7impl From<usize> for TaATR {
8    fn from(p: usize) -> Self {
9        Self::new(p)
10    }
11}
12pub use crate::indicators::incremental::trange::{TaNATR, TaTRANGE};
13impl From<usize> for TaNATR {
14    fn from(p: usize) -> Self {
15        Self::new(p)
16    }
17}
18
19/// True Range (TR)
20#[derive(Debug, Clone, Default, Serialize, Deserialize)]
21pub struct TrueRange {
22    prev_close: Option<f64>,
23}
24
25impl TrueRange {
26    pub fn new() -> Self {
27        Self::default()
28    }
29}
30
31impl Next<(f64, f64, f64)> for TrueRange {
32    type Output = f64;
33
34    fn next(&mut self, (high, low, close): (f64, f64, f64)) -> Self::Output {
35        let tr = match self.prev_close {
36            Some(pc) => {
37                let h_l = high - low;
38                let h_pc = (high - pc).abs();
39                let l_pc = (low - pc).abs();
40                h_l.max(h_pc).max(l_pc)
41            }
42            None => high - low,
43        };
44        self.prev_close = Some(close);
45        tr
46    }
47}
48
49/// Average True Range (ATR) — **EMA-smoothed variant, not Wilder's RMA**.
50///
51/// This smooths true range with a standard EMA (`alpha = 2/(period+1)`), seeded
52/// from the first bar's `high - low` and emitting a value from bar 0 with no NaN
53/// warmup. It is **not** the ATR that Wilder defined in 1978 and that TA-Lib,
54/// TradingView Pine `ta.atr`, and `pandas.ewm(alpha=1/period, adjust=False)`
55/// compute — for that, use [`TaATR`], which is proptest-verified against
56/// `talib_rs::volatility::atr`.
57///
58/// No authoritative source has been recorded for this EMA-smoothed variant; the
59/// divergence and its blast radius (SuperTrend, Keltner, ATR trailing stop, TTM
60/// Squeeze, VPN, S/R monitor, volatility-clustering regime) are tracked in
61/// `quantwave-xnaf` and recorded as data in
62/// [`crate::indicators::conventions::CONVENTION_NOTES`].
63///
64/// Note that the Polars plugin `pl.col(close).ta.atr(high, low)` and
65/// `quantwave.talib.ATR` are backed by [`TaATR`] and *are* Wilder; only this
66/// struct and the `atr(period, high, low, close)` PyO3 batch function are not.
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct ATR {
69    tr: TrueRange,
70    smoothing: EMA,
71}
72
73impl ATR {
74    pub fn new(period: usize) -> Self {
75        Self {
76            tr: TrueRange::default(),
77            smoothing: EMA::new(period),
78        }
79    }
80}
81
82impl Next<(f64, f64, f64)> for ATR {
83    type Output = f64;
84
85    fn next(&mut self, input: (f64, f64, f64)) -> Self::Output {
86        let tr = self.tr.next(input);
87        self.smoothing.next(tr)
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94    use crate::traits::Next;
95    use proptest::prelude::*;
96
97    proptest! {
98        #[test]
99        fn test_ta_atr_parity(
100            h in prop::collection::vec(1.0..100.0, 1..100),
101            l in prop::collection::vec(1.0..100.0, 1..100),
102            c in prop::collection::vec(1.0..100.0, 1..100)
103        ) {
104            let len = h.len().min(l.len()).min(c.len());
105            if len == 0 { return Ok(()); }
106            let mut high = Vec::with_capacity(len);
107            let mut low = Vec::with_capacity(len);
108            let mut close = Vec::with_capacity(len);
109            for i in 0..len {
110                let v_h: f64 = h[i];
111                let v_l: f64 = l[i];
112                let v_c: f64 = c[i];
113                high.push(v_h.max(v_l).max(v_c));
114                low.push(v_h.min(v_l).min(v_c));
115                close.push(v_c);
116            }
117
118            let period = 14;
119            let mut ta_atr = TaATR::new(period);
120            let streaming_results: Vec<f64> = (0..len).map(|i| ta_atr.next((high[i], low[i], close[i]))).collect();
121            let batch_results = talib_rs::volatility::atr(&high, &low, &close, period).unwrap_or_else(|_| vec![f64::NAN; len]);
122
123            for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
124                if s.is_nan() {
125                    assert!(b.is_nan());
126                } else {
127                    approx::assert_relative_eq!(s, b, epsilon = 1e-6);
128                }
129            }
130        }
131
132        #[test]
133        fn test_ta_trange_parity(
134            h in prop::collection::vec(1.0..100.0, 1..100),
135            l in prop::collection::vec(1.0..100.0, 1..100),
136            c in prop::collection::vec(1.0..100.0, 1..100)
137        ) {
138            let len = h.len().min(l.len()).min(c.len());
139            if len == 0 { return Ok(()); }
140            let mut high = Vec::with_capacity(len);
141            let mut low = Vec::with_capacity(len);
142            let mut close = Vec::with_capacity(len);
143            for i in 0..len {
144                let v_h: f64 = h[i];
145                let v_l: f64 = l[i];
146                let v_c: f64 = c[i];
147                high.push(v_h.max(v_l).max(v_c));
148                low.push(v_h.min(v_l).min(v_c));
149                close.push(v_c);
150            }
151
152            let mut ta_tr = TaTRANGE::new();
153            let streaming_results: Vec<f64> = (0..len).map(|i| ta_tr.next((high[i], low[i], close[i]))).collect();
154            let batch_results = talib_rs::volatility::trange(&high, &low, &close).unwrap_or_else(|_| vec![f64::NAN; len]);
155
156            for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
157                if s.is_nan() {
158                    assert!(b.is_nan());
159                } else {
160                    approx::assert_relative_eq!(s, b, epsilon = 1e-6);
161                }
162            }
163        }
164    }
165}
166
167pub const TRUE_RANGE_METADATA: IndicatorMetadata = IndicatorMetadata {
168    name: "True Range",
169    description: "True Range measures daily volatility.",
170    usage: "Use as the foundational volatility module providing ATR, True Range, and related volatility measures used by higher-level indicators such as SuperTrend and Keltner Channels.",
171    keywords: &["volatility", "atr", "classic", "range"],
172    ehlers_summary: "Average True Range, developed by J. Welles Wilder in New Concepts in Technical Trading Systems (1978), measures the average of the true range over N bars. True Range accounts for overnight gaps by taking the maximum of: current high minus low, current high minus prior close, prior close minus current low. It remains the industry standard raw volatility measure.",
173    params: &[],
174    formula_source: "https://www.investopedia.com/terms/a/atr.asp",
175    formula_latex: r#"
176\[
177TR = \max(H - L, |H - C_{t-1}|, |L - C_{t-1}|)
178\]
179"#,
180    gold_standard_file: "true_range.json",
181    category: "Classic",
182};
183
184pub const ATR_METADATA: IndicatorMetadata = IndicatorMetadata {
185    name: "Average True Range",
186    description: "ATR represents the average of true ranges over a specified period. CONVENTION: the `Atr` streaming class and the `atr(period, high, low, close)` batch function smooth true range with an EMA (alpha = 2/(period+1)), NOT Wilder's RMA. For TA-Lib/TradingView-identical ATR use `ta_atr`. See the Average True Range indicator guide for the full surface-by-surface breakdown.",
187    usage: "Use as the foundational volatility module providing ATR, True Range, and related volatility measures used by higher-level indicators such as SuperTrend and Keltner Channels. Check `quantwave.conventions(\"atr\")` before reconciling values against TA-Lib, TradingView, or pandas.",
188    keywords: &[
189        "volatility",
190        "atr",
191        "classic",
192        "range",
193        "convention-divergence",
194    ],
195    ehlers_summary: "Average True Range, developed by J. Welles Wilder in New Concepts in Technical Trading Systems (1978), measures the average of the true range over N bars. True Range accounts for overnight gaps by taking the maximum of: current high minus low, current high minus prior close, prior close minus current low. It remains the industry standard raw volatility measure.",
196    params: &[ParamDef {
197        name: "period",
198        default: "14",
199        description: "Smoothing period",
200    }],
201    // NOTE (quantwave-xnaf): this URL documents Wilder's RMA, which is what `ta_atr`
202    // implements. No source has been established for the EMA-smoothed variant that
203    // `Atr` / `atr()` actually compute; per AGENTS.md it is recorded as unsourced in
204    // `conventions::CONVENTION_NOTES` rather than having a source assumed for it.
205    formula_source: "https://www.investopedia.com/terms/a/atr.asp (documents Wilder's RMA — implemented by `ta_atr`; no source recorded for the EMA-smoothed `Atr`)",
206    formula_latex: r#"
207\[
208TR_t = \max(H_t - L_t, |H_t - C_{t-1}|, |L_t - C_{t-1}|)
209\]
210\[
211\text{Atr / atr() (EMA variant): } ATR_t = \alpha TR_t + (1-\alpha) ATR_{t-1}, \quad \alpha = \frac{2}{n+1}
212\]
213\[
214\text{ta\_atr (Wilder RMA, TA-Lib): } ATR_t = \frac{ATR_{t-1} \times (n-1) + TR_t}{n}
215\]
216"#,
217    gold_standard_file: "atr.json",
218    category: "Classic",
219};
220
221pub const NATR_METADATA: IndicatorMetadata = IndicatorMetadata {
222    name: "Normalized Average True Range (NATR)",
223    description: "A normalized version of ATR that represents volatility as a percentage of price.",
224    usage: "Use to compare volatility across different securities with varying price levels. NATR allows for normalized risk assessment and position sizing.",
225    keywords: &["volatility", "atr", "normalization", "classic"],
226    ehlers_summary: "Normalized ATR (NATR) was developed to allow traders to compare the volatility of high-priced stocks with low-priced stocks. By dividing the ATR by the closing price and multiplying by 100, the result is a percentage that can be used consistently across all assets. — TA-Lib Documentation",
227    params: &[ParamDef {
228        name: "timeperiod",
229        default: "14",
230        description: "Smoothing period",
231    }],
232    formula_source: "https://www.tradingtechnologies.com/help/x-study/technical-indicator-definitions/normalized-average-true-range-natr/",
233    formula_latex: r#"
234\[
235NATR = \frac{ATR(n)}{Close} \times 100
236\]
237"#,
238    gold_standard_file: "natr.json",
239    category: "Classic",
240};