quant-indicators 0.7.0

Pure indicator math library for trading — MA, RSI, Bollinger, MACD, ATR, HRP
Documentation
//! Simple Moving Average (SMA) indicator.

use quant_primitives::Candle;
use rust_decimal::Decimal;

use crate::error::IndicatorError;
use crate::indicator::Indicator;
use crate::series::Series;

/// Simple Moving Average indicator.
///
/// Computes the arithmetic mean of closing prices over the specified period.
///
/// # Formula
///
/// SMA = (P1 + P2 + ... + Pn) / n
///
/// where P is the closing price and n is the period.
///
/// # Example
///
/// ```
/// use quant_indicators::{Indicator, Sma};
/// use quant_primitives::Candle;
/// use chrono::Utc;
/// use rust_decimal_macros::dec;
///
/// let ts = Utc::now();
/// let candles: Vec<Candle> = (0..20).map(|i| {
///     Candle::new(dec!(100), dec!(110), dec!(90), dec!(100) + rust_decimal::Decimal::from(i), dec!(1000), ts).unwrap()
/// }).collect();
/// let sma = Sma::new(20).unwrap();
/// let series = sma.compute(&candles).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct Sma {
    period: usize,
    name: String,
}

impl Sma {
    /// Create a new SMA indicator with the specified period.
    ///
    /// # Errors
    ///
    /// Returns `InvalidParameter` if period is 0.
    pub fn new(period: usize) -> Result<Self, IndicatorError> {
        if period == 0 {
            return Err(IndicatorError::InvalidParameter {
                message: "SMA period must be > 0".to_string(),
            });
        }
        Ok(Self {
            period,
            name: format!("SMA({})", period),
        })
    }
}

impl Indicator for Sma {
    fn name(&self) -> &str {
        &self.name
    }

    fn warmup_period(&self) -> usize {
        self.period
    }

    fn compute(&self, candles: &[Candle]) -> Result<Series, IndicatorError> {
        if candles.len() < self.period {
            return Err(IndicatorError::InsufficientData {
                required: self.period,
                actual: candles.len(),
            });
        }

        let mut values = Vec::with_capacity(candles.len() - self.period + 1);
        let period_dec = Decimal::from(self.period as u64);

        for window in candles.windows(self.period) {
            let sum: Decimal = window.iter().map(|c| c.close()).sum();
            let avg = sum / period_dec;
            // Safe: windows(n) always yields slices of length n when n > 0
            let ts = window[self.period - 1].timestamp();
            values.push((ts, avg));
        }

        Ok(Series::new(values))
    }
}

#[cfg(test)]
#[path = "sma_tests.rs"]
mod tests;