use crate::{KandError, TAFloat};
pub const fn lookback(param_period: usize) -> Result<usize, KandError> {
#[cfg(feature = "check")]
{
if param_period < 1 {
return Err(KandError::InvalidParameter);
}
}
Ok(param_period)
}
pub fn roc(
input_price: &[TAFloat],
param_period: usize,
output_roc: &mut [TAFloat],
) -> Result<(), KandError> {
let len = input_price.len();
let lookback = lookback(param_period)?;
#[cfg(feature = "check")]
{
if len == 0 {
return Err(KandError::InvalidData);
}
if len <= lookback {
return Err(KandError::InsufficientData);
}
if len != output_roc.len() {
return Err(KandError::LengthMismatch);
}
}
#[cfg(feature = "deep-check")]
{
for price in input_price {
if price.is_nan() {
return Err(KandError::NaNDetected);
}
}
}
for i in lookback..len {
let current_price = input_price[i];
let prev_price = input_price[i - param_period];
#[cfg(feature = "deep-check")]
{
if prev_price == 0.0 {
return Err(KandError::InvalidData);
}
}
output_roc[i] = (current_price - prev_price) / prev_price * 100.0;
}
for value in output_roc.iter_mut().take(lookback) {
*value = TAFloat::NAN;
}
Ok(())
}
pub fn roc_inc(current_price: TAFloat, prev_price: TAFloat) -> Result<TAFloat, KandError> {
#[cfg(feature = "deep-check")]
{
if current_price.is_nan() || prev_price.is_nan() {
return Err(KandError::NaNDetected);
}
if prev_price == 0.0 {
return Err(KandError::InvalidData);
}
}
Ok((current_price - prev_price) / prev_price * 100.0)
}
#[cfg(test)]
mod tests {
use approx::assert_relative_eq;
use super::*;
#[test]
fn test_roc_calculation() {
let input_price = vec![
35216.1, 35221.4, 35190.7, 35170.0, 35181.5, 35254.6, 35202.8, 35251.9, 35197.6,
35184.7, 35175.1, 35229.9, 35212.5, 35160.7, 35090.3, 35041.2, 34999.3, 35013.4,
35069.0, 35024.6,
];
let param_period = 14;
let mut output_roc = vec![0.0; input_price.len()];
roc(&input_price, param_period, &mut output_roc).unwrap();
for value in output_roc.iter().take(14) {
assert!(value.is_nan());
}
let expected_values = [
-0.357_222_974_718_940_4,
-0.511_620_776_005_505_8,
-0.543_893_699_187_547_6,
-0.445_265_851_578_047_2,
-0.319_770_333_840_230_24,
-0.652_397_133_991_022_8,
];
for (i, expected) in expected_values.iter().enumerate() {
assert_relative_eq!(output_roc[i + 14], *expected, epsilon = 0.0001);
}
for i in 15..20 {
let result = roc_inc(input_price[i], input_price[i - param_period]).unwrap();
assert_relative_eq!(result, output_roc[i], epsilon = 0.0001);
}
}
}