Skip to main content

nautilus_indicators/python/average/
zscore.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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 nautilus_core::python::to_pyvalue_err;
17use nautilus_model::{
18    data::{Bar, QuoteTick, TradeTick},
19    enums::PriceType,
20};
21use pyo3::prelude::*;
22
23use crate::{average::zscore::ZScore, indicator::Indicator, python::float_precision};
24
25#[pyo3_stub_gen::derive::gen_stub_pymethods]
26#[pymethods]
27impl ZScore {
28    /// Z-Score: how many standard deviations the latest price sits from its rolling
29    /// mean.
30    ///
31    /// ```text
32    /// ZScore = (price - SMA(price, n)) / population_stddev(price, n)
33    /// ```
34    ///
35    /// A reading of `+2` means price is two standard deviations above its recent
36    /// average, statistically stretched to the upside; `-2` is the mirror. It is the
37    /// standard normalization behind mean-reversion strategies: a large magnitude
38    /// flags an extension, a return toward `0` flags reversion. A window with zero
39    /// dispersion yields `0` rather than dividing by zero.
40    #[new]
41    #[pyo3(signature = (period, price_type=None))]
42    fn py_new(period: i64, price_type: Option<PriceType>) -> PyResult<Self> {
43        if period < 0 {
44            return Err(to_pyvalue_err("`period` must be positive"));
45        }
46
47        let period = usize::try_from(period).map_err(to_pyvalue_err)?;
48        Self::new_checked(period, price_type).map_err(to_pyvalue_err)
49    }
50
51    fn __repr__(&self) -> String {
52        format!("ZScore({})", self.period)
53    }
54
55    #[getter]
56    #[pyo3(name = "name")]
57    fn py_name(&self) -> String {
58        self.name()
59    }
60
61    #[getter]
62    #[pyo3(name = "period")]
63    const fn py_period(&self) -> usize {
64        self.period
65    }
66
67    #[getter]
68    #[pyo3(name = "price_type")]
69    const fn py_price_type(&self) -> PriceType {
70        self.price_type
71    }
72
73    #[getter]
74    #[pyo3(name = "count")]
75    const fn py_count(&self) -> usize {
76        self.count
77    }
78
79    #[getter]
80    #[pyo3(name = "value")]
81    const fn py_value(&self) -> f64 {
82        self.value
83    }
84
85    #[getter]
86    #[pyo3(name = "mean")]
87    const fn py_mean(&self) -> f64 {
88        self.mean
89    }
90
91    #[getter]
92    #[pyo3(name = "std")]
93    const fn py_std(&self) -> f64 {
94        self.std
95    }
96
97    #[getter]
98    #[pyo3(name = "has_inputs")]
99    fn py_has_inputs(&self) -> bool {
100        self.has_inputs()
101    }
102
103    #[getter]
104    #[pyo3(name = "initialized")]
105    const fn py_initialized(&self) -> bool {
106        self.initialized
107    }
108
109    #[pyo3(name = "handle_quote_tick")]
110    fn py_handle_quote_tick(&mut self, quote: &QuoteTick) -> PyResult<()> {
111        float_precision::check_quote(quote)?;
112        self.handle_quote(quote).map_err(to_pyvalue_err)
113    }
114
115    #[pyo3(name = "handle_trade_tick")]
116    fn py_handle_trade_tick(&mut self, trade: &TradeTick) -> PyResult<()> {
117        float_precision::check_trade(trade)?;
118        self.handle_trade(trade);
119        Ok(())
120    }
121
122    #[pyo3(name = "handle_bar")]
123    fn py_handle_bar(&mut self, bar: &Bar) -> PyResult<()> {
124        float_precision::check_bar(bar)?;
125        self.handle_bar(bar);
126        Ok(())
127    }
128
129    #[pyo3(name = "reset")]
130    fn py_reset(&mut self) {
131        self.reset();
132    }
133
134    /// Updates the indicator with the given raw price value.
135    #[pyo3(name = "update_raw")]
136    fn py_update_raw(&mut self, value: f64) {
137        self.update_raw(value);
138    }
139}