Skip to main content

wickra_core/indicators/
williams_r.rs

1//! Williams %R.
2
3use std::collections::VecDeque;
4
5use crate::error::{Error, Result};
6use crate::ohlcv::Candle;
7use crate::traits::Indicator;
8
9/// Williams %R: `-100 * (HH - close) / (HH - LL)` over the lookback window.
10///
11/// Values lie in `[-100, 0]` and approximate the mirror image of the fast
12/// Stochastic %K.
13///
14/// # Example
15///
16/// ```
17/// use wickra_core::{Candle, Indicator, WilliamsR};
18///
19/// let mut indicator = WilliamsR::new(5).unwrap();
20/// let mut last = None;
21/// for i in 0..80 {
22///     let base = 100.0 + f64::from(i);
23///     let candle =
24///         Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
25///     last = indicator.update(candle);
26/// }
27/// assert!(last.is_some());
28/// ```
29#[derive(Debug, Clone)]
30pub struct WilliamsR {
31    period: usize,
32    candles: VecDeque<Candle>,
33}
34
35impl WilliamsR {
36    /// # Errors
37    /// Returns [`Error::PeriodZero`] if `period == 0`.
38    pub fn new(period: usize) -> Result<Self> {
39        if period == 0 {
40            return Err(Error::PeriodZero);
41        }
42        if period > crate::error::MAX_PERIOD {
43            return Err(Error::InvalidPeriod {
44                message: crate::error::PERIOD_ABOVE_MAX,
45            });
46        }
47        Ok(Self {
48            period,
49            candles: VecDeque::with_capacity(period),
50        })
51    }
52
53    /// Configured period.
54    pub const fn period(&self) -> usize {
55        self.period
56    }
57}
58
59impl Indicator for WilliamsR {
60    type Input = Candle;
61    type Output = f64;
62
63    #[inline]
64    fn update(&mut self, candle: Candle) -> Option<f64> {
65        if self.candles.len() == self.period {
66            self.candles.pop_front();
67        }
68        self.candles.push_back(candle);
69        if self.candles.len() < self.period {
70            return None;
71        }
72        let hh = self
73            .candles
74            .iter()
75            .map(|c| c.high)
76            .fold(f64::NEG_INFINITY, f64::max);
77        let ll = self
78            .candles
79            .iter()
80            .map(|c| c.low)
81            .fold(f64::INFINITY, f64::min);
82        let range = hh - ll;
83        if range == 0.0 {
84            return Some(-50.0);
85        }
86        Some(-100.0 * (hh - candle.close) / range)
87    }
88
89    fn reset(&mut self) {
90        self.candles.clear();
91    }
92
93    #[inline]
94    fn warmup_period(&self) -> usize {
95        self.period
96    }
97
98    #[inline]
99    fn is_ready(&self) -> bool {
100        self.candles.len() == self.period
101    }
102
103    #[inline]
104    fn name(&self) -> &'static str {
105        "WilliamsR"
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::traits::BatchExt;
113    use approx::assert_relative_eq;
114
115    fn c(h: f64, l: f64, cl: f64) -> Candle {
116        Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
117    }
118
119    #[test]
120    fn close_at_high_yields_zero() {
121        let candles = vec![c(10.0, 8.0, 9.0), c(11.0, 9.0, 10.0), c(12.0, 10.0, 12.0)];
122        let mut w = WilliamsR::new(3).unwrap();
123        let out = w.batch(&candles);
124        assert_relative_eq!(out[2].unwrap(), 0.0, epsilon = 1e-12);
125    }
126
127    #[test]
128    fn close_at_low_yields_minus_100() {
129        let candles = vec![c(12.0, 10.0, 11.0), c(11.0, 9.0, 10.0), c(10.0, 8.0, 8.0)];
130        let mut w = WilliamsR::new(3).unwrap();
131        let out = w.batch(&candles);
132        assert_relative_eq!(out[2].unwrap(), -100.0, epsilon = 1e-12);
133    }
134
135    #[test]
136    fn within_range() {
137        let candles: Vec<Candle> = (0..100)
138            .map(|i| {
139                let m = 50.0 + (f64::from(i) * 0.3).sin() * 5.0;
140                c(m + 1.0, m - 1.0, m)
141            })
142            .collect();
143        let mut w = WilliamsR::new(14).unwrap();
144        for v in w.batch(&candles).into_iter().flatten() {
145            assert!((-100.0..=0.0).contains(&v), "%R out of range: {v}");
146        }
147    }
148
149    #[test]
150    fn batch_equals_streaming() {
151        let candles: Vec<Candle> = (0..30)
152            .map(|i| c(f64::from(i) + 2.0, f64::from(i), f64::from(i) + 1.0))
153            .collect();
154        let mut a = WilliamsR::new(5).unwrap();
155        let mut b = WilliamsR::new(5).unwrap();
156        assert_eq!(
157            a.batch(&candles),
158            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
159        );
160    }
161
162    #[test]
163    fn rejects_zero_period() {
164        assert!(WilliamsR::new(0).is_err());
165    }
166
167    /// Cover the const accessor `period` (49-51) and the Indicator-impl
168    /// `warmup_period` (87-89) + `name` (95-97). Existing tests never
169    /// inspect these metadata methods.
170    #[test]
171    fn accessors_and_metadata() {
172        let w = WilliamsR::new(14).unwrap();
173        assert_eq!(w.period(), 14);
174        assert_eq!(w.warmup_period(), 14);
175        assert_eq!(w.name(), "WilliamsR");
176    }
177
178    /// Cover the `range == 0.0` defensive branch (line 78). All other
179    /// tests use H != L candles so the lookback range is always positive.
180    /// Feed a stream of perfectly flat candles (H == L == close) — the
181    /// lookback hi/lo coincide and the divide-by-zero guard fires,
182    /// returning the neutral mid-range value -50.0.
183    #[test]
184    fn zero_range_yields_minus_fifty() {
185        let candles: Vec<Candle> = (0..5).map(|_| c(10.0, 10.0, 10.0)).collect();
186        let mut w = WilliamsR::new(3).unwrap();
187        let last = w
188            .batch(&candles)
189            .into_iter()
190            .flatten()
191            .last()
192            .expect("emits");
193        assert_eq!(last, -50.0);
194    }
195
196    #[test]
197    fn reset_clears_state() {
198        let candles: Vec<Candle> = (0..20)
199            .map(|i| c(f64::from(i) + 2.0, f64::from(i), f64::from(i) + 1.0))
200            .collect();
201        let mut w = WilliamsR::new(5).unwrap();
202        w.batch(&candles);
203        assert!(w.is_ready());
204        w.reset();
205        assert!(!w.is_ready());
206        assert_eq!(w.update(candles[0]), None);
207    }
208}