use nautilus_core::python::to_pyvalue_err;
use nautilus_model::{
data::Bar,
enums::PriceType,
types::{Money, Price, Quantity, fixed::MAX_FLOAT_PRECISION},
};
use pyo3::prelude::*;
use crate::{indicator::Indicator, ratio::efficiency_ratio::EfficiencyRatio};
#[pymethods]
#[pyo3_stub_gen::derive::gen_stub_pymethods]
impl EfficiencyRatio {
#[new]
#[pyo3(signature = (period, price_type=None))]
fn py_new(period: usize, price_type: Option<PriceType>) -> PyResult<Self> {
Self::new_checked(period, price_type).map_err(to_pyvalue_err)
}
fn __repr__(&self) -> String {
format!("EfficiencyRatio({})", self.period)
}
#[getter]
#[pyo3(name = "name")]
fn py_name(&self) -> String {
self.name()
}
#[getter]
#[pyo3(name = "period")]
const fn py_period(&self) -> usize {
self.period
}
#[getter]
#[pyo3(name = "value")]
const fn py_value(&self) -> f64 {
self.value
}
#[getter]
#[pyo3(name = "initialized")]
const fn py_initialized(&self) -> bool {
self.initialized
}
#[getter]
#[pyo3(name = "has_inputs")]
fn py_has_inputs(&self) -> bool {
self.has_inputs()
}
#[pyo3(name = "update_raw")]
fn py_update_raw(
&mut self,
#[gen_stub(override_type(type_repr = "float"))] value: &Bound<'_, PyAny>,
) -> PyResult<()> {
let value = extract_update_value(value)?;
self.update_raw(value);
Ok(())
}
#[pyo3(name = "handle_bar")]
fn py_handle_bar(&mut self, bar: &Bar) -> PyResult<()> {
check_float_precision(bar.close.precision)?;
self.handle_bar(bar);
Ok(())
}
#[pyo3(name = "reset")]
fn py_reset(&mut self) {
self.reset();
}
}
fn extract_update_value(value: &Bound<'_, PyAny>) -> PyResult<f64> {
if value.is_instance_of::<Price>() {
let price = value.extract::<Price>()?;
check_float_precision(price.precision)?;
return Ok(price.as_f64());
}
if value.is_instance_of::<Quantity>() {
let quantity = value.extract::<Quantity>()?;
check_float_precision(quantity.precision)?;
return Ok(quantity.as_f64());
}
if value.is_instance_of::<Money>() {
let money = value.extract::<Money>()?;
check_float_precision(money.currency.precision)?;
return Ok(money.as_f64());
}
value.extract()
}
fn check_float_precision(precision: u8) -> PyResult<()> {
if precision > MAX_FLOAT_PRECISION {
return Err(to_pyvalue_err(format!(
"Fixed-point precision {precision} exceeds maximum float precision {MAX_FLOAT_PRECISION}",
)));
}
Ok(())
}