quant-indicators 0.7.0

Pure indicator math library for trading — MA, RSI, Bollinger, MACD, ATR, HRP
Documentation
//! Momentum indicator.

use quant_primitives::Candle;

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

/// Momentum indicator.
///
/// Measures the rate of change in price over a specified period.
/// Simple but effective for identifying trend strength.
///
/// # Formula
///
/// Momentum = Close - Close[n periods ago]
///
/// # Example
///
/// ```
/// use quant_indicators::{Indicator, Momentum};
/// use quant_primitives::Candle;
/// use chrono::Utc;
/// use rust_decimal_macros::dec;
///
/// let ts = Utc::now();
/// let candles: Vec<Candle> = (0..15).map(|i| {
///     Candle::new(dec!(100), dec!(110), dec!(90), dec!(100) + rust_decimal::Decimal::from(i), dec!(1000), ts).unwrap()
/// }).collect();
/// let mom = Momentum::new(10).unwrap();
/// let series = mom.compute(&candles).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct Momentum {
    period: usize,
    name: String,
}

impl Momentum {
    /// Create a new Momentum 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: "Momentum period must be > 0".to_string(),
            });
        }
        Ok(Self {
            period,
            name: format!("Momentum({})", period),
        })
    }
}

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

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

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

        let mut values = Vec::with_capacity(candles.len() - self.period);

        for i in self.period..candles.len() {
            let current = candles[i].close();
            let past = candles[i - self.period].close();
            let momentum = current - past;
            values.push((candles[i].timestamp(), momentum));
        }

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

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