1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
//! John Ehlers TrendFlex Indicators
//! from: https://financial-hacker.com/petra-on-programming-a-new-zero-lag-indicator/

use std::collections::VecDeque;

use super::View;
use crate::Echo;

/// John Ehlers TrendFlex Indicators
/// from: https://financial-hacker.com/petra-on-programming-a-new-zero-lag-indicator/
#[derive(Clone)]
pub struct TrendFlex<V> {
    view: V,
    window_len: usize,
    last_val: f64,
    last_m: f64,
    q_filts: VecDeque<f64>,
    out: f64,
}

impl<V> std::fmt::Debug for TrendFlex<V>
where
    V: View,
{
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(
            fmt,
            "TrendFlex(window_len: {}, last_val: {}, last_m: {}, q_filts: {:?}, out: {})",
            self.window_len, self.last_val, self.last_m, self.q_filts, self.out
        )
    }
}

/// Create a new TrendFlex Indicator with a given window length
#[inline(always)]
pub fn new_final(window_len: usize) -> TrendFlex<Echo> {
    TrendFlex::new(Echo::new(), window_len)
}

impl<V> TrendFlex<V>
where
    V: View,
{
    /// Create a new TrendFlex Indicator with a chained View
    /// and a given sliding window length
    #[inline]
    pub fn new(view: V, window_len: usize) -> Self {
        TrendFlex {
            view,
            window_len,
            last_val: 0.0,
            last_m: 0.0,
            q_filts: VecDeque::new(),
            out: 0.0,
        }
    }
}

impl<V> View for TrendFlex<V>
where
    V: View,
{
    fn update(&mut self, val: f64) {
        self.view.update(val);
        let val = self.view.last();

        if self.q_filts.len() == 0 {
            self.last_val = val;
        }
        if self.q_filts.len() > self.window_len {
            self.q_filts.pop_front();
        }
        let a1 = (-8.88442402435 / self.window_len as f64).exp();
        let b1 = 2.0 * a1 * (4.44221201218 / self.window_len as f64).cos();
        let c3 = -a1 * a1;
        let c1 = 1.0 - b1 - c3;

        let l = self.q_filts.len();
        let mut filt: f64 = 0.0;
        if l == 0 {
            filt = c1 * (val + self.last_val) / 2.0
        } else if l == 1 {
            let filt1 = self.q_filts.get(l - 1).unwrap();
            filt = c1 * (val + self.last_val) / 2.0 + b1 * filt1
        } else if l > 1 {
            let filt2 = self.q_filts.get(l - 2).unwrap();
            let filt1 = self.q_filts.get(l - 1).unwrap();
            filt = c1 * (val + self.last_val) / 2.0 + b1 * filt1 + c3 * filt2;
        }
        self.last_val = val;
        self.q_filts.push_back(filt);

        // sum the differences
        let mut d_sum: f64 = 0.0;
        for i in 0..self.q_filts.len() {
            let index = self.q_filts.len() - 1 - i;
            d_sum += filt - *self.q_filts.get(index).unwrap();
        }
        d_sum /= self.window_len as f64;

        // normalize in terms of standard deviation;
        let ms0 = 0.04 * d_sum.powi(2) + 0.96 * self.last_m;
        self.last_m = ms0;
        if ms0 > 0.0 {
            self.out = d_sum / ms0.sqrt();
        } else {
            self.out = 0.0;
        }
    }

    #[inline(always)]
    fn last(&self) -> f64 {
        self.out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plot::plot_values;
    use crate::test_data::TEST_DATA;

    #[test]
    fn trend_flex_plot() {
        let mut tf = new_final(16);
        let mut out: Vec<f64> = Vec::new();
        for v in &TEST_DATA {
            tf.update(*v);
            out.push(tf.last());
        }
        let filename = "img/trend_flex.png";
        plot_values(out, filename).unwrap();
    }
}