nautilus_indicators/momentum/
obv.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::{
17    collections::VecDeque,
18    fmt::{Debug, Display},
19};
20
21use nautilus_model::data::Bar;
22
23use crate::indicator::Indicator;
24
25#[repr(C)]
26#[derive(Debug)]
27#[cfg_attr(
28    feature = "python",
29    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")
30)]
31pub struct OnBalanceVolume {
32    pub period: usize,
33    pub value: f64,
34    pub initialized: bool,
35    has_inputs: bool,
36    obv: VecDeque<f64>,
37}
38
39impl Display for OnBalanceVolume {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        write!(f, "{}({})", self.name(), self.period)
42    }
43}
44
45impl Indicator for OnBalanceVolume {
46    fn name(&self) -> String {
47        stringify!(OnBalanceVolume).to_string()
48    }
49
50    fn has_inputs(&self) -> bool {
51        self.has_inputs
52    }
53
54    fn initialized(&self) -> bool {
55        self.initialized
56    }
57
58    fn handle_bar(&mut self, bar: &Bar) {
59        self.update_raw(
60            (&bar.open).into(),
61            (&bar.close).into(),
62            (&bar.volume).into(),
63        );
64    }
65
66    fn reset(&mut self) {
67        self.obv.clear();
68        self.value = 0.0;
69        self.has_inputs = false;
70        self.initialized = false;
71    }
72}
73
74impl OnBalanceVolume {
75    /// Creates a new [`OnBalanceVolume`] instance.
76    #[must_use]
77    pub fn new(period: usize) -> Self {
78        Self {
79            period,
80            value: 0.0,
81            obv: VecDeque::with_capacity(period),
82            has_inputs: false,
83            initialized: false,
84        }
85    }
86
87    pub fn update_raw(&mut self, open: f64, close: f64, volume: f64) {
88        if close > open {
89            self.obv.push_back(volume);
90        } else if close < open {
91            self.obv.push_back(-volume);
92        } else {
93            self.obv.push_back(0.0);
94        }
95
96        self.value = self.obv.iter().sum();
97
98        // Initialization logic
99        if !self.initialized {
100            self.has_inputs = true;
101            if self.period == 0 && !self.obv.is_empty() || self.obv.len() >= self.period {
102                self.initialized = true;
103            }
104        }
105    }
106}
107
108////////////////////////////////////////////////////////////////////////////////
109// Tests
110////////////////////////////////////////////////////////////////////////////////
111#[cfg(test)]
112mod tests {
113    use rstest::rstest;
114
115    use super::*;
116    use crate::stubs::obv_10;
117
118    #[rstest]
119    fn test_name_returns_expected_string(obv_10: OnBalanceVolume) {
120        assert_eq!(obv_10.name(), "OnBalanceVolume");
121    }
122
123    #[rstest]
124    fn test_str_repr_returns_expected_string(obv_10: OnBalanceVolume) {
125        assert_eq!(format!("{obv_10}"), "OnBalanceVolume(10)");
126    }
127
128    #[rstest]
129    fn test_period_returns_expected_value(obv_10: OnBalanceVolume) {
130        assert_eq!(obv_10.period, 10);
131    }
132
133    #[rstest]
134    fn test_initialized_without_inputs_returns_false(obv_10: OnBalanceVolume) {
135        assert!(!obv_10.initialized());
136    }
137
138    #[rstest]
139    fn test_value_with_all_higher_inputs_returns_expected_value(mut obv_10: OnBalanceVolume) {
140        let open_values = [
141            104.25, 105.50, 106.75, 108.00, 109.25, 110.50, 111.75, 113.00, 114.25, 115.50, 116.75,
142            118.00, 119.25, 120.50, 121.75,
143        ];
144
145        let close_values = [
146            105.50, 106.75, 108.00, 109.25, 110.50, 111.75, 113.00, 114.25, 115.50, 116.75, 118.00,
147            119.25, 120.50, 121.75, 123.00,
148        ];
149
150        let volume_values = [
151            1000.0, 1200.0, 1500.0, 1800.0, 2000.0, 2200.0, 2500.0, 2800.0, 3000.0, 3200.0, 3500.0,
152            3800.0, 4000.0, 4200.0, 4500.0,
153        ];
154        for i in 0..15 {
155            obv_10.update_raw(open_values[i], close_values[i], volume_values[i]);
156        }
157
158        assert!(obv_10.initialized());
159        assert_eq!(obv_10.value, 41200.0);
160    }
161
162    #[rstest]
163    fn test_reset_successfully_returns_indicator_to_fresh_state(mut obv_10: OnBalanceVolume) {
164        obv_10.update_raw(1.00020, 1.00050, 1000.0);
165        obv_10.update_raw(1.00030, 1.00060, 1200.0);
166        obv_10.update_raw(1.00070, 1.00080, 1500.0);
167
168        obv_10.reset();
169
170        assert!(!obv_10.initialized());
171        assert_eq!(obv_10.value, 0.0);
172        assert_eq!(obv_10.obv.len(), 0);
173        assert!(!obv_10.has_inputs);
174        assert!(!obv_10.initialized);
175    }
176}