tulip_rs 0.1.15

High-performance technical analysis library — 100+ indicators and 60+ candlestick patterns with SIMD acceleration
Documentation
//! # Ehlers Super Smoother
//!
//! **Source:** John Ehlers, *Cycle Analytics for Traders* (2013), Chapter 2.
//! Also published as "Predictive Indicators for Effective Trading Strategies",
//! *Technical Analysis of Stocks & Commodities*, January 2014.
//!
//! A two-pole Butterworth-inspired IIR low-pass filter designed to remove
//! aliasing and high-frequency noise from sampled price data while preserving
//! cycle content below the cutoff frequency. Unlike a simple moving average it
//! has zero lag at DC and a much sharper roll-off, making it Ehlers' preferred
//! smoothing primitive for cycle analysis.
//!
//! ## Formula
//!
//! Given `ω = π / period` (note: π, not 2π — a half-cycle convention):
//!
//! ```text
//! a1 = 2 · exp(−√2 · ω) · cos(√2 · ω)      [Ehlers uses 1.414 for √2]
//! a2 = −exp(−2√2 · ω)
//! b0 = 1 − a1 − a2
//! SS = (b0 / 2) · (Price + Price[1]) + a1·SS[1] + a2·SS[2]
//! ```
//!
//! The `b0/2` feedforward ensures unit gain at DC so the smoother tracks
//! the mean of price without bias.
//!
//! ## Role in this library
//!
//! Used as the second stage of the [`roofingfilter`] (after the High Pass
//! filter) and transitively in [`hilberttransform`]. On its own it acts as a
//! high-quality low-pass filter for any price series.

use crate::common::{validate_inputs, validate_options};
pub use crate::indicator_types::TIndicatorState;
use crate::types::{DisplayGroup, DisplayType, IndicatorError, IndicatorType, Info};
use serde::{Deserialize, Serialize};

/// Number of input price series required by this indicator.
pub const INPUTS_WIDTH: usize = 1;

/// Number of option parameters required by this indicator.
pub const OPTIONS_WIDTH: usize = 1;

/// SIMD-parallel variant that processes `N` assets with identical options simultaneously.
/// Requires the `simd_assets` Cargo feature. See [`by_assets`] for the module form.
#[cfg(feature = "simd_assets")]
pub use crate::indicators::simd_indicators::supersmoother_simd::indicator_by_assets;

/// SIMD-parallel variant that processes a single asset with `N` different option
/// sets simultaneously. Requires the `simd_options` Cargo feature. See [`by_options`].
#[cfg(feature = "simd_options")]
pub use crate::indicators::simd_indicators::supersmoother_simd::indicator_by_options;

/// Convenience module that re-exports [`indicator_by_assets`] as `indicator`,
/// allowing SIMD multi-asset computation to be used as a drop-in replacement
/// for the standard single-asset [`indicator`] function.
/// Requires the `simd_assets` Cargo feature.
#[cfg(feature = "simd_assets")]
pub mod by_assets {
    /// Processes `N` assets in parallel with shared options.
    /// See the parent module's [`super::indicator_by_assets`] for full documentation.
    pub use crate::indicators::simd_indicators::supersmoother_simd::indicator_by_assets as indicator;
}

/// Convenience module that re-exports [`indicator_by_options`] as `indicator`,
/// allowing SIMD multi-option computation to be used as a drop-in replacement
/// for the standard single-asset [`indicator`] function.
/// Requires the `simd_options` Cargo feature.
#[cfg(feature = "simd_options")]
pub mod by_options {
    /// Processes a single asset with `N` different option sets in parallel.
    /// See the parent module's [`super::indicator_by_options`] for full documentation.
    pub use crate::indicators::simd_indicators::supersmoother_simd::indicator_by_options as indicator;
}

/// Returns metadata for the Ehlers Super Smoother indicator.
///
/// # Returns
///
/// An `Info` struct containing metadata about the SuperSmoother indicator, including
/// its input (`real`), configurable `period`, and output line (`supersmoother`).
pub const INFO: Info = Info {
    name: "supersmoother",
    indicator_type: IndicatorType::Math,
    full_name: "Ehlers Super Smoother",
    inputs: &["real"],
    options: &["period"],
    outputs: &["supersmoother"],
    optional_outputs: &[],
    display_groups: &[DisplayGroup {
        offset: None,
        id: "supersmoother",
        label: "Ehlers Super Smoother",
        display_type: DisplayType::Overlay,
        outputs: &["supersmoother"],
    }],
};
#[derive(Serialize, Deserialize)]
pub struct IndicatorState {
    multipliers: (f64, f64, f64),
    state: State,
}
impl IndicatorState {
    pub fn new(state: State, multipliers: (f64, f64, f64)) -> Self {
        Self { multipliers, state }
    }
}
impl TIndicatorState<1> for IndicatorState {
    fn batch_indicator(
        &mut self,
        inputs: &[&[f64]; INPUTS_WIDTH],
        _optional_outputs: Option<&[bool]>,
    ) -> Result<Vec<Vec<f64>>, IndicatorError> {
        validate_inputs(inputs, 1)?;

        let mut super_line = crate::uninit_vec!(f64, inputs[0].len());

        cycle(
            inputs[0],
            &mut self.state,
            self.multipliers,
            &mut super_line,
        );

        Ok(vec![super_line])
    }
}

