Skip to content

Commit

Permalink
Port KeltnerPosition indicator to Rust (nautechsystems#1763)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pushkarm029 authored Jul 2, 2024
1 parent 9dd1de5 commit 8d209d5
Show file tree
Hide file tree
Showing 7 changed files with 365 additions and 1 deletion.
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 @@ -66,5 +66,6 @@ pub fn indicators(_: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_class::<crate::volatility::dc::DonchianChannel>()?;
m.add_class::<crate::volatility::rvi::RelativeVolatilityIndex>()?;
m.add_class::<crate::volatility::kc::KeltnerChannel>()?;
m.add_class::<crate::volatility::kp::KeltnerPosition>()?;
Ok(())
}
111 changes: 111 additions & 0 deletions nautilus_core/indicators/src/python/volatility/kp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// -------------------------------------------------------------------------------------------------
// 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::{exceptions::PyPermissionError, prelude::*};

use super::atr;
use crate::{average::MovingAverageType, indicator::Indicator, volatility::kp::KeltnerPosition};

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

fn __repr__(&self) -> String {
format!("KeltnerPosition({})", 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 = "k_multiplier")]
fn py_k_multiplier(&self) -> f64 {
self.k_multiplier
}

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

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

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

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

#[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_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/volatility/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@
pub mod atr;
pub mod dc;
pub mod kc;
pub mod kp;
pub mod rvi;
pub mod vr;
16 changes: 15 additions & 1 deletion nautilus_core/indicators/src/stubs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ use crate::{
},
ratio::{efficiency_ratio::EfficiencyRatio, spread_analyzer::SpreadAnalyzer},
volatility::{
dc::DonchianChannel, kc::KeltnerChannel, rvi::RelativeVolatilityIndex, vr::VolatilityRatio,
dc::DonchianChannel, kc::KeltnerChannel, kp::KeltnerPosition, rvi::RelativeVolatilityIndex,
vr::VolatilityRatio,
},
};

Expand Down Expand Up @@ -298,6 +299,19 @@ pub fn kc_10() -> KeltnerChannel {
.unwrap()
}

#[fixture]
pub fn kp_10() -> KeltnerPosition {
KeltnerPosition::new(
10,
2.0,
Some(MovingAverageType::Simple),
Some(MovingAverageType::Simple),
Some(true),
Some(0.0),
)
.unwrap()
}

#[fixture]
pub fn roc_10() -> RateOfChange {
RateOfChange::new(10, Some(true)).unwrap()
Expand Down
206 changes: 206 additions & 0 deletions nautilus_core/indicators/src/volatility/kp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
// -------------------------------------------------------------------------------------------------
// 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 nautilus_model::data::bar::Bar;

use super::kc::KeltnerChannel;
use crate::{average::MovingAverageType, indicator::Indicator};

#[repr(C)]
#[derive(Debug)]
#[cfg_attr(
feature = "python",
pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")
)]
pub struct KeltnerPosition {
pub period: usize,
pub k_multiplier: f64,
pub ma_type: MovingAverageType,
pub ma_type_atr: MovingAverageType,
pub use_previous: bool,
pub atr_floor: f64,
pub value: f64,
pub initialized: bool,
has_inputs: bool,
kc: KeltnerChannel,
}

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

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

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

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

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

fn reset(&mut self) {
self.kc.reset();
self.value = 0.0;
self.has_inputs = false;
self.initialized = false;
}
}

impl KeltnerPosition {
/// Creates a new [`KeltnerPosition`] instance.
pub fn new(
period: usize,
k_multiplier: f64,
ma_type: Option<MovingAverageType>,
ma_type_atr: Option<MovingAverageType>,
use_previous: Option<bool>,
atr_floor: Option<f64>,
) -> anyhow::Result<Self> {
Ok(Self {
period,
k_multiplier,
ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
ma_type_atr: ma_type_atr.unwrap_or(MovingAverageType::Simple),
use_previous: use_previous.unwrap_or(true),
atr_floor: atr_floor.unwrap_or(0.0),
value: 0.0,
has_inputs: false,
initialized: false,
kc: KeltnerChannel::new(
period,
k_multiplier,
ma_type,
ma_type_atr,
use_previous,
atr_floor,
)
.unwrap(),
})
}

pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
self.kc.update_raw(high, low, close);

// Initialization logic
if !self.initialized {
self.has_inputs = true;
if self.kc.initialized() {
self.initialized = true;
}
}

let k_width = (self.kc.upper - self.kc.lower) / 2.0;

if k_width > 0.0 {
self.value = (close - self.kc.middle) / k_width;
} else {
self.value = 0.0;
}
}
}

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

use super::*;
use crate::stubs::kp_10;

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

#[rstest]
fn test_str_repr_returns_expected_string(kp_10: KeltnerPosition) {
assert_eq!(
format!("{kp_10}"),
"KeltnerPosition(10,2,SIMPLE,SIMPLE,true)"
);
}

#[rstest]
fn test_period_returns_expected_value(kp_10: KeltnerPosition) {
assert_eq!(kp_10.period, 10);
assert_eq!(kp_10.k_multiplier, 2.0);
}

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

#[rstest]
fn test_value_with_all_higher_inputs_returns_expected_value(mut kp_10: KeltnerPosition) {
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..15 {
kp_10.update_raw(high_values[i], low_values[i], close_values[i]);
}

assert!(kp_10.initialized());
assert_eq!(kp_10.value, 0.471_631_205_673_758_94);
}

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

kp_10.reset();

assert!(!kp_10.initialized());
assert!(!kp_10.has_inputs);
assert_eq!(kp_10.value, 0.0);
assert_eq!(kp_10.kc.upper, 0.0);
assert_eq!(kp_10.kc.middle, 0.0);
assert_eq!(kp_10.kc.lower, 0.0);
}
}
1 change: 1 addition & 0 deletions nautilus_core/indicators/src/volatility/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@
pub mod atr;
pub mod dc;
pub mod kc;
pub mod kp;
pub mod rvi;
pub mod vr;
Loading

0 comments on commit 8d209d5

Please sign in to comment.