use crate::common::{validate_inputs, validate_options};
pub use crate::indicator_types::TIndicatorState;
use crate::indicators::ef::calc as calc_ef;
use crate::indicators::ema::multiplier as ema_multiplier;
use crate::types::{
DisplayGroup, DisplayType, IndicatorError, IndicatorType, Info,
};
use serde::{Deserialize, Serialize};
pub const INPUTS_WIDTH: usize = 1;
pub const OPTIONS_WIDTH: usize = 1;
#[cfg(feature = "simd_assets")]
pub use crate::indicators::simd_indicators::kama_simd::indicator_by_assets;
#[cfg(feature = "simd_options")]
pub use crate::indicators::simd_indicators::kama_simd::indicator_by_options;
#[cfg(feature = "simd_assets")]
pub mod by_assets {
pub use crate::indicators::simd_indicators::kama_simd::indicator_by_assets as indicator;
}
#[cfg(feature = "simd_options")]
pub mod by_options {
pub use crate::indicators::simd_indicators::kama_simd::indicator_by_options as indicator;
}
pub const INFO: Info = Info {
name: "kama",
indicator_type: IndicatorType::Trend,
full_name: "Kaufman's Adaptive Moving Average",
inputs: &["real"],
options: &["period"],
outputs: &["kama"],
optional_outputs: &["ef"],
display_groups: &[
DisplayGroup {
offset: None,
id: "kama",
label: "KAMA",
display_type: DisplayType::Overlay,
outputs: &["kama"],
},
DisplayGroup {
offset: None,
id: "ef",
label: "Efficiency Ratio",
display_type: DisplayType::Indicator,
outputs: &["ef"],
},
],
};
#[derive(Serialize, Deserialize)]
pub struct IndicatorState {
real: Vec<f64>,
period: usize,
multipliers: (f64, f64),
state: State,
}
impl IndicatorState {
pub fn new(real: &[f64], period: usize, multipliers: (f64, f64), state: State) -> Self {
Self {
period,
multipliers,
state,
real: real[real.len() - period - 1..].to_vec(),
}
}
}
impl TIndicatorState<1> for IndicatorState {
fn batch_indicator(
&mut self,
inputs: &[&[f64]; INPUTS_WIDTH],
optional_outputs: Option<&[bool]>,
) -> Result<Vec<Vec<f64>>, IndicatorError> {
validate_inputs(inputs, 1)?;
self.real.extend_from_slice(inputs[0]);
let (mut kama_line, mut ef_line) = {
let capacity = inputs[0].len();
(
crate::uninit_vec!(f64, capacity),
crate::init_optional_outputs!(
optional_outputs, &[false],
ef_line: capacity
),
)
};
cycle_kama(
&self.real,
&mut self.state,
self.period,
self.multipliers,
&mut kama_line,
&mut ef_line,
);
self.real.drain(..self.real.len() - self.period - 1);
Ok(vec![kama_line, ef_line])
}
}
#[derive(Serialize, Deserialize)]
pub struct State {
pub kama: f64,
pub sum: f64,
}
impl State {
pub fn new(kama: f64, sum: f64) -> Self {
Self { kama, sum }
}
pub fn init_state(
real: &[f64],
period: usize,
kama_line: &mut [f64],
ef_line: &mut [f64],
) -> Self {
let mut state = Self::new(
real[period - 1],
(1..period).map(|i| (real[i] - real[i - 1]).abs()).sum(),
);
let multipliers = multiplier();
let values = unsafe {
(
real.get_unchecked(period),
real.get_unchecked(period - 1),
real.get_unchecked(0),
&0.0,
)
};
let (kama, efficiency_ratio) = state.calc(values, multipliers, period, period);
kama_line[0] = kama;
let (_, want_ef) = crate::calc_want_flags!(ef_line);
crate::store_optional_outputs!(0,
want_ef, ef_line => efficiency_ratio
);
state
}
#[inline(always)]
pub fn calc(
&mut self,
values: (&f64, &f64, &f64, &f64),
multipliers: (f64, f64),
period: usize,
i: usize,
) -> (f64, f64) {
let (fast_ema, slow_ema) = multipliers;
let efficiency_ratio = calc_ef(&mut self.sum, values, period, i);
let (value, _, _, _) = values;
let smoothing_constant = (fast_ema - slow_ema)
.mul_add(efficiency_ratio, slow_ema)
.powi(2);
let per1 = 1.0 - smoothing_constant;
self.kama = self.kama.mul_add(per1, value * smoothing_constant);
(self.kama, efficiency_ratio)
}
}
pub fn min_data(options: &[f64]) -> usize {
options[0] as usize + 1
}
pub fn output_length(data_len: usize, options: &[f64]) -> usize {
data_len - min_data(options) + 1
}
pub fn indicator(
inputs: &[&[f64]; INPUTS_WIDTH],
options: &[f64; OPTIONS_WIDTH],
optional_outputs: Option<&[bool]>,
) -> Result<(Vec<Vec<f64>>, IndicatorState), IndicatorError> {
validate_options(options)?;
let period = options[0] as usize;
let multipliers = multiplier();
validate_inputs(inputs, min_data(options))?;
let real = inputs[0];
let (mut kama_line, mut ef_line) = {
let capacity = output_length(real.len(), options);
(
crate::uninit_vec!(f64, capacity),
crate::init_optional_outputs!(
optional_outputs, &[false],
ef_line: capacity
),
)
};
let mut state = State::init_state(real, period, &mut kama_line, &mut ef_line);
let ef = {
let (_, want_ef) = crate::calc_want_flags!(ef_line);
if want_ef {
&mut ef_line[1..]
} else {
&mut ef_line
}
};
cycle_kama(
real,
&mut state,
period,
multipliers,
&mut kama_line[1..],
ef,
);
Ok((
vec![kama_line, ef_line],
IndicatorState::new(real, period, multipliers, state),
))
}
fn cycle_kama(
real: &[f64],
state: &mut State,
period: usize,
multipliers: (f64, f64),
kama_line: &mut [f64],
ef_line: &mut [f64],
) {
let (_, want_ef) = crate::calc_want_flags!(ef_line);
for (j, i) in (period + 1..real.len()).enumerate() {
let values = unsafe {
(
real.get_unchecked(i),
real.get_unchecked(i - 1),
real.get_unchecked(j + 1),
real.get_unchecked(j),
)
};
let (kama, efficiency_ratio) = state.calc(values, multipliers, period, i);
unsafe { *kama_line.get_unchecked_mut(j) = kama };
crate::store_optional_outputs!(j,
want_ef, ef_line => efficiency_ratio
);
}
}
#[inline(always)]
pub fn calc(
state: &mut State,
values: (&f64, &f64, &f64, &f64),
multipliers: (f64, f64),
period: usize,
i: usize,
) -> (f64, f64) {
state.calc(values, multipliers, period, i)
}
#[inline(always)]
pub fn multiplier() -> (f64, f64) {
(ema_multiplier(2).0, ema_multiplier(30).0)
}