nautilus_indicators/momentum/
cci.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::{
24    average::{MovingAverageFactory, MovingAverageType},
25    indicator::{Indicator, MovingAverage},
26};
27
28#[repr(C)]
29#[derive(Debug)]
30#[cfg_attr(
31    feature = "python",
32    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators", unsendable)
33)]
34pub struct CommodityChannelIndex {
35    pub period: usize,
36    pub ma_type: MovingAverageType,
37    pub scalar: f64,
38    pub value: f64,
39    pub initialized: bool,
40    ma: Box<dyn MovingAverage + Send + 'static>,
41    has_inputs: bool,
42    mad: f64,
43    prices: VecDeque<f64>,
44}
45
46impl Display for CommodityChannelIndex {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        write!(f, "{}({},{})", self.name(), self.period, self.ma_type,)
49    }
50}
51
52impl Indicator for CommodityChannelIndex {
53    fn name(&self) -> String {
54        stringify!(CommodityChannelIndex).to_string()
55    }
56
57    fn has_inputs(&self) -> bool {
58        self.has_inputs
59    }
60
61    fn initialized(&self) -> bool {
62        self.initialized
63    }
64
65    fn handle_bar(&mut self, bar: &Bar) {
66        self.update_raw((&bar.high).into(), (&bar.low).into(), (&bar.close).into());
67    }
68
69    fn reset(&mut self) {
70        self.ma.reset();
71        self.mad = 0.0;
72        self.prices.clear();
73        self.value = 0.0;
74        self.has_inputs = false;
75        self.initialized = false;
76    }
77}
78
79impl CommodityChannelIndex {
80    /// Creates a new [`CommodityChannelIndex`] instance.
81    #[must_use]
82    pub fn new(period: usize, scalar: f64, ma_type: Option<MovingAverageType>) -> Self {
83        Self {
84            period,
85            scalar,
86            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
87            value: 0.0,
88            prices: VecDeque::with_capacity(period),
89            ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
90            has_inputs: false,
91            initialized: false,
92            mad: 0.0,
93        }
94    }
95
96    pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
97        let typical_price = (high + low + close) / 3.0;
98        self.prices.push_back(typical_price);
99        self.ma.update_raw(typical_price);
100        self.mad = fast_mad_with_mean(self.prices.clone(), self.ma.value());
101
102        if self.ma.initialized() {
103            self.value = (typical_price - self.ma.value()) / (self.scalar * self.mad);
104        }
105
106        if !self.initialized {
107            self.has_inputs = true;
108            if self.ma.initialized() {
109                self.initialized = true;
110            }
111        }
112    }
113}
114
115fn fast_mad_with_mean(values: VecDeque<f64>, mean: f64) -> f64 {
116    if values.is_empty() {
117        return 0.0;
118    }
119
120    let mut mad: f64 = 0.0;
121    for v in values.clone() {
122        let dev = (v - mean).abs();
123        mad += dev;
124    }
125
126    mad / values.len() as f64
127}
128
129////////////////////////////////////////////////////////////////////////////////
130// Tests
131////////////////////////////////////////////////////////////////////////////////
132#[cfg(test)]
133mod tests {
134    use nautilus_model::data::Bar;
135    use rstest::rstest;
136
137    use crate::{
138        indicator::Indicator,
139        momentum::cci::CommodityChannelIndex,
140        stubs::{bar_ethusdt_binance_minute_bid, cci_10},
141    };
142
143    #[rstest]
144    fn test_psl_initialized(cci_10: CommodityChannelIndex) {
145        let display_str = format!("{cci_10}");
146        assert_eq!(display_str, "CommodityChannelIndex(10,SIMPLE)");
147        assert_eq!(cci_10.period, 10);
148        assert!(!cci_10.initialized);
149        assert!(!cci_10.has_inputs);
150    }
151
152    #[rstest]
153    fn test_value_with_one_input(mut cci_10: CommodityChannelIndex) {
154        cci_10.update_raw(1.0, 0.9, 0.95);
155        assert_eq!(cci_10.value, 0.0);
156    }
157
158    #[rstest]
159    fn test_value_with_three_inputs(mut cci_10: CommodityChannelIndex) {
160        cci_10.update_raw(1.0, 0.9, 0.95);
161        cci_10.update_raw(2.0, 1.9, 1.95);
162        cci_10.update_raw(3.0, 2.9, 2.95);
163        assert_eq!(cci_10.value, 0.0);
164    }
165
166    #[rstest]
167    fn test_value_with_ten_inputs(mut cci_10: CommodityChannelIndex) {
168        cci_10.update_raw(1.00000, 0.90000, 1.00000);
169        cci_10.update_raw(1.00010, 0.90010, 1.00010);
170        cci_10.update_raw(1.00030, 0.90020, 1.00020);
171        cci_10.update_raw(1.00040, 0.90030, 1.00030);
172        cci_10.update_raw(1.00050, 0.90040, 1.00040);
173        cci_10.update_raw(1.00060, 0.90050, 1.00050);
174        cci_10.update_raw(1.00050, 0.90040, 1.00040);
175        cci_10.update_raw(1.00040, 0.90030, 1.00030);
176        cci_10.update_raw(1.00030, 0.90020, 1.00020);
177        cci_10.update_raw(1.00010, 0.90010, 1.00010);
178        cci_10.update_raw(1.00000, 0.90000, 1.00000);
179        assert_eq!(cci_10.value, -0.898_406_374_501_630_1);
180    }
181    #[rstest]
182    fn test_initialized_with_required_input(mut cci_10: CommodityChannelIndex) {
183        for i in 1..10 {
184            cci_10.update_raw(f64::from(i), f64::from(i), f64::from(i));
185        }
186        assert!(!cci_10.initialized);
187        cci_10.update_raw(10.0, 10.0, 10.0);
188        assert!(cci_10.initialized);
189    }
190
191    #[rstest]
192    fn test_handle_bar(mut cci_10: CommodityChannelIndex, bar_ethusdt_binance_minute_bid: Bar) {
193        cci_10.handle_bar(&bar_ethusdt_binance_minute_bid);
194        assert_eq!(cci_10.value, 0.0);
195        assert!(cci_10.has_inputs);
196        assert!(!cci_10.initialized);
197    }
198
199    #[rstest]
200    fn test_reset(mut cci_10: CommodityChannelIndex) {
201        cci_10.update_raw(1.0, 0.9, 0.95);
202        cci_10.reset();
203        assert_eq!(cci_10.value, 0.0);
204        assert_eq!(cci_10.prices.len(), 0);
205        assert_eq!(cci_10.mad, 0.0);
206        assert!(!cci_10.has_inputs);
207        assert!(!cci_10.initialized);
208    }
209}