kestrel-chartkit 0.11.3

High-performance Rust technical analysis library for indicator math, market regime classification, composite scoring, and SVG visualization.
Documentation
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
use std::collections::VecDeque;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// How an [`Ema`] produces its first value.
///
/// The recurrence `alpha * src + (1 - alpha) * prev` with `alpha = 2/(len+1)` is the same in both
/// modes; only the value it starts from differs, and with it how long the series carries the
/// influence of that start. At `len == 1` (`alpha == 1`) both modes produce the same values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum EmaInit {
    /// Seeds with the input value itself and emits from the first sample on. The default, and the
    /// historical behaviour of this type.
    #[default]
    FirstSample,
    /// Seeds with the SMA of the first `len` samples and emits from the `len`-th sample on.
    /// Earlier samples produce no value — a partially accumulated average is not an EMA.
    Sma,
}

/// Exponential moving average over a scalar stream.
///
/// `EMA_t = alpha * src_t + (1 - alpha) * EMA_{t-1}` with `alpha = 2/(len + 1)`; the first value
/// comes from [`EmaInit`]. Returns `None` while the seed is not ready, which in the default
/// [`EmaInit::FirstSample`] mode never happens: there the very first sample is already the seed.
///
/// [`Ema::reset`] clears the state and any partially accumulated seed, so the next series starts
/// deterministically.
#[derive(Debug, Clone, Copy, Default)]
pub struct Ema {
    len: usize,
    init: EmaInit,
    state: Option<f64>,
    seed_sum: f64,
    seed_count: usize,
}

impl Ema {
    pub fn new(len: usize) -> Self {
        Self {
            len,
            init: EmaInit::FirstSample,
            state: None,
            seed_sum: 0.0,
            seed_count: 0,
        }
    }

    /// Selects the initialisation; see [`EmaInit`].
    ///
    /// Additive to [`Ema::new`], which keeps the first-sample seed. Nested users of this type
    /// (MACD, TEMA, ...) are deliberately not switched over by this: a seed change inside a chain
    /// is a separate contract question per indicator.
    pub fn with_init(mut self, init: EmaInit) -> Self {
        self.init = init;
        self
    }

    pub fn init(&self) -> EmaInit {
        self.init
    }

    pub fn update(&mut self, src: f64) -> Option<f64> {
        let alpha = 2.0 / (self.len as f64 + 1.0);
        if let Some(prev) = self.state {
            let next = alpha * src + (1.0 - alpha) * prev;
            self.state = Some(next);
            return Some(next);
        }

        let seed = match self.init {
            EmaInit::FirstSample => src,
            EmaInit::Sma => {
                self.seed_sum += src;
                self.seed_count += 1;
                if self.seed_count < self.len {
                    return None;
                }
                self.seed_sum / self.len as f64
            }
        };
        self.state = Some(seed);
        Some(seed)
    }

    /// Bars needed before [`Ema::update`] first returns `Some`.
    pub fn warmup_period(&self) -> usize {
        match self.init {
            EmaInit::FirstSample => 0,
            EmaInit::Sma => self.len,
        }
    }

    pub fn reset(&mut self) {
        self.state = None;
        self.seed_sum = 0.0;
        self.seed_count = 0;
    }
}

/// Weighted moving average for scalar streams: weight `len` on the most recent sample
#[derive(Debug, Clone)]
pub struct Wma {
    len: usize,
    window: VecDeque<f64>,
}

impl Wma {
    pub fn new(len: usize) -> Self {
        Self {
            len: len.max(1),
            window: VecDeque::with_capacity(len),
        }
    }

    pub fn update(&mut self, src: f64) -> Option<f64> {
        self.window.push_back(src);
        if self.window.len() > self.len {
            self.window.pop_front();
        }
        if self.window.len() < self.len {
            return None;
        }

        let denom = (self.len * (self.len + 1)) as f64 / 2.0;
        let mut sum = 0.0;
        for (i, &val) in self.window.iter().enumerate() {
            sum += val * (i + 1) as f64;
        }
        Some(sum / denom)
    }

    pub fn reset(&mut self) {
        self.window.clear();
    }
}

/// Wilder smoothing (`alpha = 1/len`): seeds with the SMA of the first `len` samples
#[derive(Debug, Clone)]
pub struct Rma {
    len: usize,
    seed: VecDeque<f64>,
    state: Option<f64>,
}

impl Rma {
    pub fn new(len: usize) -> Self {
        Self {
            len,
            seed: VecDeque::with_capacity(len),
            state: None,
        }
    }

