use crate::{KandError, TAFloat};
pub const fn lookback(param_period: usize) -> Result<usize, KandError> {
#[cfg(feature = "check")]
{
if param_period < 2 {
return Err(KandError::InvalidParameter);
}
}
Ok(param_period)
}
pub fn rocr100(
input_price: &[TAFloat],
param_period: usize,
output_rocr100: &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_rocr100.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 {
output_rocr100[i] = (input_price[i] / input_price[i - param_period]) * 100.0;
}
for value in output_rocr100.iter_mut().take(lookback) {
*value = TAFloat::NAN;
}
Ok(())
}
pub fn rocr100_inc(input: TAFloat, prev: TAFloat) -> Result<TAFloat, KandError> {
#[cfg(feature = "deep-check")]
{
if input.is_nan() || prev.is_nan() {
return Err(KandError::NaNDetected);
}
}
Ok((input / prev) * 100.0)
}
#[cfg(test)]
mod tests {
use approx::assert_relative_eq;
use super::*;
#[test]
fn test_rocr100_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 = 10;
let mut output_rocr100 = vec![0.0; input_price.len()];
rocr100(&input_price, param_period, &mut output_rocr100).unwrap();
for value in output_rocr100.iter().take(10) {
assert!(value.is_nan());
}
let expected_values = [
99.883_575_978_032_78,
100.024_133_055_471_95,
100.061_948_185_173_93,
99.973_557_008_814_31,
99.740_772_849_366_86,
99.394_688_920_027_45,
99.421_920_983_558_12,
99.323_440_722_344_05,
99.634_634_179_603_15,
99.544_972_672_781_07,
];
for (i, expected) in expected_values.iter().enumerate() {
assert_relative_eq!(output_rocr100[i + 10], *expected, epsilon = 0.0001);
}
for i in 11..input_price.len() {
let result = rocr100_inc(input_price[i], input_price[i - param_period]).unwrap();
assert_relative_eq!(result, output_rocr100[i], epsilon = 0.0001);
}
}
}