1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//! Ehlers' Laguerre RSI.
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// John Ehlers' Laguerre RSI — a four-stage Laguerre polynomial filter wrapped
/// in an `RSI`-style up/down accumulator. The single tuning parameter `gamma`
/// in `[0, 1]` trades lag for smoothness: small `gamma` is fast and noisy,
/// large `gamma` is slow and smooth (Ehlers recommends `0.5`).
///
/// ```text
/// alpha = 1 − gamma
/// L0_t = alpha · price_t + gamma · L0_{t-1}
/// L1_t = −gamma · L0_t + L0_{t-1} + gamma · L1_{t-1}
/// L2_t = −gamma · L1_t + L1_{t-1} + gamma · L2_{t-1}
/// L3_t = −gamma · L2_t + L2_{t-1} + gamma · L3_{t-1}
///
/// cu, cd = 0
/// for each pair (L0, L1), (L1, L2), (L2, L3):
/// if upper ≥ lower: cu += upper − lower
/// else : cd += lower − upper
///
/// LRSI = 100 · cu / (cu + cd)
/// ```
///
/// The output is bounded in `[0, 100]`. State is seeded by setting all four
/// `L_i` to the first input, so the first emission lands on input #1.
///
/// Reference: John F. Ehlers, *Time Warp — Without Space Travel*, 2002.
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, LaguerreRsi};
///
/// let mut lrsi = LaguerreRsi::new(0.5).unwrap();
/// let mut last = None;
/// for i in 0..40 {
/// last = lrsi.update(100.0 + f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct LaguerreRsi {
gamma: f64,
alpha: f64,
l0: f64,
l1: f64,
l2: f64,
l3: f64,
seeded: bool,
current: Option<f64>,
}
impl LaguerreRsi {
/// # Errors
/// Returns [`Error::InvalidPeriod`] if `gamma` is non-finite or outside `[0, 1]`.
pub fn new(gamma: f64) -> Result<Self> {
if !gamma.is_finite() || !(0.0..=1.0).contains(&gamma) {
return Err(Error::InvalidPeriod {
message: "LaguerreRSI gamma must be a finite value in [0, 1]",
});
}
Ok(Self {
gamma,
alpha: 1.0 - gamma,
l0: 0.0,
l1: 0.0,
l2: 0.0,
l3: 0.0,
seeded: false,
current: None,
})
}
/// Ehlers' recommended `gamma = 0.5`.
pub fn classic() -> Self {
Self::new(0.5).expect("classic LaguerreRSI gamma is valid")
}
/// Configured `gamma`.
pub const fn gamma(&self) -> f64 {
self.gamma
}
}
impl Indicator for LaguerreRsi {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.current;
}
if !self.seeded {
// Seed all four polynomial stages with the first input so a
// constant series produces zero up/down accumulators (which we
// map to 50.0 below — the canonical neutral mid-band reading).
self.l0 = input;
self.l1 = input;
self.l2 = input;
self.l3 = input;
self.seeded = true;
self.current = Some(50.0);
return self.current;
}
let (l0_prev, l1_prev, l2_prev) = (self.l0, self.l1, self.l2);
let l0_new = self.alpha * input + self.gamma * l0_prev;
let l1_new = -self.gamma * l0_new + l0_prev + self.gamma * self.l1;
let l2_new = -self.gamma * l1_new + l1_prev + self.gamma * self.l2;
let l3_new = -self.gamma * l2_new + l2_prev + self.gamma * self.l3;
self.l0 = l0_new;
self.l1 = l1_new;
self.l2 = l2_new;
self.l3 = l3_new;
let mut cu = 0.0;
let mut cd = 0.0;
let pairs = [(l0_new, l1_new), (l1_new, l2_new), (l2_new, l3_new)];
for (upper, lower) in pairs {
if upper >= lower {
cu += upper - lower;
} else {
cd += lower - upper;
}
}
let total = cu + cd;
let value = if total > 0.0 {
// Floating-point rounding can push `cu / total` a hair above 1.0;
// clamp to the algebraic bound to keep the output strictly inside
// [0, 100].
(100.0 * cu / total).clamp(0.0, 100.0)
} else {
// No up- or down-displacements between stages: stay at the
// neutral mid-band rather than report 0 / 0.
50.0
};
self.current = Some(value);
Some(value)
}
fn reset(&mut self) {
self.l0 = 0.0;
self.l1 = 0.0;
self.l2 = 0.0;
self.l3 = 0.0;
self.seeded = false;
self.current = None;
}
fn warmup_period(&self) -> usize {
1
}
fn is_ready(&self) -> bool {
self.current.is_some()
}
fn name(&self) -> &'static str {
"LaguerreRSI"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn rejects_invalid_gamma() {
assert!(matches!(
LaguerreRsi::new(-0.1),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
LaguerreRsi::new(1.1),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
LaguerreRsi::new(f64::NAN),
Err(Error::InvalidPeriod { .. })
));
}
#[test]
fn accessors_and_metadata() {
let lrsi = LaguerreRsi::new(0.5).unwrap();
assert_eq!(lrsi.gamma(), 0.5);
assert_eq!(lrsi.warmup_period(), 1);
assert_eq!(lrsi.name(), "LaguerreRSI");
}
#[test]
fn classic_factory() {
assert_eq!(LaguerreRsi::classic().gamma(), 0.5);
}
#[test]
fn constant_series_stays_at_mid_band() {
// All four L_i seed to the constant; on subsequent flat inputs they
// stay equal, so cu = cd = 0 and LRSI reports the neutral 50.
let mut lrsi = LaguerreRsi::classic();
let out = lrsi.batch(&[42.0_f64; 60]);
for v in out.iter().flatten() {
assert_relative_eq!(*v, 50.0, epsilon = 1e-12);
}
}
#[test]
fn output_is_bounded() {
let mut lrsi = LaguerreRsi::classic();
let prices: Vec<f64> = (0..200)
.map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 25.0)
.collect();
for v in lrsi.batch(&prices).iter().flatten() {
assert!(*v >= 0.0 && *v <= 100.0, "out of range: {v}");
}
}
#[test]
fn pure_uptrend_saturates_high() {
let mut lrsi = LaguerreRsi::classic();
for i in 0..200 {
lrsi.update(100.0 + f64::from(i));
}
let v = lrsi.current.unwrap();
assert!(v > 80.0, "uptrend should drive LRSI well above 50: {v}");
}
#[test]
fn pure_downtrend_saturates_low() {
let mut lrsi = LaguerreRsi::classic();
for i in 0..200 {
lrsi.update(300.0 - f64::from(i));
}
let v = lrsi.current.unwrap();
assert!(v < 20.0, "downtrend should drive LRSI well below 50: {v}");
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=120)
.map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 5.0)
.collect();
let mut a = LaguerreRsi::classic();
let mut b = LaguerreRsi::classic();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut lrsi = LaguerreRsi::classic();
lrsi.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
assert!(lrsi.is_ready());
lrsi.reset();
assert!(!lrsi.is_ready());
assert!(!lrsi.seeded);
}
#[test]
fn ignores_non_finite_input() {
let mut lrsi = LaguerreRsi::classic();
let before = lrsi.update(10.0).unwrap();
assert_eq!(lrsi.update(f64::NAN), Some(before));
assert_eq!(lrsi.update(f64::INFINITY), Some(before));
}
#[test]
fn gamma_zero_passes_through_l0() {
// gamma = 0 -> alpha = 1, so L0 mirrors the input exactly each step.
// The polynomial chain then lags by one stage; the up/down accumulator
// still produces a bounded reading and the first non-seed step shifts
// off 50 as soon as input changes.
let mut lrsi = LaguerreRsi::new(0.0).unwrap();
assert_eq!(lrsi.update(10.0), Some(50.0));
let v = lrsi.update(11.0).unwrap();
assert!((0.0..=100.0).contains(&v));
}
}