Skip to main content

wickra_core/indicators/
weighted_close.rs

1//! Weighted Close.
2
3use crate::ohlcv::Candle;
4use crate::traits::Indicator;
5
6/// Weighted Close — the bar's `(high + low + 2·close) / 4`.
7///
8/// A representative per-bar price that, unlike the [`TypicalPrice`](crate::TypicalPrice),
9/// gives the close double weight — useful when the closing print matters more
10/// than the extremes for your strategy. As a stateless per-bar transform it
11/// emits a value from the very first candle.
12///
13/// # Example
14///
15/// ```
16/// use wickra_core::{Candle, Indicator, WeightedClose};
17///
18/// let mut indicator = WeightedClose::new();
19/// let mut last = None;
20/// for i in 0..80 {
21///     let base = 100.0 + f64::from(i);
22///     let candle =
23///         Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
24///     last = indicator.update(candle);
25/// }
26/// assert!(last.is_some());
27/// ```
28#[derive(Debug, Clone, Default)]
29pub struct WeightedClose {
30    has_emitted: bool,
31}
32
33impl WeightedClose {
34    /// Construct a new Weighted Close transform.
35    pub const fn new() -> Self {
36        Self { has_emitted: false }
37    }
38}
39
40impl Indicator for WeightedClose {
41    type Input = Candle;
42    type Output = f64;
43
44    fn update(&mut self, candle: Candle) -> Option<f64> {
45        self.has_emitted = true;
46        Some(candle.weighted_close())
47    }
48
49    fn reset(&mut self) {
50        self.has_emitted = false;
51    }
52
53    fn warmup_period(&self) -> usize {
54        1
55    }
56
57    fn is_ready(&self) -> bool {
58        self.has_emitted
59    }
60
61    fn name(&self) -> &'static str {
62        "WeightedClose"
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69    use crate::traits::BatchExt;
70    use approx::assert_relative_eq;
71
72    fn candle(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
73        Candle::new(open, high, low, close, 1.0, ts).unwrap()
74    }
75
76    #[test]
77    fn reference_value() {
78        // (high + low + 2·close) / 4 = (12 + 8 + 2·11) / 4 = 42 / 4 = 10.5.
79        let mut wc = WeightedClose::new();
80        assert_relative_eq!(
81            wc.update(candle(10.0, 12.0, 8.0, 11.0, 0)).unwrap(),
82            10.5,
83            epsilon = 1e-12
84        );
85    }
86
87    /// Cover the Indicator-impl `name` body (61-63).
88    #[test]
89    fn name_metadata() {
90        let wc = WeightedClose::new();
91        assert_eq!(wc.name(), "WeightedClose");
92    }
93
94    #[test]
95    fn emits_from_first_candle() {
96        let mut wc = WeightedClose::new();
97        assert_eq!(wc.warmup_period(), 1);
98        assert!(!wc.is_ready());
99        assert!(wc.update(candle(10.0, 11.0, 9.0, 10.0, 0)).is_some());
100        assert!(wc.is_ready());
101    }
102
103    #[test]
104    fn reset_clears_state() {
105        let mut wc = WeightedClose::new();
106        wc.update(candle(10.0, 11.0, 9.0, 10.0, 0));
107        assert!(wc.is_ready());
108        wc.reset();
109        assert!(!wc.is_ready());
110    }
111
112    #[test]
113    fn batch_equals_streaming() {
114        let candles: Vec<Candle> = (0..40)
115            .map(|i| {
116                let base = 100.0 + i as f64;
117                candle(base, base + 2.0, base - 2.0, base + 1.0, i)
118            })
119            .collect();
120        let mut a = WeightedClose::new();
121        let mut b = WeightedClose::new();
122        assert_eq!(
123            a.batch(&candles),
124            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
125        );
126    }
127}