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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
use std::collections::VecDeque;
use super::View;
use crate::Echo;
#[derive(Clone)]
pub struct RSI<V> {
view: V,
window_len: usize,
avg_gain: f64,
avg_loss: f64,
old_ref: f64,
last_val: f64,
q_vals: VecDeque<f64>,
out: f64,
}
impl<V> std::fmt::Debug for RSI<V>
where
V: View,
{
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(fmt, "RSI(window_len: {}, avg_gain: {}, avg_loss: {}, old_ref: {}, last_val: {}, q_vals: {:?}, out: {})",
self.window_len, self.avg_gain, self.avg_loss, self.old_ref, self.last_val, self.q_vals, self.out)
}
}
#[inline(always)]
pub fn new_final(window_len: usize) -> RSI<Echo> {
RSI::new(Echo::new(), window_len)
}
impl<V> RSI<V>
where
V: View,
{
#[inline]
pub fn new(view: V, window_len: usize) -> Self {
RSI {
view,
window_len,
avg_gain: 0.0,
avg_loss: 0.0,
old_ref: 0.0,
last_val: 0.0,
q_vals: VecDeque::new(),
out: 0.0,
}
}
}
impl<V> View for RSI<V>
where
V: View,
{
fn update(&mut self, val: f64) {
self.view.update(val);
let val = self.view.last();
if self.q_vals.len() == 0 {
self.old_ref = val;
self.last_val = val;
}
if self.q_vals.len() >= self.window_len {
let old_val = self.q_vals.front().unwrap();
let change = old_val - self.old_ref;
self.old_ref = *old_val;
self.q_vals.pop_front();
if change > 0.0 {
self.avg_gain -= change / self.window_len as f64;
} else {
self.avg_loss -= change.abs() / self.window_len as f64;
}
}
self.q_vals.push_back(val);
let change = val - self.last_val;
self.last_val = val;
if change > 0.0 {
self.avg_gain += change / self.window_len as f64;
} else {
self.avg_loss += change.abs() / self.window_len as f64;
}
if self.q_vals.len() < self.window_len {
self.out = 50.0;
} else {
if self.avg_loss == 0.0 {
self.out = 100.0;
} else {
let rs = self.avg_gain / self.avg_loss;
let rsi = 100.0 - 100.0 / (1.0 + rs);
self.out = rsi;
}
}
}
#[inline(always)]
fn last(&self) -> f64 {
return self.out;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plot::plot_values;
use crate::test_data::TEST_DATA;
#[test]
fn rsi_plot() {
let mut rsi = new_final(16);
let mut out: Vec<f64> = Vec::new();
for v in &TEST_DATA {
rsi.update(*v);
out.push(rsi.last());
}
let filename = "img/rsi.png";
plot_values(out, filename).unwrap();
}
#[test]
fn rsi_range() {
let mut rsi = new_final(16);
for v in &TEST_DATA {
rsi.update(*v);
let last = rsi.last();
assert!(last >= 0.0);
assert!(last <= 100.0);
}
}
}