    pub fn update(&mut self, src: f64) -> Option<f64> {
        if let Some(prev) = self.state {
            let alpha = 1.0 / self.len as f64;
            let next = alpha * src + (1.0 - alpha) * prev;
            self.state = Some(next);
            return Some(next);
        }
        self.seed.push_back(src);
        if self.seed.len() < self.len {
            return None;
        }
        let sma = self.seed.iter().sum::<f64>() / self.len as f64;
        self.state = Some(sma);
        Some(sma)
    }

    pub fn reset(&mut self) {
        self.seed.clear();
        self.state = None;
    }
}

/// Plain windowed average
#[derive(Debug, Clone)]
pub struct Sma {
    len: usize,
    window: VecDeque<f64>,
    sum: f64,
}

impl Sma {
    pub fn new(len: usize) -> Self {
        Self {
            len,
            window: VecDeque::with_capacity(len),
            sum: 0.0,
        }
    }

    pub fn update(&mut self, src: f64) -> Option<f64> {
        self.window.push_back(src);
        self.sum += src;
        if self.window.len() > self.len {
            self.sum -= self.window.pop_front().unwrap();
        }
        if self.window.len() < self.len {
            return None;
        }
        Some(self.sum / self.len as f64)
    }

    pub fn reset(&mut self) {
        self.window.clear();
        self.sum = 0.0;
    }
}

/// Rolling window for finding highest and lowest values
#[derive(Debug, Clone)]
pub struct ExtremeWindow {
    len: usize,
    window: VecDeque<f64>,
}

impl ExtremeWindow {
    pub fn new(len: usize) -> Self {
        Self {
            len,
            window: VecDeque::with_capacity(len),
        }
    }

    pub fn push(&mut self, value: f64) -> Option<(f64, f64)> {
        if self.window.len() == self.len {
            self.window.pop_front();
        }
        self.window.push_back(value);
        if self.window.len() < self.len {
            return None;
        }
        let lowest = self.window.iter().cloned().fold(f64::INFINITY, f64::min);
        let highest = self
            .window
            .iter()
            .cloned()
            .fold(f64::NEG_INFINITY, f64::max);
        Some((lowest, highest))
    }

    pub fn reset(&mut self) {
        self.window.clear();
    }
}

pub fn crossed_over(prev_a: f64, prev_b: f64, a: f64, b: f64) -> bool {
    prev_a <= prev_b && a > b
}

