fast-ta 0.2.1

High-performance technical analysis indicators with batch, prepared, and streaming APIs
//! Average Deviation (AVGDEV).

use crate::{
    period_lookback, validate_finite_slice, validate_input_len, validate_output_len, CompactOutput,
    Float, IndicatorConfig, OutputRange, PreparedBatchRunner, Result, StreamingComputation,
    TalibError,
};

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::vec::Vec;
fn validate_avgdev_input(real: &[Float], timeperiod: usize) -> Result<(usize, usize)> {
    let lookback = period_lookback("timeperiod", timeperiod)?;
    validate_finite_slice("real", real)?;
    let count = validate_input_len(real.len(), lookback)?;
    Ok((lookback, count))
}

fn avgdev_kernel(
    real: &[Float],
    timeperiod: usize,
    lookback: usize,
    count: usize,
    out_real: &mut [Float],
) -> OutputRange {
    if count == 0 {
        return OutputRange::empty();
    }

    let period = timeperiod as Float;
    for output_idx in 0..count {
        let window = &real[output_idx..output_idx + timeperiod];
        let mean = window.iter().copied().sum::<Float>() / period;
        let deviation = window
            .iter()
            .map(|value| (*value - mean).abs())
            .sum::<Float>()
            / period;
        out_real[output_idx] = deviation;
    }

    OutputRange::new(lookback, count)
}

/// TA-Lib-style Average Deviation batch function.
#[allow(non_snake_case)]
pub fn AVGDEV(real: &[Float], timeperiod: usize, out_real: &mut [Float]) -> Result<OutputRange> {
    let (lookback, count) = validate_avgdev_input(real, timeperiod)?;
    validate_output_len("AVGDEV", out_real.len(), count)?;
    Ok(avgdev_kernel(real, timeperiod, lookback, count, out_real))
}

/// Immutable Average Deviation Indicator Configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AVGDEVConfig {
    period: usize,
}

impl AVGDEVConfig {
    /// Creates a configuration for `timeperiod` observations.
    pub fn new(timeperiod: usize) -> Result<Self> {
        period_lookback("timeperiod", timeperiod)?;
        Ok(Self { period: timeperiod })
    }

    /// Returns the configured Period.
    #[inline]
    pub const fn period(&self) -> usize {
        self.period
    }
}

impl crate::traits::sealed::Sealed for AVGDEVConfig {}

impl IndicatorConfig for AVGDEVConfig {
    type Input<'a> = &'a [Float];
    type Output = Vec<Float>;
    type OutputMut<'a> = &'a mut [Float];
    type BatchRunner = AVGDEVBatchRunner;
    type Stream = AVGDEVStream;

    #[inline]
    fn lookback(&self) -> usize {
        self.period - 1
    }

    fn compute<'a>(&self, input: Self::Input<'a>) -> Result<CompactOutput<Self::Output>> {
        let (lookback, count) = validate_avgdev_input(input, self.period)?;
        let mut values = Vec::with_capacity(count);
        values.resize(count, 0.0 as Float);
        let range = avgdev_kernel(input, self.period, lookback, count, &mut values);
        CompactOutput::new(input.len(), range, values)
    }

    #[inline]
    fn compute_into<'a>(
        &self,
        input: Self::Input<'a>,
        output: Self::OutputMut<'a>,
    ) -> Result<OutputRange> {
        AVGDEV(input, self.period, output)
    }

    #[inline]
    fn prepare_batch(&self, max_input_len: usize) -> Result<Self::BatchRunner> {
        Ok(AVGDEVBatchRunner {
            config: *self,
            max_input_len,
        })
    }

    #[inline]
    fn stream(&self) -> Result<Self::Stream> {
        AVGDEVStream::new(self.period)
    }
}

/// Prepared Batch Runner for Average Deviation.
#[derive(Debug, Clone)]
pub struct AVGDEVBatchRunner {
    config: AVGDEVConfig,
    max_input_len: usize,
}

impl crate::traits::sealed::Sealed for AVGDEVBatchRunner {}

impl PreparedBatchRunner<AVGDEVConfig> for AVGDEVBatchRunner {
    #[inline]
    fn max_input_len(&self) -> usize {
        self.max_input_len
    }

    #[inline]
    fn compute_into<'a>(
        &mut self,
        input: <AVGDEVConfig as IndicatorConfig>::Input<'a>,
        output: <AVGDEVConfig as IndicatorConfig>::OutputMut<'a>,
    ) -> Result<OutputRange>
    where
        AVGDEVConfig: 'a,
    {
        if input.len() > self.max_input_len {
            return Err(TalibError::prepared_capacity_exceeded(
                self.max_input_len,
                input.len(),
            ));
        }
        IndicatorConfig::compute_into(&self.config, input, output)
    }
}

/// Independent Streaming Computation state for Average Deviation.
#[derive(Debug, Clone)]
pub struct AVGDEVStream {
    period: usize,
    buffer: Vec<Float>,
    index: usize,
    count: usize,
}

impl AVGDEVStream {
    fn new(period: usize) -> Result<Self> {
        period_lookback("timeperiod", period)?;
        let mut buffer = Vec::new();
        buffer.resize(period, 0.0 as Float);
        Ok(Self {
            period,
            buffer,
            index: 0,
            count: 0,
        })
    }
}

impl crate::traits::sealed::Sealed for AVGDEVStream {}

impl StreamingComputation<AVGDEVConfig> for AVGDEVStream {
    type Tick = Float;
    type TickOutput = Float;

    fn next(&mut self, input: Float) -> Result<Option<Float>> {
        validate_finite_slice("input", &[input])?;

        self.buffer[self.index] = input;
        if self.count < self.period {
            self.count += 1;
        }
        self.index = (self.index + 1) % self.period;

        if self.count < self.period {
            return Ok(None);
        }

        let mean = self.buffer.iter().copied().sum::<Float>() / self.period as Float;
        let deviation = self
            .buffer
            .iter()
            .map(|value| (*value - mean).abs())
            .sum::<Float>()
            / self.period as Float;
        Ok(Some(deviation))
    }

    fn reset(&mut self) {
        self.buffer.fill(0.0 as Float);
        self.index = 0;
        self.count = 0;
    }
}