Files
ferro-ta/src/momentum/cci.rs
T
2026-03-23 23:34:28 +05:30

44 lines
1.4 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use crate::validation;
use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1};
use pyo3::prelude::*;
/// Commodity Channel Index (TA-Libcompatible): (typical_price - SMA) / (0.015 * MAD).
#[pyfunction]
#[pyo3(signature = (high, low, close, timeperiod = 14))]
pub fn cci<'py>(
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
close: PyReadonlyArray1<'py, f64>,
timeperiod: usize,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
validation::validate_timeperiod(timeperiod, "timeperiod", 1)?;
let highs = high.as_slice()?;
let lows = low.as_slice()?;
let closes = close.as_slice()?;
let n = highs.len();
validation::validate_equal_length(&[
(n, "high"),
(lows.len(), "low"),
(closes.len(), "close"),
])?;
let tp: Vec<f64> = highs
.iter()
.zip(lows.iter())
.zip(closes.iter())
.map(|((&h, &l), &c)| (h + l + c) / 3.0)
.collect();
let mut result = vec![f64::NAN; n];
for i in (timeperiod - 1)..n {
let window = &tp[(i + 1 - timeperiod)..=i];
let mean: f64 = window.iter().sum::<f64>() / timeperiod as f64;
let mad: f64 = window.iter().map(|&x| (x - mean).abs()).sum::<f64>() / timeperiod as f64;
result[i] = if mad != 0.0 {
(tp[i] - mean) / (0.015 * mad)
} else {
0.0
};
}
Ok(result.into_pyarray(py))
}