#[derive(Serialize, Deserialize)]
pub struct State {
    // previous outputs
    pub y1: f64,        // y[t-1]
    pub y2: f64,        // y[t-2]
    pub prev_real: f64, // x[t-1] for Ehlers input averaging: (Close + Close[1]) / 2
}
impl State {
    pub fn new() -> Self {
        Self {
            y1: 0.0,
            y2: 0.0,
            prev_real: 0.0,
        }
    }
    pub fn init_state(real: &[f64], period: usize, multipliers: (f64, f64, f64)) -> Self {
        let mut state = Self::new();
        for &value in real.iter().take(period) {
            state.calc(value, multipliers);
        }
        state
    }
    #[inline(always)]
    pub fn calc(&mut self, real: f64, multipliers: (f64, f64, f64)) -> f64 {
        let (a1, a2, b0) = multipliers;
        // Ehlers: coeff/2 * (Close + Close[1]) + a1*y1 + a2*y2
        let y = (b0 * 0.5).mul_add(real + self.prev_real, a1.mul_add(self.y1, a2 * self.y2));
        self.y2 = self.y1;
        self.y1 = y;
        self.prev_real = real;
        y
    }
}


/// Returns the minimum amount of data required for the SuperSmoother indicator.
///
/// # Arguments
///
/// * `options` - A slice containing the options for the SuperSmoother calculation (`period`).
///
/// # Returns
///
/// The minimum number of input bars required (`period + 1`).
pub fn min_data(options: &[f64]) -> usize {
    options[0] as usize + 1
}

/// Returns the number of output values produced by the SuperSmoother indicator
/// given input data length and options.
///
/// # Arguments
///
/// * `data_len` - The length of the input data.
/// * `options` - A slice containing the options for the SuperSmoother calculation.
///
/// # Returns
///
/// The number of output values.
pub fn output_length(data_len: usize, options: &[f64]) -> usize {
    data_len - min_data(options) + 1
}

/// Calculates the Ehlers Super Smoother indicator over the full input dataset.
///
/// # Inputs
///
/// * `inputs[0]` — real (close) prices
///
/// # Options
///
/// * `options[0]` — period
///
/// # Outputs
///
/// * `outputs[0]` — `supersmoother` line
///
/// # Arguments
///
/// * `inputs` - Array of input price slices (see Inputs above).
/// * `options` - Array of indicator options (see Options above).
/// * `_optional_outputs` - Unused; SuperSmoother has no optional outputs.
///
/// # Returns
///
/// `Ok((outputs, state))` where `outputs[0]` is the `supersmoother` line and
/// `state` can be passed to `IndicatorState::batch_indicator` for streaming.
/// Returns `Err(IndicatorError)` if inputs are too short or options are invalid.
pub fn indicator(
    inputs: &[&[f64]; INPUTS_WIDTH],
    options: &[f64; OPTIONS_WIDTH],
    _optional_outputs: Option<&[bool]>,
) -> Result<(Vec<Vec<f64>>, IndicatorState), IndicatorError> {
    validate_options(options)?;
    let period = options[0] as usize;
    let multipliers = multiplier(period);
    validate_inputs(inputs, min_data(options))?;

    let mut super_line = {
        let capacity = output_length(inputs[0].len(), options);
        crate::uninit_vec!(f64, capacity)
    };
    let mut state = State::init_state(inputs[0], period, multipliers);

    let real = &inputs[0][period..];
    cycle(real, &mut state, multipliers, &mut super_line);

    Ok((vec![super_line], IndicatorState::new(state, multipliers)))
}

/// Performs the core filter loop for the SuperSmoother indicator.
///
/// # Arguments
///
/// * `real` - A slice of input price values.
/// * `state` - A mutable reference to the filter state (`y1`, `y2`).
/// * `multipliers` - The precomputed filter coefficients `(a1, a2, b0)`.
/// * `super_line` - Output slice for the filtered values (must be the same length as `real`).
fn cycle(real: &[f64], state: &mut State, multipliers: (f64, f64, f64), super_line: &mut [f64]) {
    for i in 0..real.len() {
        unsafe {
            *super_line.get_unchecked_mut(i) = state.calc(*real.get_unchecked(i), multipliers);
        }
    }
}

/// Calculates the SuperSmoother value for a single bar.
///
/// # Arguments
///
/// * `state` - A mutable reference to the current filter state (`y1`, `y2`).
/// * `real` - The current input price value.
/// * `multipliers` - The precomputed filter coefficients `(a1, a2, b0)`.
///
/// # Returns
///
/// The filtered output value for this bar.
#[inline(always)]
pub fn calc(state: &mut State, real: f64, multipliers: (f64, f64, f64)) -> f64 {
    state.calc(real, multipliers)
}

/// Computes the 2-pole SuperSmoother filter coefficients for a given period.
///
/// # Arguments
///
/// * `period` - The filter period. Controls the cutoff frequency of the smoother.
///
/// # Returns
///
/// A tuple `(a1, a2, b0)` where:
/// - `a1`, `a2` are the IIR feedback coefficients
/// - `b0` is the feedforward gain (`1 - a1 - a2`)
pub fn multiplier(period: usize) -> (f64, f64, f64) {
    let omega = std::f64::consts::PI / period as f64;

    let a1 = 2.0 * (-1.414 * omega).exp() * (1.414 * omega).cos();
    let a2 = -(-2.828 * omega).exp();
    let b0 = 1.0 - a1 - a2;

    (a1, a2, b0)
}