Skip to main content

weirdnet_plugin/
series.rs

1//! Vector math over columns: what math code spaces compile to, and handy in Rust ones.
2//! Missing values are `NaN`; windows that are not full yet give `NaN`.
3
4/// `n` copies of `v`.
5pub fn k(v: f64, n: usize) -> Vec<f64> {
6    vec![v; n]
7}
8
9/// Element by element (`a` and `b` have the same length).
10pub fn zip(a: &[f64], b: &[f64], f: impl Fn(f64, f64) -> f64) -> Vec<f64> {
11    a.iter().zip(b).map(|(x, y)| f(*x, *y)).collect()
12}
13
14pub fn map(a: &[f64], f: impl Fn(f64) -> f64) -> Vec<f64> {
15    a.iter().map(|x| f(*x)).collect()
16}
17
18/// `if(c, a, b)`: `a` where `c` is true (not 0, not NaN), else `b`.
19pub fn choose(c: &[f64], a: &[f64], b: &[f64]) -> Vec<f64> {
20    c.iter().enumerate().map(|(i, x)| if truthy(*x) { a[i] } else { b[i] }).collect()
21}
22
23pub fn truthy(x: f64) -> bool {
24    x != 0.0 && !x.is_nan()
25}
26
27pub fn flag(b: bool) -> f64 {
28    if b {
29        1.0
30    } else {
31        0.0
32    }
33}
34
35/// The first value of a window/period argument, as a count (at least 1).
36pub fn count_arg(w: &[f64]) -> usize {
37    w.first().copied().filter(|x| x.is_finite() && *x >= 1.0).unwrap_or(1.0) as usize
38}
39
40fn rolling(a: &[f64], n: usize, f: impl Fn(&[f64]) -> f64) -> Vec<f64> {
41    (0..a.len()).map(|i| if i + 1 < n { f64::NAN } else { f(&a[i + 1 - n..=i]) }).collect()
42}
43
44fn mean_of(w: &[f64]) -> f64 {
45    w.iter().sum::<f64>() / w.len() as f64
46}
47
48fn std_of(w: &[f64]) -> f64 {
49    if w.len() < 2 {
50        return f64::NAN;
51    }
52    let m = mean_of(w);
53    (w.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (w.len() - 1) as f64).sqrt()
54}
55
56/// Simple moving average over `n` values.
57pub fn sma(a: &[f64], n: &[f64]) -> Vec<f64> {
58    rolling(a, count_arg(n), mean_of)
59}
60
61/// Exponential moving average with span `n` (alpha = 2 / (n + 1)), seeded with the first value.
62pub fn ema(a: &[f64], n: &[f64]) -> Vec<f64> {
63    let alpha = 2.0 / (count_arg(n) as f64 + 1.0);
64    let mut out = Vec::with_capacity(a.len());
65    let mut prev = f64::NAN;
66    for &x in a {
67        prev = if prev.is_nan() {
68            x
69        } else if x.is_nan() {
70            prev
71        } else {
72            alpha * x + (1.0 - alpha) * prev
73        };
74        out.push(prev);
75    }
76    out
77}
78
79pub fn rolling_sum(a: &[f64], n: &[f64]) -> Vec<f64> {
80    rolling(a, count_arg(n), |w| w.iter().sum())
81}
82pub fn rolling_min(a: &[f64], n: &[f64]) -> Vec<f64> {
83    rolling(a, count_arg(n), |w| w.iter().copied().fold(f64::INFINITY, f64::min))
84}
85pub fn rolling_max(a: &[f64], n: &[f64]) -> Vec<f64> {
86    rolling(a, count_arg(n), |w| w.iter().copied().fold(f64::NEG_INFINITY, f64::max))
87}
88pub fn rolling_std(a: &[f64], n: &[f64]) -> Vec<f64> {
89    rolling(a, count_arg(n), std_of)
90}
91
92/// The value `n` rows earlier.
93pub fn lag(a: &[f64], n: &[f64]) -> Vec<f64> {
94    let n = count_arg(n);
95    (0..a.len()).map(|i| if i >= n { a[i - n] } else { f64::NAN }).collect()
96}
97
98/// The value `n` rows later.
99pub fn lead(a: &[f64], n: &[f64]) -> Vec<f64> {
100    let n = count_arg(n);
101    (0..a.len()).map(|i| a.get(i + n).copied().unwrap_or(f64::NAN)).collect()
102}
103
104/// Change from the previous row.
105pub fn diff(a: &[f64]) -> Vec<f64> {
106    (0..a.len()).map(|i| if i == 0 { f64::NAN } else { a[i] - a[i - 1] }).collect()
107}
108
109/// Change from the previous row in percent.
110pub fn pct_change(a: &[f64]) -> Vec<f64> {
111    (0..a.len()).map(|i| if i == 0 { f64::NAN } else { (a[i] - a[i - 1]) / a[i - 1] * 100.0 }).collect()
112}
113
114/// Running total (NaN counts as 0).
115pub fn cumsum(a: &[f64]) -> Vec<f64> {
116    let mut s = 0.0;
117    a.iter()
118        .map(|x| {
119            if !x.is_nan() {
120                s += x;
121            }
122            s
123        })
124        .collect()
125}
126
127fn finite(a: &[f64]) -> Vec<f64> {
128    a.iter().copied().filter(|x| !x.is_nan()).collect()
129}
130
131/// Aggregates: one value, repeated for every row.
132pub fn sum(a: &[f64]) -> Vec<f64> {
133    k(finite(a).iter().sum(), a.len())
134}
135pub fn mean(a: &[f64]) -> Vec<f64> {
136    let f = finite(a);
137    k(if f.is_empty() { f64::NAN } else { mean_of(&f) }, a.len())
138}
139pub fn min(a: &[f64]) -> Vec<f64> {
140    k(finite(a).into_iter().fold(f64::NAN, f64::min), a.len())
141}
142pub fn max(a: &[f64]) -> Vec<f64> {
143    k(finite(a).into_iter().fold(f64::NAN, f64::max), a.len())
144}
145pub fn std(a: &[f64]) -> Vec<f64> {
146    k(std_of(&finite(a)), a.len())
147}
148pub fn count(a: &[f64]) -> Vec<f64> {
149    k(finite(a).len() as f64, a.len())
150}
151pub fn first(a: &[f64]) -> Vec<f64> {
152    k(a.first().copied().unwrap_or(f64::NAN), a.len())
153}
154pub fn last(a: &[f64]) -> Vec<f64> {
155    k(a.last().copied().unwrap_or(f64::NAN), a.len())
156}
157
158/// Standard score against the whole column.
159pub fn zscore(a: &[f64]) -> Vec<f64> {
160    let f = finite(a);
161    let (m, s) = (mean_of(&f), std_of(&f));
162    map(a, |x| (x - m) / s)
163}
164
165/// Row number from 0.
166pub fn row(n: usize) -> Vec<f64> {
167    (0..n).map(|i| i as f64).collect()
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn windows_and_aggregates() {
176        let a = [1.0, 2.0, 3.0, 4.0];
177        let s = sma(&a, &[2.0]);
178        assert!(s[0].is_nan());
179        assert_eq!(&s[1..], &[1.5, 2.5, 3.5]);
180        assert_eq!(lag(&a, &[1.0])[1], 1.0);
181        assert_eq!(cumsum(&a), vec![1.0, 3.0, 6.0, 10.0]);
182        assert_eq!(sum(&a), vec![10.0; 4]);
183        assert_eq!(ema(&a, &[1.0]), a.to_vec());
184        assert_eq!(choose(&[1.0, 0.0], &[5.0, 5.0], &[7.0, 7.0]), vec![5.0, 7.0]);
185        assert_eq!(rolling_max(&a, &[3.0])[3], 4.0);
186        assert_eq!(pct_change(&a)[1], 100.0);
187    }
188}