Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement AverageTrueRange in Rust #1502

Merged
merged 2 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions nautilus_core/indicators/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub mod average;
pub mod indicator;
pub mod momentum;
pub mod ratio;
pub mod volatility;

#[cfg(test)]
mod stubs;
Expand Down
3 changes: 3 additions & 0 deletions nautilus_core/indicators/src/python/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use pyo3::{prelude::*, pymodule};
pub mod average;
pub mod momentum;
pub mod ratio;
pub mod volatility;

#[pymodule]
pub fn indicators(_: Python<'_>, m: &PyModule) -> PyResult<()> {
Expand All @@ -33,5 +34,7 @@ pub fn indicators(_: Python<'_>, m: &PyModule) -> PyResult<()> {
// momentum
m.add_class::<crate::momentum::rsi::RelativeStrengthIndex>()?;
m.add_class::<crate::momentum::aroon::AroonOscillator>()?;
// volatility
m.add_class::<crate::volatility::atr::AverageTrueRange>()?;
Ok(())
}
101 changes: 101 additions & 0 deletions nautilus_core/indicators/src/python/volatility/atr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// -------------------------------------------------------------------------------------------------
// 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, volatility::atr::AverageTrueRange};

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

fn __repr__(&self) -> String {
format!(
"AverageTrueRange({},{},{},{})",
self.period, self.ma_type, self.use_previous, self.value_floor,
)
}

#[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 = "count")]
fn py_count(&self) -> usize {
self.count
}

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

#[getter]
#[pyo3(name = "initialized")]
fn py_initialized(&self) -> bool {
self.is_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) {
// Function body intentionally left blank.
}

#[pyo3(name = "handle_trade_tick")]
fn py_handle_trade_tick(&mut self, _tick: &TradeTick) {
// Function body intentionally left blank.
}

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

#[pyo3(name = "reset")]
fn py_reset(&mut self) {
self.reset();
}
}
16 changes: 16 additions & 0 deletions nautilus_core/indicators/src/python/volatility/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// -------------------------------------------------------------------------------------------------
// 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.
// -------------------------------------------------------------------------------------------------

pub mod atr;
149 changes: 149 additions & 0 deletions nautilus_core/indicators/src/volatility/atr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// -------------------------------------------------------------------------------------------------
// 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::fmt::{Debug, Display};

use anyhow::Result;
use nautilus_model::data::{bar::Bar, quote::QuoteTick, trade::TradeTick};
use pyo3::prelude::*;

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

/// An indicator which calculates a Average True Range (ATR) across a rolling window.
#[repr(C)]
#[derive(Debug)]
#[pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")]
pub struct AverageTrueRange {
pub period: usize,
pub ma_type: MovingAverageType,
pub use_previous: bool,
pub value_floor: f64,
pub value: f64,
pub count: usize,
pub is_initialized: bool,
has_inputs: bool,
_previous_close: f64,
_ma: Box<dyn MovingAverage + Send + 'static>,
}

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

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

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

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

fn handle_quote_tick(&mut self, _tick: &QuoteTick) {
// Function body intentionally left blank.
}

fn handle_trade_tick(&mut self, _tick: &TradeTick) {
// Function body intentionally left blank.
}

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

fn reset(&mut self) {
self._previous_close = 0.0;
self.value = 0.0;
self.count = 0;
self.has_inputs = false;
self.is_initialized = false;
}
}

impl AverageTrueRange {
pub fn new(
period: usize,
ma_type: Option<MovingAverageType>,
use_previous: Option<bool>,
value_floor: Option<f64>,
) -> Result<Self> {
Ok(Self {
period,
ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
use_previous: use_previous.unwrap_or(true),
value_floor: value_floor.unwrap_or(0.0),
value: 0.0,
count: 0,
_previous_close: 0.0,
_ma: MovingAverageFactory::create(MovingAverageType::Simple, period),
has_inputs: false,
is_initialized: false,
})
}

pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
if self.use_previous {
if !self.has_inputs {
self._previous_close = close;
}
self._ma.update_raw(
f64::max(self._previous_close, high) - f64::min(low, self._previous_close),
);
self._previous_close = close;
} else {
self._ma.update_raw(high - low);
}

self._floor_value();
self.increment_count();
}

fn _floor_value(&mut self) {
if self.value_floor == 0.0 || self.value_floor < self._ma.value() {
self.value = self._ma.value();
} else {
// Floor the value
self.value = self.value_floor;
}
}

fn increment_count(&mut self) {
self.count += 1;

if !self.is_initialized {
self.has_inputs = true;
if self.count >= self.period {
self.is_initialized = true;
}
}
}
}
16 changes: 16 additions & 0 deletions nautilus_core/indicators/src/volatility/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// -------------------------------------------------------------------------------------------------
// 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.
// -------------------------------------------------------------------------------------------------

pub mod atr;
31 changes: 31 additions & 0 deletions nautilus_trader/core/nautilus_pyo3.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,14 @@ class TriggerType(Enum):
MARK_PRICE = "MARK_PRICE"
INDEX_PRICE = "INDEX_PRICE"

class MovingAverageType(Enum):
SIMPLE = "SIMPLE"
EXPONENTIAL = "EXPONENTIAL"
DOUBLE_EXPONENTIAL = "DOUBLE_EXPONENTIAL"
WILDER = "WILDER"
HULL = "HULL"


### Identifiers

class AccountId:
Expand Down Expand Up @@ -1970,6 +1978,29 @@ class AroonOscillator:
def handle_bar(self, bar: Bar) -> None: ...
def reset(self) -> None: ...

class AverageTrueRange:
def __init__(
self,
period: int,
ma_type: MovingAverageType = ...,
use_previous: bool = True,
value_floor: float = 0.0,
) -> None: ...
@property
def name(self) -> str: ...
@property
def period(self) -> int: ...
@property
def count(self) -> int: ...
@property
def initialized(self) -> bool: ...
@property
def has_inputs(self) -> bool: ...
@property
def value(self) -> float: ...
def update_raw(self, high: float, low: float, close: float) -> None: ...
def handle_bar(self, bar: Bar) -> None: ...
def reset(self) -> None: ...

###################################################################################################
# Adapters
Expand Down
Loading