Skip to content

Commit

Permalink
Port BollingerBands indicator to Rust (#1734)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pushkarm029 committed Jun 24, 2024
1 parent 20f1513 commit 815d760
Show file tree
Hide file tree
Showing 11 changed files with 375 additions and 4 deletions.
4 changes: 4 additions & 0 deletions nautilus_core/indicators/src/momentum/amat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ impl Indicator for ArcherMovingAveragesTrends {
self.slow_ma.reset();
self.long_run = false;
self.short_run = false;
self.fast_ma_price.clear();
self.slow_ma_price.clear();
self.has_inputs = false;
self.initialized = false;
}
}

Expand Down
223 changes: 223 additions & 0 deletions nautilus_core/indicators/src/momentum/bb.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
// -------------------------------------------------------------------------------------------------
// Copyright (C) 2015-2024 Nautech Systems Pty Ltd. All rights reserved.
// https://nautechsystems.io
//
// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -------------------------------------------------------------------------------------------------

use std::{
collections::VecDeque,
fmt::{Debug, Display},
};

use nautilus_model::data::{bar::Bar, quote::QuoteTick, trade::TradeTick};

use crate::{
average::{MovingAverageFactory, MovingAverageType},
indicator::{Indicator, MovingAverage},
};

#[repr(C)]
#[derive(Debug)]
#[cfg_attr(
feature = "python",
pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")
)]

pub struct BollingerBands {
pub period: usize,
pub k: f64,
pub ma_type: MovingAverageType,
pub upper: f64,
pub middle: f64,
pub lower: f64,
pub initialized: bool,
ma: Box<dyn MovingAverage + Send + 'static>,
prices: VecDeque<f64>,
has_inputs: bool,
}

impl Display for BollingerBands {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}({},{},{})",
self.name(),
self.period,
self.k,
self.ma_type,
)
}
}

impl Indicator for BollingerBands {
fn name(&self) -> String {
stringify!(BollingerBands).to_string()
}

fn has_inputs(&self) -> bool {
self.has_inputs
}

fn initialized(&self) -> bool {
self.initialized
}

fn handle_quote_tick(&mut self, tick: &QuoteTick) {
let bid = tick.bid_price.raw as f64;
let ask = tick.ask_price.raw as f64;
let mid = (bid + ask) / 2.0;
self.update_raw(ask, bid, mid);
}

fn handle_trade_tick(&mut self, tick: &TradeTick) {
let price = tick.price.raw as f64;
self.update_raw(price, price, price);
}

fn handle_bar(&mut self, bar: &Bar) {
self.update_raw((&bar.high).into(), (&bar.low).into(), (&bar.close).into());
}

fn reset(&mut self) {
self.ma.reset();
self.prices.clear();
self.upper = 0.0;
self.middle = 0.0;
self.lower = 0.0;
self.has_inputs = false;
self.initialized = false;
}
}

impl BollingerBands {
/// Creates a new [`BollingerBands`] instance.
pub fn new(period: usize, k: f64, ma_type: Option<MovingAverageType>) -> anyhow::Result<Self> {
Ok(Self {
period,
k,
ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
has_inputs: false,
initialized: false,
upper: 0.0,
middle: 0.0,
lower: 0.0,
ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
prices: VecDeque::with_capacity(period),
})
}

pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
let typical = (high + low + close) / 3.0;
self.prices.push_back(typical);
self.ma.update_raw(typical);

// Initialization logic
if !self.initialized {
self.has_inputs = true;
if self.prices.len() >= self.period {
self.initialized = true;
}
}

// Calculate values
let std = fast_std_with_mean(self.prices.clone(), self.ma.value());

self.upper = self.ma.value() + self.k * std;
self.middle = self.ma.value();
self.lower = self.ma.value() - self.k * std;
}
}

pub fn fast_std_with_mean(values: VecDeque<f64>, mean: f64) -> f64 {
if values.is_empty() {
return 0.0;
}

let mut std_dev = 0.0;
for v in &values {
let diff = v - mean;
std_dev += diff * diff;
}

(std_dev / values.len() as f64).sqrt()
}

////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
use rstest::rstest;

use super::*;
use crate::stubs::bb_10;

#[rstest]
fn test_name_returns_expected_string(bb_10: BollingerBands) {
assert_eq!(bb_10.name(), "BollingerBands");
}

#[rstest]
fn test_str_repr_returns_expected_string(bb_10: BollingerBands) {
assert_eq!(format!("{bb_10}"), "BollingerBands(10,0.1,SIMPLE)");
}

#[rstest]
fn test_period_returns_expected_value(bb_10: BollingerBands) {
assert_eq!(bb_10.period, 10);
assert_eq!(bb_10.k, 0.1);
}

#[rstest]
fn test_initialized_without_inputs_returns_false(bb_10: BollingerBands) {
assert!(!bb_10.initialized());
}

#[rstest]
fn test_value_with_all_higher_inputs_returns_expected_value(mut bb_10: BollingerBands) {
let high_values = [
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0,
];
let low_values = [
0.9, 1.9, 2.9, 3.9, 4.9, 5.9, 6.9, 7.9, 8.9, 9.9, 10.1, 10.2, 10.3, 11.1, 11.4,
];

let close_values = [
0.95, 1.95, 2.95, 3.95, 4.95, 5.95, 6.95, 7.95, 8.95, 9.95, 10.05, 10.15, 10.25, 11.05,
11.45,
];

for i in 0..10 {
bb_10.update_raw(high_values[i], low_values[i], close_values[i]);
}

assert!(bb_10.initialized());
assert_eq!(bb_10.upper, 5.737228132326901);
assert_eq!(bb_10.middle, 5.45);
assert_eq!(bb_10.lower, 5.162771867673099);
}

