Skip to main content

wickra_core/indicators/
beta.rs

1//! Rolling Beta — sensitivity of an asset to a benchmark.
2
3use std::collections::VecDeque;
4
5use crate::error::{Error, Result};
6use crate::traits::Indicator;
7
8/// Rolling Beta of an `asset` series relative to a `benchmark` series.
9///
10/// Each `update` receives one `(asset, benchmark)` pair. Over the trailing
11/// window of `period` pairs:
12///
13/// ```text
14/// cov_ab = (1/n) · Σ a·b − ā·b̄
15/// var_b  = (1/n) · Σ b² − b̄²
16/// Beta   = cov_ab / var_b
17/// ```
18///
19/// Beta measures how much the asset moves for a unit move in the
20/// benchmark. A reading of `1.0` means the two move together one-for-one;
21/// `2.0` means the asset typically doubles the benchmark's moves;
22/// `0.5` means it moves only half as much; `0.0` means moves are
23/// uncorrelated; negative Betas signal a hedge. It is the slope of the
24/// OLS regression of the asset on the benchmark and the foundation of the
25/// CAPM. Unlike [`crate::PearsonCorrelation`], Beta is *not* unit-free —
26/// it carries the ratio of standard deviations.
27///
28/// Each `update` is O(1): four running sums (`Σa`, `Σb`, `Σb²`, `Σa·b`)
29/// are maintained as the window slides. A flat benchmark window has zero
30/// variance and Beta is undefined; the indicator returns `0` in that
31/// case rather than producing `NaN`.
32///
33/// Conventionally Beta is computed on **returns** (typically log-returns)
34/// rather than raw prices; feed the indicator pre-computed returns if
35/// that is your convention. The pure rolling OLS slope is the same
36/// either way.
37///
38/// # Example
39///
40/// ```
41/// use wickra_core::{Beta, Indicator};
42///
43/// let mut indicator = Beta::new(20).unwrap();
44/// let mut last = None;
45/// for i in 0..40 {
46///     // Asset doubles every benchmark move.
47///     last = indicator.update((2.0 * f64::from(i), f64::from(i)));
48/// }
49/// assert!((last.unwrap() - 2.0).abs() < 1e-9);
50/// ```
51#[derive(Debug, Clone)]
52pub struct Beta {
53    period: usize,
54    window: VecDeque<(f64, f64)>,
55    sum_a: f64,
56    sum_b: f64,
57    sum_bb: f64,
58    sum_ab: f64,
59}
60
61impl Beta {
62    /// Construct a new rolling Beta.
63    ///
64    /// # Errors
65    /// Returns [`Error::InvalidPeriod`] if `period < 2`.
66    pub fn new(period: usize) -> Result<Self> {
67        if period < 2 {
68            return Err(Error::InvalidPeriod {
69                message: "beta needs period >= 2",
70            });
71        }
72        Ok(Self {
73            period,
74            window: VecDeque::with_capacity(period),
75            sum_a: 0.0,
76            sum_b: 0.0,
77            sum_bb: 0.0,
78            sum_ab: 0.0,
79        })
80    }
81
82    /// Configured period.
83    pub const fn period(&self) -> usize {
84        self.period
85    }
86}
87
88impl Indicator for Beta {
89    /// `(asset, benchmark)` pair.
90    type Input = (f64, f64);
91    type Output = f64;
92
93    fn update(&mut self, input: (f64, f64)) -> Option<f64> {
94        let (a, b) = input;
95        if self.window.len() == self.period {
96            let (oa, ob) = self.window.pop_front().expect("non-empty");
97            self.sum_a -= oa;
98            self.sum_b -= ob;
99            self.sum_bb -= ob * ob;
100            self.sum_ab -= oa * ob;
101        }
102        self.window.push_back((a, b));
103        self.sum_a += a;
104        self.sum_b += b;
105        self.sum_bb += b * b;
106        self.sum_ab += a * b;
107        if self.window.len() < self.period {
108            return None;
109        }
110        let n = self.period as f64;
111        let mean_a = self.sum_a / n;
112        let mean_b = self.sum_b / n;
113        let var_b = (self.sum_bb / n - mean_b * mean_b).max(0.0);
114        let cov = self.sum_ab / n - mean_a * mean_b;
115        if var_b == 0.0 {
116            // A flat benchmark has no defined beta.
117            return Some(0.0);
118        }
119        Some(cov / var_b)
120    }
121
122    fn reset(&mut self) {
123        self.window.clear();
124        self.sum_a = 0.0;
125        self.sum_b = 0.0;
126        self.sum_bb = 0.0;
127        self.sum_ab = 0.0;
128    }
129
130    fn warmup_period(&self) -> usize {
131        self.period
132    }
133
134    fn is_ready(&self) -> bool {
135        self.window.len() == self.period
136    }
137
138    fn name(&self) -> &'static str {
139        "Beta"
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use crate::traits::BatchExt;
147    use approx::assert_relative_eq;
148
149    #[test]
150    fn rejects_period_below_two() {
151        assert!(Beta::new(0).is_err());
152        assert!(Beta::new(1).is_err());
153        assert!(Beta::new(2).is_ok());
154    }
155
156    #[test]
157    fn accessors_and_metadata() {
158        let b = Beta::new(14).unwrap();
159        assert_eq!(b.period(), 14);
160        assert_eq!(b.warmup_period(), 14);
161        assert_eq!(b.name(), "Beta");
162    }
163
164    #[test]
165    fn perfect_two_to_one_relationship() {
166        let pairs: Vec<(f64, f64)> = (0..10)
167            .map(|i| (2.0 * f64::from(i), f64::from(i)))
168            .collect();
169        let last = Beta::new(5)
170            .unwrap()
171            .batch(&pairs)
172            .into_iter()
173            .flatten()
174            .last()
175            .unwrap();
176        assert_relative_eq!(last, 2.0, epsilon = 1e-9);
177    }
178
179    #[test]
180    fn perfect_negative_one() {
181        let pairs: Vec<(f64, f64)> = (0..10).map(|i| (-f64::from(i), f64::from(i))).collect();
182        let last = Beta::new(5)
183            .unwrap()
184            .batch(&pairs)
185            .into_iter()
186            .flatten()
187            .last()
188            .unwrap();
189        assert_relative_eq!(last, -1.0, epsilon = 1e-9);
190    }
191
192    #[test]
193    fn constant_benchmark_yields_zero() {
194        let pairs: Vec<(f64, f64)> = (0..10).map(|i| (f64::from(i), 7.0)).collect();
195        let last = Beta::new(5)
196            .unwrap()
197            .batch(&pairs)
198            .into_iter()
199            .flatten()
200            .last()
201            .unwrap();
202        assert_relative_eq!(last, 0.0, epsilon = 1e-12);
203    }
204
205    #[test]
206    fn reset_clears_state() {
207        let mut b = Beta::new(5).unwrap();
208        b.batch(&[(1.0, 2.0), (2.0, 4.0), (3.0, 6.0), (4.0, 8.0), (5.0, 10.0)]);
209        assert!(b.is_ready());
210        b.reset();
211        assert!(!b.is_ready());
212        assert_eq!(b.update((1.0, 1.0)), None);
213    }
214
215    #[test]
216    fn batch_equals_streaming() {
217        let pairs: Vec<(f64, f64)> = (0..60)
218            .map(|i| {
219                let t = f64::from(i);
220                (t.sin() * 2.0 + 0.3 * t.cos(), t.sin())
221            })
222            .collect();
223        let batch = Beta::new(14).unwrap().batch(&pairs);
224        let mut b = Beta::new(14).unwrap();
225        let streamed: Vec<_> = pairs.iter().map(|p| b.update(*p)).collect();
226        assert_eq!(batch, streamed);
227    }
228}