pub fn crossed_under(prev_a: f64, prev_b: f64, a: f64, b: f64) -> bool {
    prev_a >= prev_b && a < b
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum SmootherKind {
    #[default]
    Ema,
    Sma,
    Rma,
    Alma,
    Jma,
    SuperSmoother,
    Kama,
}

impl SmootherKind {
    /// Builds a boxed [`Smoother`] of this kind with `len` bars of lookback/decay, using common
    /// defaults for `Alma` (`offset = 0.85`, `sigma = 6.0`), `Jma` (`phase = 0.0`,
    /// `power = 2.0`) and `Kama` (Kaufman's own `fast_period = 2`, `slow_period = 30`). Use the
    /// concrete constructors directly to override those.
    pub fn build(self, len: usize) -> Box<dyn Smoother> {
        match self {
            SmootherKind::Ema => Box::new(Ema::new(len)),
            SmootherKind::Sma => Box::new(Sma::new(len)),
            SmootherKind::Rma => Box::new(Rma::new(len)),
            SmootherKind::Alma => Box::new(Alma::new(len, 0.85, 6.0)),
            SmootherKind::Jma => Box::new(Jma::new(len, 0.0, 2.0)),
            SmootherKind::SuperSmoother => Box::new(SuperSmoother::new(len)),
            SmootherKind::Kama => Box::new(Kama::with_defaults(len)),
        }
    }
}

/// Common contract for streaming smoothers, letting them be chained ([`SmootherChain`]) or
/// selected dynamically ([`SmootherKind::build`]) regardless of concrete type.
pub trait Smoother: Send + Sync {
    /// Feeds one value. Returns `None` while still inside this smoother's own warmup.
    fn update(&mut self, src: f64) -> Option<f64>;
    fn reset(&mut self);
    /// Bars needed before this smoother first returns `Some`. `0` for smoothers that emit from
    /// the first sample (`Ema`, `Jma`).
    fn warmup_period(&self) -> usize {
        0
    }
}

impl Smoother for Ema {
    fn update(&mut self, src: f64) -> Option<f64> {
        Ema::update(self, src)
    }
    fn reset(&mut self) {
        Ema::reset(self)
    }
    fn warmup_period(&self) -> usize {
        Ema::warmup_period(self)
    }
}

impl Smoother for Sma {
    fn update(&mut self, src: f64) -> Option<f64> {
        Sma::update(self, src)
    }
    fn reset(&mut self) {
        Sma::reset(self)
    }
    fn warmup_period(&self) -> usize {
        self.len
    }
}

impl Smoother for Rma {
    fn update(&mut self, src: f64) -> Option<f64> {
        Rma::update(self, src)
    }
    fn reset(&mut self) {
        Rma::reset(self)
    }
    fn warmup_period(&self) -> usize {
        self.len
    }
}

impl Smoother for Wma {
    fn update(&mut self, src: f64) -> Option<f64> {
        Wma::update(self, src)
    }
    fn reset(&mut self) {
        Wma::reset(self)
    }
    fn warmup_period(&self) -> usize {
        self.len
    }
}

impl Smoother for Alma {
    fn update(&mut self, src: f64) -> Option<f64> {
        Alma::update(self, src)
    }
    fn reset(&mut self) {
        Alma::reset(self)
    }
    fn warmup_period(&self) -> usize {
        self.len
    }
}

impl Smoother for Jma {
    fn update(&mut self, src: f64) -> Option<f64> {
        Some(Jma::update(self, src))
    }
    fn reset(&mut self) {
        Jma::reset(self)
    }
}

impl Smoother for SuperSmoother {
    fn update(&mut self, src: f64) -> Option<f64> {
        Some(SuperSmoother::update(self, src))
    }
    fn reset(&mut self) {
        SuperSmoother::reset(self)
    }
}

impl Smoother for Kama {
    fn update(&mut self, src: f64) -> Option<f64> {
        Kama::update(self, src)
    }
    fn reset(&mut self) {
        Kama::reset(self)
    }
    fn warmup_period(&self) -> usize {
        self.period + 1
    }
}

/// A typed, ordered pipeline of [`Smoother`] stages: each stage's output feeds the next stage's
/// input. Its own warmup/reset contract composes cleanly from its stages':
/// [`SmootherChain::warmup_period`] is the sum of every stage's warmup (a downstream stage cannot
/// start accumulating until its upstream first emits), and [`SmootherChain::reset`] resets every
/// stage. Works with any mix of existing `Smoother` impls, and with future ones without changes
/// here — implement [`Smoother`] and it is chainable.
pub struct SmootherChain {
    stages: Vec<Box<dyn Smoother>>,
}

impl SmootherChain {
    pub fn new(stages: Vec<Box<dyn Smoother>>) -> Self {
        Self { stages }
    }

    pub fn warmup_period(&self) -> usize {
        self.stages.iter().map(|s| s.warmup_period()).sum()
    }

    pub fn reset(&mut self) {
        for stage in &mut self.stages {
            stage.reset();
        }
    }

    /// Feeds `src` through every stage in order. Returns `None` if any stage is still inside its
    /// own warmup this bar.
    pub fn update(&mut self, src: f64) -> Option<f64> {
        let mut value = src;
        for stage in &mut self.stages {
            value = stage.update(value)?;
        }
        Some(value)
    }
}

/// A [`SmootherChain`] is itself a [`Smoother`], so chains compose (a chain can be one stage of
/// another chain) and can be used anywhere a single smoother is expected, e.g. as one leg of
/// [`super::trend_relationship::AdaptiveTrendRelationship`].
impl Smoother for SmootherChain {
    fn update(&mut self, src: f64) -> Option<f64> {
        SmootherChain::update(self, src)
    }
    fn reset(&mut self) {
        SmootherChain::reset(self)
    }
    fn warmup_period(&self) -> usize {
        SmootherChain::warmup_period(self)
    }
}

/// Arnaud Legoux Moving Average (ALMA)
#[derive(Debug, Clone)]
pub struct Alma {
    len: usize,
    offset: f64,
    sigma: f64,
    window: VecDeque<f64>,
    weights: Vec<f64>,
    sum_weights: f64,
}

impl Alma {
    pub fn new(len: usize, offset: f64, sigma: f64) -> Self {
        let len = len.max(1);
        let m = offset * (len - 1) as f64;
        let s = (len as f64 / sigma).max(1e-6);

        let mut weights = Vec::with_capacity(len);
        let mut sum_weights = 0.0;
        for i in 0..len {
            let w = (-(i as f64 - m).powi(2) / (2.0 * s * s)).exp();
            weights.push(w);
            sum_weights += w;
        }

        Self {
            len,
            offset,
            sigma,
            window: VecDeque::with_capacity(len),
            weights,
            sum_weights,
        }
    }

    pub fn offset(&self) -> f64 {
        self.offset
    }

    pub fn sigma(&self) -> f64 {
        self.sigma
    }

    pub fn update(&mut self, src: f64) -> Option<f64> {
        self.window.push_back(src);
        if self.window.len() > self.len {
            self.window.pop_front();
        }
        if self.window.len() < self.len {
            return None;
        }

        let mut weighted_sum = 0.0;
        for (i, &val) in self.window.iter().enumerate() {
            weighted_sum += val * self.weights[i];
        }
        Some(weighted_sum / self.sum_weights)
    }

    pub fn reset(&mut self) {
        self.window.clear();
    }
}

/// Open Jurik-style moving-average approximation.
#[derive(Debug, Clone)]
pub struct Jma {
    len: usize,
    phase: f64,
    power: f64,
    e0: f64,
    e1: f64,
    e2: f64,
    jma: f64,
    initialized: bool,
}

impl Jma {
    pub fn new(len: usize, phase: f64, power: f64) -> Self {
        Self {
            len: len.max(1),
            phase: phase.clamp(-100.0, 100.0),
            power: power.max(1.0),
            e0: 0.0,
            e1: 0.0,
            e2: 0.0,
            jma: 0.0,
            initialized: false,
        }
    }

    pub fn phase(&self) -> f64 {
        self.phase
    }

    pub fn update(&mut self, src: f64) -> f64 {
        if !self.initialized {
            self.e0 = src;
            self.e1 = 0.0;
            self.e2 = 0.0;
            self.jma = src;
            self.initialized = true;
            return src;
        }

        let phase_ratio = self.phase / 100.0 + 1.5;
        let length_term = 0.45 * (self.len.saturating_sub(1)) as f64;
        let beta = length_term / (length_term + 2.0);
        let alpha = beta.powf(self.power);
        self.e0 = (1.0 - alpha) * src + alpha * self.e0;
        self.e1 = (src - self.e0) * (1.0 - beta) + beta * self.e1;
        self.e2 = (self.e0 + phase_ratio * self.e1 - self.jma) * (1.0 - alpha).powi(2)
            + alpha.powi(2) * self.e2;
        self.jma += self.e2;
        self.jma
    }

    pub fn reset(&mut self) {
        self.e0 = 0.0;
        self.e1 = 0.0;
        self.e2 = 0.0;
        self.jma = 0.0;
        self.initialized = false;
    }
}

/// Ehlers' SuperSmoother, a 2-pole Butterworth low-pass filter:
/// `a1 = exp(-1.414 · π / len)`, `c2 = 2 · a1 · cos(1.414 · π / len)`, `c3 = -a1²`,
/// `c1 = 1 - c2 - c3`, and `ss_t = c1 · (src_t + src_(t-1)) / 2 + c2 · ss_(t-1) + c3 · ss_(t-2)`.
/// Valid from the first sample: the missing `src[1]`/`ss[1]`/`ss[2]` terms on the first bars
/// default to `0`, producing a short transient rather than a `None` warmup.
#[derive(Debug, Clone)]
pub struct SuperSmoother {
    c1: f64,
    c2: f64,
    c3: f64,
    prev_src: f64,
    prev1: f64,
    prev2: f64,
}

impl SuperSmoother {
    pub fn new(len: usize) -> Self {
        let len = len.max(1) as f64;
        let a1 = (-1.414 * std::f64::consts::PI / len).exp();
        let b1 = 2.0 * a1 * (1.414 * std::f64::consts::PI / len).cos();
        let c2 = b1;
        let c3 = -(a1 * a1);
        let c1 = 1.0 - c2 - c3;
        Self {
            c1,
            c2,
            c3,
            prev_src: 0.0,
            prev1: 0.0,
            prev2: 0.0,
        }
    }

    pub fn update(&mut self, src: f64) -> f64 {
        let ss =
            self.c1 * (src + self.prev_src) / 2.0 + self.c2 * self.prev1 + self.c3 * self.prev2;
        self.prev2 = self.prev1;
        self.prev1 = ss;
        self.prev_src = src;
        ss
    }

    pub fn reset(&mut self) {
        self.prev_src = 0.0;
        self.prev1 = 0.0;
        self.prev2 = 0.0;
    }
}

/// Kaufman's Adaptive Moving Average as a scalar-stream [`Smoother`] stage — same
/// efficiency-ratio-derived adaptive-alpha formula as
/// [`KamaEngine`](super::moving_averages::KamaEngine), decoupled from [`crate::model::Bar`] so it
/// can be one stage of a [`Smoother`]/[`SmootherChain`] pipeline instead of only a stand-alone bar
/// indicator. It reuses `KamaEngine`'s math with configurable `fast_period`/`slow_period` rather
/// than adding a second variant with fixed 2/30 periods.
#[derive(Debug, Clone)]
pub struct Kama {
    period: usize,
    fast_period: usize,
    slow_period: usize,
    window: VecDeque<f64>,
    state: Option<f64>,
}

impl Kama {
    pub fn new(period: usize, fast_period: usize, slow_period: usize) -> Self {
        let period = period.max(1);
        Self {
            period,
            fast_period,
            slow_period,
            window: VecDeque::with_capacity(period + 1),
            state: None,
        }
    }

    /// Kaufman's own defaults (`fast_period = 2`, `slow_period = 30`), matching
    /// [`KamaEngine`](super::moving_averages::KamaEngine)'s catalog defaults.
    pub fn with_defaults(period: usize) -> Self {
        Self::new(period, 2, 30)
    }

    pub fn update(&mut self, src: f64) -> Option<f64> {
        self.window.push_back(src);
        if self.window.len() > self.period + 1 {
            self.window.pop_front();
        }
        if self.window.len() < self.period + 1 {
            return None;
        }

        let change = (self.window.back().unwrap() - self.window.front().unwrap()).abs();
        let mut volatility = 0.0f64;
        for pair in self.window.iter().collect::<Vec<_>>().windows(2) {
            volatility += (*pair[1] - *pair[0]).abs();
        }
        let er = if volatility > 0.0 {
            change / volatility
        } else {
            0.0
        };

        let fast_sc = 2.0 / (self.fast_period as f64 + 1.0);
        let slow_sc = 2.0 / (self.slow_period as f64 + 1.0);
        let sc = (er * (fast_sc - slow_sc) + slow_sc).powi(2);

        let next = match self.state {
            Some(prev) => prev + sc * (src - prev),
            None => src,
        };
        self.state = Some(next);
        Some(next)
    }

    pub fn reset(&mut self) {
        self.window.clear();
        self.state = None;
    }
}

#[cfg(test)]
mod jma_tests {
    use super::Jma;

    #[test]
    fn phase_changes_the_open_jurik_approximation() {
        let mut leading = Jma::new(7, 100.0, 2.0);
        let mut lagging = Jma::new(7, -100.0, 2.0);
        let input = [10.0, 11.0, 13.0, 12.0, 15.0];
        let leading_value = input.into_iter().map(|v| leading.update(v)).last().unwrap();
        let lagging_value = input.into_iter().map(|v| lagging.update(v)).last().unwrap();
        assert!(leading_value > lagging_value);
    }

    #[test]
    fn matches_reference_formula_fixture() {
        let mut jma = Jma::new(3, 0.0, 2.0);
        let actual: Vec<_> = [1.0, 2.0, 3.0, 4.0]
            .into_iter()
            .map(|value| jma.update(value))
            .collect();
        let expected = [
            1.0,
            1.819_360_773_771_215_6,
            2.819_354_006_908_239,
            3.831_322_396_018_062,
        ];
        for (actual, expected) in actual.iter().zip(expected) {
            assert!((actual - expected).abs() < 1e-12, "{actual} != {expected}");
        }
    }
}

#[cfg(test)]
mod supersmoother_tests {
    use super::SuperSmoother;

    /// Reference values independently derived (Python, from the documented Ehlers 2-pole
    /// Butterworth formula transcribed in `SuperSmoother::new`/`update`'s doc comments — not by
    /// running this Rust code):
    /// ```python
    /// import math
    /// def super_smoother(prices, length):
    ///     a1 = math.exp(-1.414 * math.pi / length)
    ///     b1 = 2 * a1 * math.cos(1.414 * math.pi / length)
    ///     c2, c3 = b1, -(a1 * a1)
    ///     c1 = 1 - c2 - c3
    ///     prev_src = prev1 = prev2 = 0.0
    ///     out = []
    ///     for src in prices:
    ///         ss = c1 * (src + prev_src) / 2.0 + c2 * prev1 + c3 * prev2
    ///         prev2, prev1, prev_src = prev1, ss, src
    ///         out.append(ss)
    ///     return out
    /// ```
    #[test]
    fn matches_independently_derived_reference_formula_fixture() {
        let mut ss = SuperSmoother::new(3);
        let actual: Vec<_> = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
            .into_iter()
            .map(|value| ss.update(value))
            .collect();
        let expected = [
            0.505_413_249_748_865_4,
            1.536_919_267_057_587,
            2.563_799_552_420_708,
            3.563_269_185_823_832_3,
            4.561_856_630_604_048,
            5.561_826_276_936_932,
        ];
        for (actual, expected) in actual.iter().zip(expected) {
            assert!((actual - expected).abs() < 1e-12, "{actual} != {expected}");
        }
    }

    #[test]
    fn reset_clears_transient_state() {
        let mut ss = SuperSmoother::new(5);
        ss.update(100.0);
        ss.update(110.0);
        ss.reset();
        let mut fresh = SuperSmoother::new(5);
        assert_eq!(ss.update(50.0), fresh.update(50.0));
    }
}

#[cfg(test)]
mod kama_smoother_tests {
    use super::Kama;

    /// `Kama` reuses `KamaEngine`'s already golden-validated formula (see
    /// `tests/golden_reference_moving_averages.rs`, `kama5_last =
    /// 14.554043488814198` for `KAMA(period=5, fast_period=2, slow_period=30)` over the shared
    /// `CLOSES` series `[10, 11, 12, 11, 13, 14, 13, 15, 16, 15]`) — this is not a new formula
    /// derivation, just a check that the `Bar`-decoupled scalar-stream version computes the exact
    /// same sequence as the already-confirmed `Indicator` version, referencing that existing
    /// golden fixture rather than re-deriving it (no circularity: the fixture value predates and
    /// is independent of this struct).
    #[test]
    fn matches_already_confirmed_kama_engine_golden_value() {
        const CLOSES: [f64; 10] = [10.0, 11.0, 12.0, 11.0, 13.0, 14.0, 13.0, 15.0, 16.0, 15.0];
        let mut kama = Kama::new(5, 2, 30);
        let mut last = None;
        for &c in &CLOSES {
            if let Some(value) = kama.update(c) {
                last = Some(value);
            }
        }
        let last = last.expect("kama produced no output");
        assert!(
            (last - 14.554_043_488_814_198).abs() < 1e-9,
            "{last} != 14.554043488814198"
        );
    }

    #[test]
    fn warmup_returns_none_until_period_plus_one_samples() {
        let mut kama = Kama::new(3, 2, 30);
        assert_eq!(kama.update(1.0), None);
        assert_eq!(kama.update(2.0), None);
        assert_eq!(kama.update(3.0), None);
        assert!(kama.update(4.0).is_some());
    }
}

#[cfg(test)]
mod chain_tests {
    use super::*;

    #[test]
    fn test_chain_warmup_is_sum_of_stage_warmups() {
        let chain =
            SmootherChain::new(vec![SmootherKind::Sma.build(3), SmootherKind::Rma.build(4)]);
        assert_eq!(chain.warmup_period(), 3 + 4);
    }

    #[test]
    fn test_chain_none_until_every_stage_warm() {
        let mut chain =
            SmootherChain::new(vec![SmootherKind::Sma.build(2), SmootherKind::Sma.build(2)]);
        assert_eq!(chain.update(1.0), None); // stage 1 still cold
        assert_eq!(chain.update(2.0), None); // stage 1 warm (sma=1.5), stage 2 gets its 1st input
                                             // stage 1 sma(2,3)=2.5; stage 2 now has both its inputs (1.5, 2.5) -> warm.
        let value = chain.update(3.0).unwrap();
        assert!((value - 2.0).abs() < 1e-9);
        let value = chain.update(4.0).unwrap();
        assert!((value - 3.0).abs() < 1e-9);
    }

    #[test]
    fn test_chain_reset_clears_every_stage() {
        let mut chain = SmootherChain::new(vec![SmootherKind::Sma.build(2)]);
        chain.update(1.0);
        assert!(chain.update(2.0).is_some());
        chain.reset();
        assert_eq!(chain.update(5.0), None, "reset stage must re-enter warmup");
    }

    #[test]
    fn test_smoother_kind_build_matches_direct_construction() {
        let mut via_kind = SmootherKind::Ema.build(5);
        let mut direct = Ema::new(5);
        for v in [10.0, 11.0, 12.0, 9.0] {
            assert_eq!(via_kind.update(v), Ema::update(&mut direct, v));
        }
    }
}