quant-indicators 0.7.0

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

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

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

/// Weighted Moving Average indicator.
///
/// Assigns linearly increasing weights to more recent prices.
/// Most recent price has weight = period, oldest has weight = 1.
///
/// # Formula
///
/// WMA = (P1*1 + P2*2 + ... + Pn*n) / (1 + 2 + ... + n)
///
/// where n = period and Pn is the most recent price.
///
/// # Example
///
/// ```
/// use quant_indicators::{Indicator, Wma};
/// 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 wma = Wma::new(20).unwrap();
/// let series = wma.compute(&candles).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct Wma {
    period: usize,
    weight_sum: Decimal,
    name: String,
}

impl Wma {
    /// Create a new WMA 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: "WMA period must be > 0".to_string(),
            });
        }
        // Sum of weights: 1 + 2 + ... + n = n(n+1)/2
        let weight_sum =
            Decimal::from(period as u64) * Decimal::from(period as u64 + 1) / Decimal::TWO;
        Ok(Self {
            period,
            weight_sum,
            name: format!("WMA({})", period),
        })
    }
}

impl Indicator for Wma {
    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);

        for window in candles.windows(self.period) {
            let weighted_sum: Decimal = window
                .iter()
                .enumerate()
                .map(|(i, c)| c.close() * Decimal::from((i + 1) as u64))
                .sum();

            let wma = weighted_sum / self.weight_sum;
            let ts = window[self.period - 1].timestamp();
            values.push((ts, wma));
        }

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

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