use crate::error::FinError;
use crate::signals::{BarInput, Signal, SignalValue};
use rust_decimal::Decimal;
use std::collections::VecDeque;
pub struct Atr {
name: String,
period: usize,
prev_close: Option<Decimal>,
tr_values: VecDeque<Decimal>,
}
impl Atr {
pub fn new(name: impl Into<String>, period: usize) -> Result<Self, crate::error::FinError> {
if period == 0 {
return Err(crate::error::FinError::InvalidPeriod(period));
}
Ok(Self {
name: name.into(),
period,
prev_close: None,
tr_values: VecDeque::with_capacity(period),
})
}
}
impl Signal for Atr {
fn name(&self) -> &str {
&self.name
}
fn update(&mut self, bar: &BarInput) -> Result<SignalValue, FinError> {
let true_range = match self.prev_close {
None => {
self.prev_close = Some(bar.close);
return Ok(SignalValue::Unavailable);
}
Some(prev) => bar.true_range(Some(prev))
};
self.prev_close = Some(bar.close);
self.tr_values.push_back(true_range);
if self.tr_values.len() > self.period {
self.tr_values.pop_front();
}
if self.tr_values.len() < self.period {
return Ok(SignalValue::Unavailable);
}
let sum: Decimal = self.tr_values.iter().copied().sum();
#[allow(clippy::cast_possible_truncation)]
let atr = sum
.checked_div(Decimal::from(self.period as u32))
.ok_or(FinError::ArithmeticOverflow)?;
Ok(SignalValue::Scalar(atr))
}
fn is_ready(&self) -> bool {
self.tr_values.len() >= self.period
}
fn period(&self) -> usize {
self.period
}
fn reset(&mut self) {
self.prev_close = None;
self.tr_values.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ohlcv::OhlcvBar;
use crate::signals::Signal;
use crate::types::{NanoTimestamp, Price, Quantity, Symbol};
use rust_decimal_macros::dec;
fn bar(o: &str, h: &str, l: &str, c: &str) -> OhlcvBar {
OhlcvBar {
symbol: Symbol::new("X").unwrap(),
open: Price::new(o.parse().unwrap()).unwrap(),
high: Price::new(h.parse().unwrap()).unwrap(),
low: Price::new(l.parse().unwrap()).unwrap(),
close: Price::new(c.parse().unwrap()).unwrap(),
volume: Quantity::zero(),
ts_open: NanoTimestamp::new(0),
ts_close: NanoTimestamp::new(1),
tick_count: 1,
}
}
#[test]
fn test_atr_unavailable_on_first_bar() {
let mut atr = Atr::new("atr1", 1).unwrap();
let v = atr.update_bar(&bar("100", "110", "90", "105")).unwrap();
assert_eq!(v, SignalValue::Unavailable);
assert!(!atr.is_ready());
}
#[test]
fn test_atr_period_1_ready_after_two_bars() {
let mut atr = Atr::new("atr1", 1).unwrap();
atr.update_bar(&bar("100", "110", "90", "100")).unwrap();
let v = atr.update_bar(&bar("100", "115", "95", "110")).unwrap();
assert_eq!(v, SignalValue::Scalar(dec!(20)));
assert!(atr.is_ready());
}
#[test]
fn test_atr_uses_prev_close_for_gap() {
let mut atr = Atr::new("atr1", 1).unwrap();
atr.update_bar(&bar("100", "100", "100", "100")).unwrap();
let v = atr.update_bar(&bar("118", "120", "115", "119")).unwrap();
assert_eq!(v, SignalValue::Scalar(dec!(20)));
}
#[test]
fn test_atr_period_0_fails() {
assert!(Atr::new("atr0", 0).is_err());
}
#[test]
fn test_atr_period_3_averages_true_ranges() {
let mut atr = Atr::new("atr3", 3).unwrap();
atr.update_bar(&bar("100", "110", "90", "100")).unwrap();
atr.update_bar(&bar("100", "120", "80", "110")).unwrap();
atr.update_bar(&bar("112", "115", "105", "108")).unwrap();
let v = atr.update_bar(&bar("110", "112", "100", "105")).unwrap();
if let SignalValue::Scalar(atr_val) = v {
let expected = dec!(62) / dec!(3);
assert_eq!(atr_val, expected);
} else {
panic!("expected Scalar after period bars");
}
}
#[test]
fn test_atr_unavailable_before_period_filled() {
let mut atr = Atr::new("atr3", 3).unwrap();
atr.update_bar(&bar("100", "110", "90", "100")).unwrap(); let v1 = atr.update_bar(&bar("100", "120", "80", "110")).unwrap(); let v2 = atr.update_bar(&bar("112", "115", "105", "108")).unwrap(); assert_eq!(v1, SignalValue::Unavailable);
assert_eq!(v2, SignalValue::Unavailable);
assert!(!atr.is_ready());
}
}