quantaxis_rs/indicators/
maximum.rs

1use std::f64::INFINITY;
2use std::fmt;
3
4use crate::{High, Next, Reset};
5use crate::errors::*;
6
7/// Returns the highest value in a given time frame.
8///
9/// # Parameters
10///
11/// * _n_ - size of the time frame (integer greater than 0). Default value is 14.
12///
13/// # Example
14///
15/// ```
16/// use quantaxis_rs::indicators::Maximum;
17/// use quantaxis_rs::Next;
18///
19/// let mut max = Maximum::new(3).unwrap();
20/// assert_eq!(max.next(7.0), 7.0);
21/// assert_eq!(max.next(5.0), 7.0);
22/// assert_eq!(max.next(4.0), 7.0);
23/// assert_eq!(max.next(4.0), 5.0);
24/// assert_eq!(max.next(8.0), 8.0);
25/// ```
26#[derive(Debug, Clone)]
27pub struct Maximum {
28    n: usize,
29    vec: Vec<f64>,
30    max_index: usize,
31    cur_index: usize,
32}
33
34impl Maximum {
35    pub fn new(n: u32) -> Result<Self> {
36        let n = n as usize;
37
38        if n == 0 {
39            return Err(Error::from_kind(ErrorKind::InvalidParameter));
40        }
41
42        let indicator = Self {
43            n: n,
44            vec: vec![-INFINITY; n],
45            max_index: 0,
46            cur_index: 0,
47        };
48        Ok(indicator)
49    }
50
51    fn find_max_index(&self) -> usize {
52        let mut max = -INFINITY;
53        let mut index: usize = 0;
54
55        for (i, &val) in self.vec.iter().enumerate() {
56            if val > max {
57                max = val;
58                index = i;
59            }
60        }
61
62        index
63    }
64}
65
66impl Next<f64> for Maximum {
67    type Output = f64;
68
69    fn next(&mut self, input: f64) -> Self::Output {
70        self.cur_index = (self.cur_index + 1) % (self.n as usize);
71        self.vec[self.cur_index] = input;
72
73        if input > self.vec[self.max_index] {
74            self.max_index = self.cur_index;
75        } else if self.max_index == self.cur_index {
76            self.max_index = self.find_max_index();
77        }
78
79        self.vec[self.max_index]
80    }
81}
82
83impl<'a, T: High> Next<&'a T> for Maximum {
84    type Output = f64;
85
86    fn next(&mut self, input: &'a T) -> Self::Output {
87        self.next(input.high())
88    }
89}
90
91impl Reset for Maximum {
92    fn reset(&mut self) {
93        for i in 0..self.n {
94            self.vec[i] = -INFINITY;
95        }
96    }
97}
98
99impl Default for Maximum {
100    fn default() -> Self {
101        Self::new(14).unwrap()
102    }
103}
104
105impl fmt::Display for Maximum {
106    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107        write!(f, "MAX({})", self.n)
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use crate::test_helper::*;
114
115    use super::*;
116    macro_rules! test_indicator {
117        ($i:tt) => {
118            #[test]
119            fn test_indicator() {
120                let bar = Bar::new();
121
122                // ensure Default trait is implemented
123                let mut indicator = $i::default();
124
125                // ensure Next<f64> is implemented
126                let first_output = indicator.next(12.3);
127
128                // ensure next accepts &DataItem as well
129                indicator.next(&bar);
130
131                // ensure Reset is implemented and works correctly
132                indicator.reset();
133                assert_eq!(indicator.next(12.3), first_output);
134
135                // ensure Display is implemented
136                format!("{}", indicator);
137            }
138        };
139    }
140    test_indicator!(Maximum);
141
142    #[test]
143    fn test_new() {
144        assert!(Maximum::new(0).is_err());
145        assert!(Maximum::new(1).is_ok());
146    }
147
148    #[test]
149    fn test_next() {
150        let mut max = Maximum::new(3).unwrap();
151
152        assert_eq!(max.next(4.0), 4.0);
153        assert_eq!(max.next(1.2), 4.0);
154        assert_eq!(max.next(5.0), 5.0);
155        assert_eq!(max.next(3.0), 5.0);
156        assert_eq!(max.next(4.0), 5.0);
157        assert_eq!(max.next(0.0), 4.0);
158        assert_eq!(max.next(-1.0), 4.0);
159        assert_eq!(max.next(-2.0), 0.0);
160        assert_eq!(max.next(-1.5), -1.0);
161    }
162
163    #[test]
164    fn test_next_with_bars() {
165        fn bar(high: f64) -> Bar {
166            Bar::new().high(high)
167        }
168
169        let mut max = Maximum::new(2).unwrap();
170
171        assert_eq!(max.next(&bar(1.1)), 1.1);
172        assert_eq!(max.next(&bar(4.0)), 4.0);
173        assert_eq!(max.next(&bar(3.5)), 4.0);
174        assert_eq!(max.next(&bar(2.0)), 3.5);
175    }
176
177    #[test]
178    fn test_reset() {
179        let mut max = Maximum::new(100).unwrap();
180        assert_eq!(max.next(4.0), 4.0);
181        assert_eq!(max.next(10.0), 10.0);
182        assert_eq!(max.next(4.0), 10.0);
183
184        max.reset();
185        assert_eq!(max.next(4.0), 4.0);
186    }
187
188    #[test]
189    fn test_default() {
190        Maximum::default();
191    }
192
193    #[test]
194    fn test_display() {
195        let indicator = Maximum::new(7).unwrap();
196        assert_eq!(format!("{}", indicator), "MAX(7)");
197    }
198}