#[rstest]
fn test_reset_successfully_returns_indicator_to_fresh_state(mut bb_10: BollingerBands) {
bb_10.update_raw(1.00020, 1.00050, 1.00030);
bb_10.update_raw(1.00030, 1.00060, 1.00040);
bb_10.update_raw(1.00070, 1.00080, 1.00075);

bb_10.reset();

assert!(!bb_10.initialized());
assert_eq!(bb_10.upper, 0.0);
assert_eq!(bb_10.middle, 0.0);
assert_eq!(bb_10.lower, 0.0);
assert_eq!(bb_10.prices.len(), 0);
}
}
2 changes: 2 additions & 0 deletions nautilus_core/indicators/src/momentum/dm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ impl Indicator for DirectionalMovement {
self.previous_low = 0.0;
self.pos = 0.0;
self.neg = 0.0;
self.has_inputs = false;
self.initialized = false;
}
}

Expand Down
2 changes: 2 additions & 0 deletions nautilus_core/indicators/src/momentum/kvo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ impl Indicator for KlingerVolumeOscillator {
self.slow_ma.reset();
self.signal_ma.reset();
self.value = 0.0;
self.has_inputs = false;
self.initialized = false;
}
}

Expand Down
1 change: 1 addition & 0 deletions nautilus_core/indicators/src/momentum/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

pub mod amat;
pub mod aroon;
pub mod bb;
pub mod bias;
pub mod cmo;
pub mod dm;
Expand Down
2 changes: 1 addition & 1 deletion nautilus_core/indicators/src/momentum/swings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ impl Indicator for Swings {
fn reset(&mut self) {
self.high_inputs.clear();
self.low_inputs.clear();

self.has_inputs = false;
self.initialized = false;
self.direction = 0;
self.changed = false;
self.high_datetime = 0.0;
Expand Down
1 change: 1 addition & 0 deletions nautilus_core/indicators/src/python/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ pub fn indicators(_: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_class::<crate::momentum::dm::DirectionalMovement>()?;
m.add_class::<crate::momentum::amat::ArcherMovingAveragesTrends>()?;
m.add_class::<crate::momentum::swings::Swings>()?;
m.add_class::<crate::momentum::bb::BollingerBands>()?;
// volatility
m.add_class::<crate::volatility::atr::AverageTrueRange>()?;
Ok(())
Expand Down
105 changes: 105 additions & 0 deletions nautilus_core/indicators/src/python/momentum/bb.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// -------------------------------------------------------------------------------------------------
// Copyright (C) 2015-2024 Nautech Systems Pty Ltd. All rights reserved.
// https://nautechsystems.io
//
// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -------------------------------------------------------------------------------------------------

use nautilus_core::python::to_pyvalue_err;
use nautilus_model::data::{bar::Bar, quote::QuoteTick, trade::TradeTick};
use pyo3::prelude::*;

use crate::{average::MovingAverageType, indicator::Indicator, momentum::bb::BollingerBands};

#[pymethods]
impl BollingerBands {
#[new]
pub fn py_new(period: usize, k: f64, ma_type: Option<MovingAverageType>) -> PyResult<Self> {
Self::new(period, k, ma_type).map_err(to_pyvalue_err)
}

fn __repr__(&self) -> String {
format!("BollingerBands({})", self.period)
}

#[getter]
#[pyo3(name = "name")]
fn py_name(&self) -> String {
self.name()
}

#[getter]
#[pyo3(name = "period")]
fn py_period(&self) -> usize {
self.period
}

#[getter]
#[pyo3(name = "has_inputs")]
fn py_has_inputs(&self) -> bool {
self.has_inputs()
}

#[getter]
#[pyo3(name = "k")]
fn py_k(&self) -> f64 {
self.k
}

#[getter]
#[pyo3(name = "upper")]
fn py_upper(&self) -> f64 {
self.upper
}

#[getter]
#[pyo3(name = "middle")]
fn py_middle(&self) -> f64 {
self.middle
}

#[getter]
#[pyo3(name = "lower")]
fn py_lower(&self) -> f64 {
self.lower
}

#[getter]
#[pyo3(name = "initialized")]
fn py_initialized(&self) -> bool {
self.initialized
}

#[pyo3(name = "update_raw")]
fn py_update_raw(&mut self, high: f64, low: f64, close: f64) {
self.update_raw(high, low, close);
}

#[pyo3(name = "handle_quote_tick")]
fn py_handle_quote_tick(&mut self, tick: &QuoteTick) {
self.handle_quote_tick(tick);
}

#[pyo3(name = "handle_trade_tick")]
fn py_handle_trade_tick(&mut self, tick: &TradeTick) {
self.handle_trade_tick(tick);
}

#[pyo3(name = "handle_bar")]
fn py_handle_bar(&mut self, bar: &Bar) {
self.handle_bar(bar);
}

#[pyo3(name = "reset")]
fn py_reset(&mut self) {
self.reset();
}
}
1 change: 1 addition & 0 deletions nautilus_core/indicators/src/python/momentum/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

pub mod amat;
pub mod aroon;
pub mod bb;
pub mod bias;
pub mod cmo;
pub mod dm;
Expand Down
Loading

0 comments on commit 815d760

Please sign in to comment.