1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use crate::sliding_window::View;
use crate::Echo;
#[derive(Clone)]
pub struct EMA {
view: Box<dyn View>,
window_len: usize,
alpha: f64,
last_ema: f64,
out: f64,
}
impl std::fmt::Debug for EMA {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(fmt, "EMA(window_len: {}, alpha: {}, last_ema: {}, out: {})",
self.window_len, self.alpha, self.last_ema, self.out)
}
}
impl EMA {
pub fn new(view: Box<dyn View>, window_len: usize) -> Box<Self> {
Self::with_alpha(view, window_len, 2.0)
}
pub fn new_final(window_len: usize) -> Box<Self> {
Self::new(Echo::new(), window_len)
}
pub fn with_alpha(view: Box<dyn View>, window_len: usize, alpha: f64) -> Box<Self> {
Box::new(Self {
view,
window_len,
alpha,
last_ema: 0.0,
out: 0.0,
})
}
}
impl View for EMA {
fn update(&mut self, val: f64) {
self.view.update(val);
let val: f64 = self.view.last();
let weight: f64 = self.alpha / (1.0 + self.window_len as f64);
if self.last_ema == 0.0 {
self.out = val;
self.last_ema = val;
return;
}
self.out = val * weight + self.last_ema * (1.0 - weight);
self.last_ema = self.out;
}
fn last(&self) -> f64 {
self.out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plot::plot_values;
use crate::test_data::TEST_DATA;
#[test]
fn ema_plot() {
let mut ema = EMA::new_final(16);
let mut out: Vec<f64> = vec![];
for v in &TEST_DATA {
ema.update(*v);
out.push(ema.last());
}
let filename = "img/ema.png";
plot_values(out, filename).unwrap();
}
}