Skip to main content

wickra_core/indicators/
tsf_oscillator.rs

1//! Time Series Forecast Oscillator (TSF Oscillator).
2
3use crate::error::{Error, Result};
4use crate::indicators::tsf::Tsf;
5use crate::traits::Indicator;
6
7/// Time Series Forecast Oscillator — the percentage gap between the close and
8/// the **one-bar-ahead** time-series forecast of the close.
9///
10/// ```text
11/// TSFOsc_t = 100 · (close_t − TSF(close, period)_t) / close_t
12/// ```
13///
14/// where [`Tsf`](crate::Tsf) projects the rolling least-squares line one bar
15/// past the window (`a + b·period`). It is the close-relative companion to
16/// [`Cfo`](crate::Cfo), which measures the same percentage gap against the
17/// regression value at the *current* bar (`a + b·(period − 1)`). Because `TSF`
18/// advances one bar further than `LinearRegression`, the two differ by exactly
19/// the slope term `100·b/close`: on a trending series `TSFOsc` reads more
20/// negative in an uptrend (the forecast has already stepped above price) and
21/// more positive in a downtrend.
22///
23/// Positive readings mean the close sits *above* its forward forecast (price
24/// has overshot the projected trend); negative readings mean it sits below.
25/// Wraps the existing `Tsf` so the warmup matches.
26///
27/// # Example
28///
29/// ```
30/// use wickra_core::{Indicator, TsfOscillator};
31///
32/// let mut indicator = TsfOscillator::new(14).unwrap();
33/// let mut last = None;
34/// for i in 0..40 {
35///     last = indicator.update(100.0 + f64::from(i));
36/// }
37/// assert!(last.is_some());
38/// ```
39#[derive(Debug, Clone)]
40pub struct TsfOscillator {
41    period: usize,
42    tsf: Tsf,
43    current: Option<f64>,
44}
45
46impl TsfOscillator {
47    /// Construct a new TSF oscillator over `period` inputs.
48    ///
49    /// # Errors
50    /// Returns [`Error::InvalidPeriod`] if `period < 2` — a regression line is
51    /// undefined for fewer than two points.
52    pub fn new(period: usize) -> Result<Self> {
53        if period < 2 {
54            return Err(Error::InvalidPeriod {
55                message: "TSF oscillator needs period >= 2",
56            });
57        }
58        if period > crate::error::MAX_PERIOD {
59            return Err(Error::InvalidPeriod {
60                message: crate::error::PERIOD_ABOVE_MAX,
61            });
62        }
63        Ok(Self {
64            period,
65            tsf: Tsf::new(period)?,
66            current: None,
67        })
68    }
69
70    /// Configured period.
71    pub const fn period(&self) -> usize {
72        self.period
73    }
74}
75
76impl Indicator for TsfOscillator {
77    type Input = f64;
78    type Output = f64;
79
80    #[inline]
81    fn update(&mut self, input: f64) -> Option<f64> {
82        if !input.is_finite() {
83            return None;
84        }
85        let forecast = self.tsf.update(input)?;
86        // Hold the previous value if the close is zero — the percentage form
87        // is undefined and a return of inf would propagate badly.
88        if input == 0.0 {
89            return self.current;
90        }
91        let value = 100.0 * (input - forecast) / input;
92        self.current = Some(value);
93        Some(value)
94    }
95
96    fn reset(&mut self) {
97        self.tsf.reset();
98        self.current = None;
99    }
100
101    #[inline]
102    fn warmup_period(&self) -> usize {
103        self.period
104    }
105
106    #[inline]
107    fn is_ready(&self) -> bool {
108        self.current.is_some()
109    }
110
111    #[inline]
112    fn name(&self) -> &'static str {
113        "TsfOscillator"
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use crate::traits::BatchExt;
121    use approx::assert_relative_eq;
122
123    #[test]
124    fn rejects_short_period() {
125        assert!(matches!(
126            TsfOscillator::new(1),
127            Err(Error::InvalidPeriod { .. })
128        ));
129        assert!(matches!(
130            TsfOscillator::new(0),
131            Err(Error::InvalidPeriod { .. })
132        ));
133    }
134
135    #[test]
136    fn accessors_and_metadata() {
137        let osc = TsfOscillator::new(14).unwrap();
138        assert_eq!(osc.period(), 14);
139        assert_eq!(osc.warmup_period(), 14);
140        assert_eq!(osc.name(), "TsfOscillator");
141        assert!(!osc.is_ready());
142    }
143
144    #[test]
145    fn reference_value() {
146        // period 3 over [1, 2, 9]: fit y = 0 + 4x, one-bar-ahead TSF at x = 3
147        // is 12. With close = 9, TSFOsc = 100·(9 − 12)/9 = −33.3333…%.
148        let mut osc = TsfOscillator::new(3).unwrap();
149        let out = osc.batch(&[1.0_f64, 2.0, 9.0]);
150        assert!(out[0].is_none());
151        assert!(out[1].is_none());
152        assert_relative_eq!(out[2].unwrap(), -100.0 / 3.0, epsilon = 1e-9);
153        assert!(osc.is_ready());
154    }
155
156    #[test]
157    fn constant_series_yields_zero() {
158        // On a flat series the regression slope is 0, so the one-bar-ahead TSF
159        // equals the constant and close − forecast is exactly 0.
160        let mut osc = TsfOscillator::new(5).unwrap();
161        let out = osc.batch(&[42.0_f64; 30]);
162        for v in out.iter().skip(4).flatten() {
163            assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
164        }
165    }
166
167    #[test]
168    fn linear_uptrend_reads_negative() {
169        // Unlike CFO (evaluated at the current bar), the forecast steps one bar
170        // ahead, so on a rising line the projection sits above the close and the
171        // oscillator is negative: TSFOsc = −100·slope/close.
172        let mut osc = TsfOscillator::new(5).unwrap();
173        let prices: Vec<f64> = (1..=20).map(|i| f64::from(i) * 2.0).collect();
174        let out = osc.batch(&prices);
175        for v in out.iter().skip(4).flatten() {
176            assert!(*v < 0.0, "uptrend forecast overshoots close, got {v}");
177        }
178    }
179
180    #[test]
181    fn warmup_emits_first_value_at_period() {
182        let mut osc = TsfOscillator::new(3).unwrap();
183        assert_eq!(osc.update(1.0), None);
184        assert_eq!(osc.update(2.0), None);
185        assert!(osc.update(3.0).is_some());
186    }
187
188    #[test]
189    fn batch_equals_streaming() {
190        let prices: Vec<f64> = (1..=80)
191            .map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 5.0)
192            .collect();
193        let mut a = TsfOscillator::new(14).unwrap();
194        let mut b = TsfOscillator::new(14).unwrap();
195        assert_eq!(
196            a.batch(&prices),
197            prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
198        );
199    }
200
201    #[test]
202    fn reset_clears_state() {
203        let mut osc = TsfOscillator::new(5).unwrap();
204        osc.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
205        assert!(osc.is_ready());
206        osc.reset();
207        assert!(!osc.is_ready());
208        assert_eq!(osc.update(1.0), None);
209    }
210
211    #[test]
212    fn zero_close_holds_value() {
213        let mut osc = TsfOscillator::new(3).unwrap();
214        osc.batch(&[1.0_f64, 2.0, 3.0]);
215        let before = osc.current;
216        assert_eq!(osc.update(0.0), before);
217    }
218}