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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use std::fmt;
use crate::{Close, Next, Reset, Volume};
#[derive(Debug, Clone)]
pub struct OnBalanceVolume {
obv: f64,
prev_close: f64,
}
impl OnBalanceVolume {
pub fn new() -> Self {
Self {
obv: 0.0,
prev_close: 0.0,
}
}
}
impl<'a, T: Close + Volume> Next<&'a T> for OnBalanceVolume {
type Output = f64;
fn next(&mut self, input: &'a T) -> f64 {
if input.close() > self.prev_close {
self.obv = self.obv + input.volume();
} else if input.close() < self.prev_close {
self.obv = self.obv - input.volume();
}
self.prev_close = input.close();
self.obv
}
}
impl Default for OnBalanceVolume {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for OnBalanceVolume {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "OBV")
}
}
impl Reset for OnBalanceVolume {
fn reset(&mut self) {
self.obv = 0.0;
self.prev_close = 0.0;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_helper::*;
#[test]
fn test_next_bar() {
let mut obv = OnBalanceVolume::new();
let bar1 = Bar::new().close(1.5).volume(1000.0);
let bar2 = Bar::new().close(5).volume(5000.0);
let bar3 = Bar::new().close(4).volume(9000.0);
let bar4 = Bar::new().close(4).volume(4000.0);
assert_eq!(obv.next(&bar1), 1000.0);
assert_eq!(obv.next(&bar2), 6000.0);
assert_eq!(obv.next(&bar3), -3000.0);
assert_eq!(obv.next(&bar4), -3000.0);
}
#[test]
fn test_reset() {
let mut obv = OnBalanceVolume::new();
let bar1 = Bar::new().close(1.5).volume(1000.0);
let bar2 = Bar::new().close(4).volume(2000.0);
let bar3 = Bar::new().close(8).volume(3000.0);
assert_eq!(obv.next(&bar1), 1000.0);
assert_eq!(obv.next(&bar2), 3000.0);
assert_eq!(obv.next(&bar3), 6000.0);
obv.reset();
assert_eq!(obv.next(&bar1), 1000.0);
assert_eq!(obv.next(&bar2), 3000.0);
assert_eq!(obv.next(&bar3), 6000.0);
}
#[test]
fn test_default() {
OnBalanceVolume::default();
}
#[test]
fn test_display() {
let obv = OnBalanceVolume::new();
assert_eq!(format!("{}", obv), "OBV");
}
}