mylittleindicators 0.1.8

Multi-stream financial indicators library — 556 bar indicators + 21 event primitives across 35 categories. Consumes 27 stream kinds from digdigdig3 exchange connectors: OHLCV bars, ticks, orderbook (snapshot/delta/L3), funding/predicted funding/funding settlement, mark price, index price, open interest, liquidations, ticker, agg trades, long/short ratio, option greeks, volatility index, historical volatility, basis (derived), composite index, settlement events, block trades, insurance fund, risk limit, market warning, and three kline-family variants. Live-verified on 12 exchanges (89% pass-rate on a 150s BTC slice).
Documentation
// Spectral Crest Factor: max magnitude / RMS magnitude of spectrum

use crate::bar_indicators::signal_processing::fft::FastFourierTransform;
use crate::bar_indicators::indicator_value::IndicatorValue;

#[derive(Clone)]
pub struct SpectralCrest {
    window: usize,
    fft: FastFourierTransform,
    buf: Vec<f64>,
    idx: usize,
    filled: bool,
    pub value: f64,
}

impl SpectralCrest {
    pub fn new(window: usize) -> Self {
        let w = window.clamp(16, 256);
        Self {
            window: w,
            fft: FastFourierTransform::new(w, 1.0),
            buf: vec![0.0; w],
            idx: 0,
            filled: false,
            value: 0.0,
        }
    }

    #[inline]
    pub fn reset(&mut self) {
        self.idx = 0;
        self.filled = false;
        self.buf.fill(0.0);
        self.value = 0.0;
        self.fft.reset();
    }

    #[inline]
    pub fn is_ready(&self) -> bool {
        self.filled && self.fft.is_ready()
    }

    pub fn update_bar(&mut self, _o: f64, _h: f64, _l: f64, c: f64, _v: f64) -> f64 {
        let n = self.window;
        self.buf[self.idx] = c;
        self.idx = (self.idx + 1) % n;
        if !self.filled && self.idx == 0 {
            self.filled = true;
        }
        if self.filled {
            let mut mean = 0.0;
            for i in 0..n {
                mean += self.buf[i];
            }
            mean /= n as f64;
            for i in 0..n {
                self.fft.update(self.buf[(self.idx + i) % n] - mean);
            }
            let fd = self.fft.frequency_domain();
            let mut max_mag = 0.0;
            let mut sum_pow = 0.0;
            let mut count = 0.0;
            for i in 0..fd.magnitudes.len() {
                let m = fd.magnitudes[i];
                if m > max_mag {
                    max_mag = m;
                }
            }
            for i in 0..fd.power_spectrum.len() {
                sum_pow += fd.power_spectrum[i];
                count += 1.0;
            }
            let rms = if count > 0.0 {
                (sum_pow / count).sqrt()
            } else {
                0.0
            };
            self.value = if rms > 0.0 { max_mag / rms } else { 0.0 };
        }
        self.value
    }

    #[inline]
    pub fn value(&self) -> IndicatorValue {
        IndicatorValue::Single(self.value)
    }

    pub fn window(&self) -> usize {
        self.window
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_spectral_crest_creation() {
        let sc = SpectralCrest::new(64);
        assert!(!sc.is_ready());
        assert_eq!(sc.value().main(), 0.0);
        assert_eq!(sc.window(), 64);
    }

    #[test]
    fn test_spectral_crest_warmup() {
        let mut sc = SpectralCrest::new(64);
        for i in 0..70 {
            let price = 100.0 + (i as f64 * 0.1).sin() * 5.0;
            sc.update_bar(price, price + 1.0, price - 1.0, price, 1000.0);
        }
        assert!(sc.is_ready());
    }

    #[test]
    fn test_spectral_crest_finite() {
        let mut sc = SpectralCrest::new(64);
        for i in 0..100 {
            let price = 100.0 + (i as f64 * 0.2).sin() * 10.0;
            let value = sc.update_bar(price, price + 1.0, price - 1.0, price, 1000.0);
            assert!(value.is_finite(), "Crest should be finite");
        }
    }

    #[test]
    fn test_spectral_crest_reset() {
        let mut sc = SpectralCrest::new(64);
        for i in 0..70 {
            sc.update_bar(100.0 + i as f64, 101.0, 99.0, 100.0 + i as f64, 1000.0);
        }
        sc.reset();
        assert!(!sc.is_ready());
        assert_eq!(sc.value().main(), 0.0);
    }
}