Skip to main content

indicators/trend/
atr.rs

1//! Average True Range (ATR).
2//!
3//! Python source: `indicators/trend/volatility/atr.py :: class ATR`
4//!
5//! # Python algorithm (to port)
6//! ```python
7//! high_low        = data["high"] - data["low"]
8//! high_close_prev = abs(data["high"] - data["close"].shift(1))
9//! low_close_prev  = abs(data["low"]  - data["close"].shift(1))
10//! tr  = pd.concat([high_low, high_close_prev, low_close_prev], axis=1).max(axis=1)
11//! atr = tr.rolling(period).mean()           # method=="sma"
12//! # or:
13//! atr = tr.ewm(span=period, adjust=False).mean()  # method=="ema"
14//!
15//! normalized_atr = atr / data["close"] * 100   # percentage
16//! ```
17//!
18//! Output columns: `"ATR_{period}"`, `"ATR_{period}_normalized"`.
19//!
20//! See also: `crate::functions::atr()` and `crate::functions::true_range()`.
21
22use std::collections::HashMap;
23
24use crate::error::IndicatorError;
25use crate::functions::{self};
26use crate::indicator::{Indicator, IndicatorOutput};
27use crate::registry::{param_str, param_usize};
28use crate::types::Candle;
29
30// ── Params ────────────────────────────────────────────────────────────────────
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum AtrMethod {
34    Sma,
35    Ema,
36}
37
38#[derive(Debug, Clone)]
39pub struct AtrParams {
40    /// Period.  Python default: 14.
41    pub period: usize,
42    /// Smoothing method.  Python default: `"sma"`.
43    pub method: AtrMethod,
44}
45
46impl Default for AtrParams {
47    fn default() -> Self {
48        Self {
49            period: 14,
50            method: AtrMethod::Sma,
51        }
52    }
53}
54
55// ── Indicator struct ──────────────────────────────────────────────────────────
56
57#[derive(Debug, Clone)]
58pub struct Atr {
59    pub params: AtrParams,
60}
61
62impl Atr {
63    pub fn new(params: AtrParams) -> Self {
64        Self { params }
65    }
66    pub fn with_period(period: usize) -> Self {
67        Self::new(AtrParams {
68            period,
69            ..Default::default()
70        })
71    }
72
73    fn output_key(&self) -> String {
74        format!("ATR_{}", self.params.period)
75    }
76    fn norm_key(&self) -> String {
77        format!("ATR_{}_normalized", self.params.period)
78    }
79}
80
81impl Indicator for Atr {
82    fn name(&self) -> &'static str {
83        "ATR"
84    }
85    fn required_len(&self) -> usize {
86        self.params.period + 1
87    } // need prev close
88    fn required_columns(&self) -> &[&'static str] {
89        &["high", "low", "close"]
90    }
91
92    /// TODO: port Python SMA/EMA-smoothed ATR + normalized output.
93    ///
94    /// `crate::functions::atr()` already implements EMA-smoothed ATR.
95    /// For SMA-smoothed, roll the true range manually.
96    fn calculate(&self, candles: &[Candle]) -> Result<IndicatorOutput, IndicatorError> {
97        self.check_len(candles)?;
98
99        let high: Vec<f64> = candles.iter().map(|c| c.high).collect();
100        let low: Vec<f64> = candles.iter().map(|c| c.low).collect();
101        let close: Vec<f64> = candles.iter().map(|c| c.close).collect();
102
103        let tr = functions::true_range(&high, &low, &close)?;
104
105        let atr_vals = match self.params.method {
106            AtrMethod::Ema => functions::ema(&tr, self.params.period)?,
107            AtrMethod::Sma => functions::sma(&tr, self.params.period)?,
108        };
109
110        let norm: Vec<f64> = atr_vals
111            .iter()
112            .zip(&close)
113            .map(|(&a, &c)| if c == 0.0 { f64::NAN } else { a / c * 100.0 })
114            .collect();
115
116        Ok(IndicatorOutput::from_pairs([
117            (self.output_key(), atr_vals),
118            (self.norm_key(), norm),
119        ]))
120    }
121}
122
123// ── Registry factory ──────────────────────────────────────────────────────────
124
125pub fn factory<S: ::std::hash::BuildHasher>(params: &HashMap<String, String, S>) -> Result<Box<dyn Indicator>, IndicatorError> {
126    let period = param_usize(params, "period", 14)?;
127    let method = match param_str(params, "method", "sma") {
128        "ema" => AtrMethod::Ema,
129        _ => AtrMethod::Sma,
130    };
131    Ok(Box::new(Atr::new(AtrParams { period, method })))
132}
133
134// ── Tests ─────────────────────────────────────────────────────────────────────
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    fn candles(data: &[(f64, f64, f64)]) -> Vec<Candle> {
141        data.iter()
142            .enumerate()
143            .map(|(i, &(h, l, c))| Candle {
144                time: i64::try_from(i).expect("time index fits i64"),
145                open: c,
146                high: h,
147                low: l,
148                close: c,
149                volume: 1.0,
150            })
151            .collect()
152    }
153
154    #[test]
155    fn atr_output_has_both_columns() {
156        let bars: Vec<(f64, f64, f64)> = (1..=20)
157            .map(|i| (i as f64 + 1.0, i as f64 - 1.0, i as f64))
158            .collect();
159        let atr = Atr::with_period(5);
160        let out = atr.calculate(&candles(&bars)).unwrap();
161        assert!(out.get("ATR_5").is_some());
162        assert!(out.get("ATR_5_normalized").is_some());
163    }
164
165    #[test]
166    fn atr_insufficient_data() {
167        assert!(
168            Atr::with_period(14)
169                .calculate(&candles(&[(10.0, 8.0, 9.0)]))
170                .is_err()
171        );
172    }
173
174    #[test]
175    fn atr_normalized_is_percentage() {
176        let bars: Vec<(f64, f64, f64)> = (1..=20)
177            .map(|i| (i as f64 + 1.0, i as f64 - 1.0, i as f64))
178            .collect();
179        let atr = Atr::with_period(5);
180        let out = atr.calculate(&candles(&bars)).unwrap();
181        let atr_vals = out.get("ATR_5").unwrap();
182        let norm_vals = out.get("ATR_5_normalized").unwrap();
183        let close: Vec<f64> = bars.iter().map(|&(_, _, c)| c).collect();
184        for i in 0..bars.len() {
185            if !atr_vals[i].is_nan() {
186                let expected = atr_vals[i] / close[i] * 100.0;
187                assert!((norm_vals[i] - expected).abs() < 1e-9);
188            }
189        }
190    }
191
192    #[test]
193    fn factory_creates_atr() {
194        let params = [
195            ("period".into(), "14".into()),
196            ("method".into(), "ema".into()),
197        ]
198        .into();
199        let ind = factory(&params).unwrap();
200        assert_eq!(ind.name(), "ATR");
201    }
202}