Skip to main content

ferrochart_indicators/
calc.rs

1//! The 30 indicator calculations of `docs/book/src/indicators.md`, on top of the kernels
2//! in [`crate::kernel`].
3//!
4//! A [`Calc`] sees valid bars only (gap bars are skipped by the caller,
5//! `docs/book/src/indicators.md`) and follows the kernels' contract: `peek` computes
6//! the outputs of a tentative newest bar without changing the state, `push`
7//! commits a bar. Display shifts (Ichimoku) are `OutputSpec::shift`, applied
8//! by the chart when drawing.
9//!
10//! Small-state calculations (SAR, `SuperTrend`, OBV, VWAP) implement `peek` as
11//! "copy the state, step the copy"; window calculations peek their kernels.
12
13use crate::kernel::{Ring, RollingExtreme, RollingSum, Sma, Smooth, WilderSum, Wma};
14
15/// One valid bar.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub(crate) struct Bar {
18    pub time: i64,
19    pub open: f64,
20    pub high: f64,
21    pub low: f64,
22    pub close: f64,
23    /// NaN when the series has no volume.
24    pub volume: f64,
25}
26
27/// Price an indicator reads (`docs/book/src/indicators.md`).
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub enum Source {
30    /// Close (default).
31    #[default]
32    Close,
33    /// Open.
34    Open,
35    /// High.
36    High,
37    /// Low.
38    Low,
39    /// `(H + L) / 2`.
40    Hl2,
41    /// `(H + L + C) / 3`.
42    Hlc3,
43    /// `(O + H + L + C) / 4`.
44    Ohlc4,
45}
46
47impl Source {
48    pub(crate) fn of(self, b: &Bar) -> f64 {
49        match self {
50            Self::Close => b.close,
51            Self::Open => b.open,
52            Self::High => b.high,
53            Self::Low => b.low,
54            Self::Hl2 => f64::midpoint(b.high, b.low),
55            Self::Hlc3 => hlc3(b),
56            Self::Ohlc4 => (b.open + b.high + b.low + b.close) / 4.0,
57        }
58    }
59}
60
61fn hlc3(b: &Bar) -> f64 {
62    (b.high + b.low + b.close) / 3.0
63}
64
65/// `a / b`, or `if_zero` when `b == 0`.
66fn div(a: f64, b: f64, if_zero: f64) -> f64 {
67    if b == 0.0 { if_zero } else { a / b }
68}
69
70/// True range against the previous close; NaN on the first bar.
71fn true_range(b: &Bar, prev_close: Option<f64>) -> f64 {
72    prev_close.map_or(f64::NAN, |pc| {
73        (b.high - b.low)
74            .max((b.high - pc).abs())
75            .max((b.low - pc).abs())
76    })
77}
78
79/// An incremental calculation over valid bars.
80pub(crate) trait Calc: Send {
81    /// Number of outputs.
82    fn outputs(&self) -> usize;
83    /// Outputs for `b` as the newest bar, without committing it.
84    fn peek(&self, b: &Bar, out: &mut [f64]);
85    /// Commits `b`.
86    fn push(&mut self, b: &Bar);
87}
88
89// ---- 1. moving averages ------------------------------------------------------
90
91pub(crate) struct SmaCalc {
92    src: Source,
93    k: Sma,
94}
95
96impl SmaCalc {
97    pub(crate) fn new(n: usize, src: Source) -> Self {
98        Self {
99            src,
100            k: Sma::new(n),
101        }
102    }
103}
104
105impl Calc for SmaCalc {
106    fn outputs(&self) -> usize {
107        1
108    }
109    fn peek(&self, b: &Bar, out: &mut [f64]) {
110        out[0] = self.k.peek(self.src.of(b));
111    }
112    fn push(&mut self, b: &Bar) {
113        self.k.push(self.src.of(b));
114    }
115}
116
117pub(crate) struct EmaCalc {
118    src: Source,
119    k: Smooth,
120}
121
122impl EmaCalc {
123    pub(crate) fn new(n: usize, src: Source) -> Self {
124        Self {
125            src,
126            k: Smooth::ema(n),
127        }
128    }
129}
130
131impl Calc for EmaCalc {
132    fn outputs(&self) -> usize {
133        1
134    }
135    fn peek(&self, b: &Bar, out: &mut [f64]) {
136        out[0] = self.k.peek(self.src.of(b));
137    }
138    fn push(&mut self, b: &Bar) {
139        self.k.push(self.src.of(b));
140    }
141}
142
143pub(crate) struct WmaCalc {
144    src: Source,
145    k: Wma,
146}
147
148impl WmaCalc {
149    pub(crate) fn new(n: usize, src: Source) -> Self {
150        Self {
151            src,
152            k: Wma::new(n),
153        }
154    }
155}
156
157impl Calc for WmaCalc {
158    fn outputs(&self) -> usize {
159        1
160    }
161    fn peek(&self, b: &Bar, out: &mut [f64]) {
162        out[0] = self.k.peek(self.src.of(b));
163    }
164    fn push(&mut self, b: &Bar) {
165        self.k.push(self.src.of(b));
166    }
167}
168
169pub(crate) struct HmaCalc {
170    src: Source,
171    half: Wma,
172    full: Wma,
173    hull: Wma,
174}
175
176impl HmaCalc {
177    pub(crate) fn new(n: usize, src: Source) -> Self {
178        let n = n.max(2);
179        Self {
180            src,
181            half: Wma::new(n / 2),
182            full: Wma::new(n),
183            hull: Wma::new(n.isqrt()),
184        }
185    }
186
187    fn raw(&self, p: f64) -> f64 {
188        2.0 * self.half.peek(p) - self.full.peek(p)
189    }
190}
191
192impl Calc for HmaCalc {
193    fn outputs(&self) -> usize {
194        1
195    }
196    fn peek(&self, b: &Bar, out: &mut [f64]) {
197        out[0] = self.hull.peek(self.raw(self.src.of(b)));
198    }
199    fn push(&mut self, b: &Bar) {
200        let p = self.src.of(b);
201        let raw = self.raw(p);
202        self.half.push(p);
203        self.full.push(p);
204        self.hull.push(raw);
205    }
206}
207
208pub(crate) struct VwmaCalc {
209    src: Source,
210    pv: RollingSum,
211    v: RollingSum,
212}
213
214impl VwmaCalc {
215    pub(crate) fn new(n: usize, src: Source) -> Self {
216        Self {
217            src,
218            pv: RollingSum::new(n),
219            v: RollingSum::new(n),
220        }
221    }
222}
223
224impl Calc for VwmaCalc {
225    fn outputs(&self) -> usize {
226        1
227    }
228    fn peek(&self, b: &Bar, out: &mut [f64]) {
229        let sv = self.v.peek(b.volume);
230        out[0] = div(self.pv.peek(self.src.of(b) * b.volume), sv, f64::NAN);
231    }
232    fn push(&mut self, b: &Bar) {
233        self.pv.push(self.src.of(b) * b.volume);
234        self.v.push(b.volume);
235    }
236}
237
238/// EMA, EMA of EMA, EMA of that (DEMA, TEMA, TRIX).
239#[derive(Clone, Copy)]
240struct EmaChain {
241    e: [Smooth; 3],
242}
243
244impl EmaChain {
245    fn new(n: usize) -> Self {
246        Self {
247            e: [Smooth::ema(n); 3],
248        }
249    }
250
251    fn peek(&self, p: f64) -> [f64; 3] {
252        let y1 = self.e[0].peek(p);
253        let y2 = self.e[1].peek(y1);
254        [y1, y2, self.e[2].peek(y2)]
255    }
256
257    fn push(&mut self, p: f64) {
258        let [y1, y2, _] = self.peek(p);
259        self.e[0].push(p);
260        self.e[1].push(y1);
261        self.e[2].push(y2);
262    }
263}
264
265pub(crate) struct DemaCalc {
266    src: Source,
267    k: EmaChain,
268}
269
270impl DemaCalc {
271    pub(crate) fn new(n: usize, src: Source) -> Self {
272        Self {
273            src,
274            k: EmaChain::new(n),
275        }
276    }
277}
278
279impl Calc for DemaCalc {
280    fn outputs(&self) -> usize {
281        1
282    }
283    fn peek(&self, b: &Bar, out: &mut [f64]) {
284        let [y1, y2, _] = self.k.peek(self.src.of(b));
285        out[0] = 2.0 * y1 - y2;
286    }
287    fn push(&mut self, b: &Bar) {
288        self.k.push(self.src.of(b));
289    }
290}
291
292pub(crate) struct TemaCalc {
293    src: Source,
294    k: EmaChain,
295}
296
297impl TemaCalc {
298    pub(crate) fn new(n: usize, src: Source) -> Self {
299        Self {
300            src,
301            k: EmaChain::new(n),
302        }
303    }
304}
305
306impl Calc for TemaCalc {
307    fn outputs(&self) -> usize {
308        1
309    }
310    fn peek(&self, b: &Bar, out: &mut [f64]) {
311        let [y1, y2, y3] = self.k.peek(self.src.of(b));
312        out[0] = 3.0 * y1 - 3.0 * y2 + y3;
313    }
314    fn push(&mut self, b: &Bar) {
315        self.k.push(self.src.of(b));
316    }
317}
318
319pub(crate) struct VolumeMaCalc(Sma);
320
321impl VolumeMaCalc {
322    pub(crate) fn new(n: usize) -> Self {
323        Self(Sma::new(n))
324    }
325}
326
327impl Calc for VolumeMaCalc {
328    fn outputs(&self) -> usize {
329        1
330    }
331    fn peek(&self, b: &Bar, out: &mut [f64]) {
332        out[0] = self.0.peek(b.volume);
333    }
334    fn push(&mut self, b: &Bar) {
335        self.0.push(b.volume);
336    }
337}
338
339// ---- 2. channels -------------------------------------------------------------
340
341/// Outputs: upper, mid, lower.
342pub(crate) struct BollCalc {
343    src: Source,
344    k: f64,
345    mid: Sma,
346}
347
348impl BollCalc {
349    pub(crate) fn new(n: usize, k: f64, src: Source) -> Self {
350        Self {
351            src,
352            k,
353            mid: Sma::new(n),
354        }
355    }
356}
357
358impl Calc for BollCalc {
359    fn outputs(&self) -> usize {
360        3
361    }
362    fn peek(&self, b: &Bar, out: &mut [f64]) {
363        let p = self.src.of(b);
364        let mid = self.mid.peek(p);
365        let w = self.mid.window();
366        let n = (w.cap() + 1) as f64;
367        // Directly over the window, oldest first (`docs/book/src/indicators.md`, BOLL).
368        let mut ss = 0.0;
369        for c in w.iter().chain(std::iter::once(p)) {
370            ss += (c - mid) * (c - mid);
371        }
372        let sd = (ss / n).sqrt();
373        out[0] = mid + self.k * sd;
374        out[1] = mid;
375        out[2] = mid - self.k * sd;
376    }
377    fn push(&mut self, b: &Bar) {
378        self.mid.push(self.src.of(b));
379    }
380}
381
382/// `RMA(TR, n)`.
383#[derive(Clone, Copy)]
384pub(crate) struct Atr {
385    prev_close: Option<f64>,
386    k: Smooth,
387}
388
389impl Atr {
390    pub(crate) fn new(n: usize) -> Self {
391        Self {
392            prev_close: None,
393            k: Smooth::rma(n),
394        }
395    }
396
397    pub(crate) fn peek(&self, b: &Bar) -> f64 {
398        self.k.peek(true_range(b, self.prev_close))
399    }
400
401    pub(crate) fn push(&mut self, b: &Bar) {
402        self.k.push(true_range(b, self.prev_close));
403        self.prev_close = Some(b.close);
404    }
405}
406
407pub(crate) struct AtrCalc(Atr);
408
409impl AtrCalc {
410    pub(crate) fn new(n: usize) -> Self {
411        Self(Atr::new(n))
412    }
413}
414
415impl Calc for AtrCalc {
416    fn outputs(&self) -> usize {
417        1
418    }
419    fn peek(&self, b: &Bar, out: &mut [f64]) {
420        out[0] = self.0.peek(b);
421    }
422    fn push(&mut self, b: &Bar) {
423        self.0.push(b);
424    }
425}
426
427/// Outputs: upper, mid, lower.
428pub(crate) struct KeltnerCalc {
429    m: f64,
430    mid: Smooth,
431    atr: Atr,
432}
433
434impl KeltnerCalc {
435    pub(crate) fn new(n: usize, m: f64, atr_n: usize) -> Self {
436        Self {
437            m,
438            mid: Smooth::ema(n),
439            atr: Atr::new(atr_n),
440        }
441    }
442}
443
444impl Calc for KeltnerCalc {
445    fn outputs(&self) -> usize {
446        3
447    }
448    fn peek(&self, b: &Bar, out: &mut [f64]) {
449        let mid = self.mid.peek(b.close);
450        let a = self.atr.peek(b);
451        out[0] = mid + self.m * a;
452        out[1] = mid;
453        out[2] = mid - self.m * a;
454    }
455    fn push(&mut self, b: &Bar) {
456        self.mid.push(b.close);
457        self.atr.push(b);
458    }
459}
460
461/// `(max(H, n) + min(L, n)) / 2` and its parts.
462struct MidRange {
463    hi: RollingExtreme,
464    lo: RollingExtreme,
465}
466
467impl MidRange {
468    fn new(n: usize) -> Self {
469        Self {
470            hi: RollingExtreme::max(n),
471            lo: RollingExtreme::min(n),
472        }
473    }
474
475    fn peek(&self, b: &Bar) -> (f64, f64) {
476        (self.hi.peek(b.high), self.lo.peek(b.low))
477    }
478
479    fn mid(&self, b: &Bar) -> f64 {
480        let (h, l) = self.peek(b);
481        f64::midpoint(h, l)
482    }
483
484    fn push(&mut self, b: &Bar) {
485        self.hi.push(b.high);
486        self.lo.push(b.low);
487    }
488}
489
490/// Outputs: upper, mid, lower.
491pub(crate) struct DonchianCalc(MidRange);
492
493impl DonchianCalc {
494    pub(crate) fn new(n: usize) -> Self {
495        Self(MidRange::new(n))
496    }
497}
498
499impl Calc for DonchianCalc {
500    fn outputs(&self) -> usize {
501        3
502    }
503    fn peek(&self, b: &Bar, out: &mut [f64]) {
504        let (up, lo) = self.0.peek(b);
505        out[0] = up;
506        out[1] = f64::midpoint(up, lo);
507        out[2] = lo;
508    }
509    fn push(&mut self, b: &Bar) {
510        self.0.push(b);
511    }
512}
513
514/// Outputs: tenkan, kijun, `span_a` (+shift), `span_b` (+shift), chikou (−shift).
515pub(crate) struct IchimokuCalc {
516    tenkan: MidRange,
517    kijun: MidRange,
518    senkou: MidRange,
519}
520
521impl IchimokuCalc {
522    /// The display shift is `OutputSpec::shift` (the chart's business).
523    pub(crate) fn new(tenkan: usize, kijun: usize, senkou: usize) -> Self {
524        Self {
525            tenkan: MidRange::new(tenkan),
526            kijun: MidRange::new(kijun),
527            senkou: MidRange::new(senkou),
528        }
529    }
530}
531
532impl Calc for IchimokuCalc {
533    fn outputs(&self) -> usize {
534        5
535    }
536    fn peek(&self, b: &Bar, out: &mut [f64]) {
537        let t = self.tenkan.mid(b);
538        let k = self.kijun.mid(b);
539        out[0] = t;
540        out[1] = k;
541        out[2] = f64::midpoint(t, k);
542        out[3] = self.senkou.mid(b);
543        out[4] = b.close;
544    }
545    fn push(&mut self, b: &Bar) {
546        self.tenkan.push(b);
547        self.kijun.push(b);
548        self.senkou.push(b);
549    }
550}
551
552/// Parabolic SAR; mirrors TA-Lib's `TA_SAR` (`docs/book/src/indicators.md`, SAR).
553#[derive(Clone, Copy)]
554struct SarState {
555    count: u8,
556    /// First bar's high and low.
557    first: (f64, f64),
558    is_long: bool,
559    af: f64,
560    ep: f64,
561    sar: f64,
562    /// Previous bar's high and low.
563    prev: (f64, f64),
564}
565
566pub(crate) struct SarCalc {
567    af_start: f64,
568    af_step: f64,
569    af_max: f64,
570    s: SarState,
571}
572
573impl SarCalc {
574    pub(crate) fn new(af_start: f64, af_step: f64, af_max: f64) -> Self {
575        Self {
576            af_start,
577            af_step,
578            af_max,
579            s: SarState {
580                count: 0,
581                first: (0.0, 0.0),
582                is_long: true,
583                af: af_start,
584                ep: 0.0,
585                sar: 0.0,
586                prev: (0.0, 0.0),
587            },
588        }
589    }
590
591    /// Advances `s` by `b`; returns the output.
592    fn step(&self, s: &mut SarState, b: &Bar) -> f64 {
593        let (new_high, new_low) = (b.high, b.low);
594        match s.count {
595            0 => {
596                s.first = (b.high, b.low);
597                s.count = 1;
598                return f64::NAN;
599            }
600            1 => {
601                let (h0, l0) = s.first;
602                let up_move = new_high - h0;
603                let down_move = l0 - new_low;
604                s.is_long = !(down_move > 0.0 && down_move > up_move);
605                s.af = self.af_start;
606                if s.is_long {
607                    (s.ep, s.sar) = (new_high, l0);
608                } else {
609                    (s.ep, s.sar) = (new_low, h0);
610                }
611                // TA-Lib starts with the previous bar equal to this one.
612                s.prev = (new_high, new_low);
613                s.count = 2;
614            }
615            _ => {}
616        }
617        let (prev_high, prev_low) = s.prev;
618        let out;
619        if s.is_long {
620            if new_low <= s.sar {
621                s.is_long = false;
622                s.sar = s.ep;
623                if s.sar < prev_high {
624                    s.sar = prev_high;
625                }
626                if s.sar < new_high {
627                    s.sar = new_high;
628                }
629                out = s.sar;
630                s.af = self.af_start;
631                s.ep = new_low;
632                s.sar = s.sar + s.af * (s.ep - s.sar);
633                if s.sar < prev_high {
634                    s.sar = prev_high;
635                }
636                if s.sar < new_high {
637                    s.sar = new_high;
638                }
639            } else {
640                out = s.sar;
641                if new_high > s.ep {
642                    s.ep = new_high;
643                    s.af = (s.af + self.af_step).min(self.af_max);
644                }
645                s.sar = s.sar + s.af * (s.ep - s.sar);
646                if s.sar > prev_low {
647                    s.sar = prev_low;
648                }
649                if s.sar > new_low {
650                    s.sar = new_low;
651                }
652            }
653        } else if new_high >= s.sar {
654            s.is_long = true;
655            s.sar = s.ep;
656            if s.sar > prev_low {
657                s.sar = prev_low;
658            }
659            if s.sar > new_low {
660                s.sar = new_low;
661            }
662            out = s.sar;
663            s.af = self.af_start;
664            s.ep = new_high;
665            s.sar = s.sar + s.af * (s.ep - s.sar);
666            if s.sar > prev_low {
667                s.sar = prev_low;
668            }
669            if s.sar > new_low {
670                s.sar = new_low;
671            }
672        } else {
673            out = s.sar;
674            if new_low < s.ep {
675                s.ep = new_low;
676                s.af = (s.af + self.af_step).min(self.af_max);
677            }
678            s.sar = s.sar + s.af * (s.ep - s.sar);
679            if s.sar < prev_high {
680                s.sar = prev_high;
681            }
682            if s.sar < new_high {
683                s.sar = new_high;
684            }
685        }
686        s.prev = (new_high, new_low);
687        out
688    }
689}
690
691impl Calc for SarCalc {
692    fn outputs(&self) -> usize {
693        1
694    }
695    fn peek(&self, b: &Bar, out: &mut [f64]) {
696        let mut s = self.s;
697        out[0] = self.step(&mut s, b);
698    }
699    fn push(&mut self, b: &Bar) {
700        let mut s = self.s;
701        self.step(&mut s, b);
702        self.s = s;
703    }
704}
705
706#[derive(Clone, Copy)]
707struct SuperTrendState {
708    atr: Atr,
709    started: bool,
710    up: f64,
711    dn: f64,
712    bull: bool,
713    prev_close: f64,
714}
715
716/// Outputs: long (lower band in up trends), short (upper band in down trends).
717pub(crate) struct SuperTrendCalc {
718    m: f64,
719    s: SuperTrendState,
720}
721
722impl SuperTrendCalc {
723    pub(crate) fn new(atr_n: usize, m: f64) -> Self {
724        Self {
725            m,
726            s: SuperTrendState {
727                atr: Atr::new(atr_n),
728                started: false,
729                up: f64::NAN,
730                dn: f64::NAN,
731                bull: true,
732                prev_close: f64::NAN,
733            },
734        }
735    }
736
737    fn step(&self, s: &mut SuperTrendState, b: &Bar, out: &mut [f64]) {
738        let a = s.atr.peek(b);
739        s.atr.push(b);
740        out[0] = f64::NAN;
741        out[1] = f64::NAN;
742        if !a.is_nan() {
743            let hl2 = f64::midpoint(b.high, b.low);
744            let basic_up = hl2 + self.m * a;
745            let basic_dn = hl2 - self.m * a;
746            if s.started {
747                if basic_up < s.up || s.prev_close > s.up {
748                    s.up = basic_up;
749                }
750                if basic_dn > s.dn || s.prev_close < s.dn {
751                    s.dn = basic_dn;
752                }
753                if s.bull && b.close < s.dn {
754                    s.bull = false;
755                } else if !s.bull && b.close > s.up {
756                    s.bull = true;
757                }
758            } else {
759                (s.up, s.dn, s.bull, s.started) = (basic_up, basic_dn, true, true);
760            }
761            if s.bull {
762                out[0] = s.dn;
763            } else {
764                out[1] = s.up;
765            }
766        }
767        s.prev_close = b.close;
768    }
769}
770
771impl Calc for SuperTrendCalc {
772    fn outputs(&self) -> usize {
773        2
774    }
775    fn peek(&self, b: &Bar, out: &mut [f64]) {
776        let mut s = self.s;
777        self.step(&mut s, b, out);
778    }
779    fn push(&mut self, b: &Bar) {
780        let mut s = self.s;
781        self.step(&mut s, b, &mut [0.0; 2]);
782        self.s = s;
783    }
784}
785
786/// Where VWAP restarts (`docs/book/src/indicators.md`, VWAP).
787#[derive(Clone, Copy, Debug, PartialEq, Eq)]
788pub enum VwapAnchor {
789    /// Every day (default).
790    Day,
791    /// Every week, starting on Monday.
792    Week,
793    /// Every month.
794    Month,
795    /// Once, at the first bar at or after this time (ms).
796    Time(i64),
797}
798
799const MS_DAY: i64 = 86_400_000;
800
801/// Months since 1970-01 of a day number (Howard Hinnant's algorithm).
802fn civil_month(days: i64) -> i64 {
803    let z = days + 719_468;
804    let era = z.div_euclid(146_097);
805    let doe = z - era * 146_097;
806    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
807    let mut y = yoe + era * 400;
808    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
809    let mp = (5 * doy + 2) / 153;
810    let month = if mp < 10 { mp + 3 } else { mp - 9 };
811    if month <= 2 {
812        y += 1;
813    }
814    y * 12 + month - 1
815}
816
817#[derive(Clone, Copy)]
818struct VwapState {
819    key: Option<i64>,
820    spv: f64,
821    sv: f64,
822}
823
824pub(crate) struct VwapCalc {
825    anchor: VwapAnchor,
826    utc_offset_ms: i64,
827    s: VwapState,
828}
829
830impl VwapCalc {
831    pub(crate) fn new(anchor: VwapAnchor, utc_offset_ms: i64) -> Self {
832        Self {
833            anchor,
834            utc_offset_ms,
835            s: VwapState {
836                key: None,
837                spv: 0.0,
838                sv: 0.0,
839            },
840        }
841    }
842
843    fn step(&self, s: &mut VwapState, b: &Bar) -> f64 {
844        let days = b.time.saturating_add(self.utc_offset_ms).div_euclid(MS_DAY);
845        let key = match self.anchor {
846            VwapAnchor::Time(t0) => {
847                if b.time < t0 {
848                    return f64::NAN;
849                }
850                0
851            }
852            VwapAnchor::Day => days,
853            VwapAnchor::Week => (days + 3).div_euclid(7),
854            VwapAnchor::Month => civil_month(days),
855        };
856        if s.key != Some(key) {
857            *s = VwapState {
858                key: Some(key),
859                spv: 0.0,
860                sv: 0.0,
861            };
862        }
863        s.spv += hlc3(b) * b.volume;
864        s.sv += b.volume;
865        div(s.spv, s.sv, f64::NAN)
866    }
867}
868
869impl Calc for VwapCalc {
870    fn outputs(&self) -> usize {
871        1
872    }
873    fn peek(&self, b: &Bar, out: &mut [f64]) {
874        let mut s = self.s;
875        out[0] = self.step(&mut s, b);
876    }
877    fn push(&mut self, b: &Bar) {
878        let mut s = self.s;
879        self.step(&mut s, b);
880        self.s = s;
881    }
882}
883
884// ---- 3. oscillators ----------------------------------------------------------
885
886/// Outputs: macd, signal, hist.
887pub(crate) struct MacdCalc {
888    src: Source,
889    fast: Smooth,
890    slow: Smooth,
891    signal: Smooth,
892}
893
894impl MacdCalc {
895    pub(crate) fn new(fast: usize, slow: usize, signal: usize, src: Source) -> Self {
896        Self {
897            src,
898            fast: Smooth::ema(fast),
899            slow: Smooth::ema(slow),
900            signal: Smooth::ema(signal),
901        }
902    }
903
904    fn macd(&self, p: f64) -> f64 {
905        self.fast.peek(p) - self.slow.peek(p)
906    }
907}
908
909impl Calc for MacdCalc {
910    fn outputs(&self) -> usize {
911        3
912    }
913    fn peek(&self, b: &Bar, out: &mut [f64]) {
914        let m = self.macd(self.src.of(b));
915        let s = self.signal.peek(m);
916        out[0] = m;
917        out[1] = s;
918        out[2] = m - s;
919    }
920    fn push(&mut self, b: &Bar) {
921        let p = self.src.of(b);
922        let m = self.macd(p);
923        self.fast.push(p);
924        self.slow.push(p);
925        self.signal.push(m);
926    }
927}
928
929/// RSI of a value stream.
930#[derive(Clone, Copy)]
931struct Rsi {
932    prev: Option<f64>,
933    gain: Smooth,
934    loss: Smooth,
935}
936
937impl Rsi {
938    fn new(n: usize) -> Self {
939        Self {
940            prev: None,
941            gain: Smooth::rma(n),
942            loss: Smooth::rma(n),
943        }
944    }
945
946    fn moves(&self, p: f64) -> (f64, f64) {
947        self.prev.map_or((f64::NAN, f64::NAN), |q| {
948            ((p - q).max(0.0), (q - p).max(0.0))
949        })
950    }
951
952    fn peek(&self, p: f64) -> f64 {
953        let (g, l) = self.moves(p);
954        let (ag, al) = (self.gain.peek(g), self.loss.peek(l));
955        if ag.is_nan() {
956            return f64::NAN;
957        }
958        div(100.0 * ag, ag + al, 50.0)
959    }
960
961    fn push(&mut self, p: f64) {
962        let (g, l) = self.moves(p);
963        self.gain.push(g);
964        self.loss.push(l);
965        self.prev = Some(p);
966    }
967}
968
969pub(crate) struct RsiCalc {
970    src: Source,
971    k: Rsi,
972}
973
974impl RsiCalc {
975    pub(crate) fn new(n: usize, src: Source) -> Self {
976        Self {
977            src,
978            k: Rsi::new(n),
979        }
980    }
981}
982
983impl Calc for RsiCalc {
984    fn outputs(&self) -> usize {
985        1
986    }
987    fn peek(&self, b: &Bar, out: &mut [f64]) {
988        out[0] = self.k.peek(self.src.of(b));
989    }
990    fn push(&mut self, b: &Bar) {
991        self.k.push(self.src.of(b));
992    }
993}
994
995/// `100·(x − min)/(max − min)`, 50 for a zero range.
996fn stoch_raw(x: f64, max: f64, min: f64) -> f64 {
997    if max.is_nan() || min.is_nan() {
998        return f64::NAN;
999    }
1000    div(100.0 * (x - min), max - min, 50.0)
1001}
1002
1003/// `%K = SMA(raw, smooth_k)`, `%D = SMA(%K, d)`.
1004struct KD {
1005    k: Sma,
1006    d: Sma,
1007}
1008
1009impl KD {
1010    fn new(smooth_k: usize, d: usize) -> Self {
1011        Self {
1012            k: Sma::new(smooth_k),
1013            d: Sma::new(d),
1014        }
1015    }
1016
1017    fn peek(&self, raw: f64, out: &mut [f64]) {
1018        let k = self.k.peek(raw);
1019        out[0] = k;
1020        out[1] = self.d.peek(k);
1021    }
1022
1023    fn push(&mut self, raw: f64) {
1024        let k = self.k.peek(raw);
1025        self.k.push(raw);
1026        self.d.push(k);
1027    }
1028}
1029
1030/// Outputs: k, d.
1031pub(crate) struct StochCalc {
1032    range: MidRange,
1033    kd: KD,
1034}
1035
1036impl StochCalc {
1037    pub(crate) fn new(k: usize, smooth_k: usize, d: usize) -> Self {
1038        Self {
1039            range: MidRange::new(k),
1040            kd: KD::new(smooth_k, d),
1041        }
1042    }
1043
1044    fn raw(&self, b: &Bar) -> f64 {
1045        let (h, l) = self.range.peek(b);
1046        stoch_raw(b.close, h, l)
1047    }
1048}
1049
1050impl Calc for StochCalc {
1051    fn outputs(&self) -> usize {
1052        2
1053    }
1054    fn peek(&self, b: &Bar, out: &mut [f64]) {
1055        self.kd.peek(self.raw(b), out);
1056    }
1057    fn push(&mut self, b: &Bar) {
1058        let raw = self.raw(b);
1059        self.range.push(b);
1060        self.kd.push(raw);
1061    }
1062}
1063
1064/// Outputs: k, d.
1065pub(crate) struct StochRsiCalc {
1066    src: Source,
1067    rsi: Rsi,
1068    hi: RollingExtreme,
1069    lo: RollingExtreme,
1070    kd: KD,
1071}
1072
1073impl StochRsiCalc {
1074    pub(crate) fn new(
1075        rsi_n: usize,
1076        stoch_n: usize,
1077        smooth_k: usize,
1078        d: usize,
1079        src: Source,
1080    ) -> Self {
1081        Self {
1082            src,
1083            rsi: Rsi::new(rsi_n),
1084            hi: RollingExtreme::max(stoch_n),
1085            lo: RollingExtreme::min(stoch_n),
1086            kd: KD::new(smooth_k, d),
1087        }
1088    }
1089
1090    fn raw(&self, r: f64) -> f64 {
1091        stoch_raw(r, self.hi.peek(r), self.lo.peek(r))
1092    }
1093}
1094
1095impl Calc for StochRsiCalc {
1096    fn outputs(&self) -> usize {
1097        2
1098    }
1099    fn peek(&self, b: &Bar, out: &mut [f64]) {
1100        let r = self.rsi.peek(self.src.of(b));
1101        self.kd.peek(self.raw(r), out);
1102    }
1103    fn push(&mut self, b: &Bar) {
1104        let p = self.src.of(b);
1105        let r = self.rsi.peek(p);
1106        let raw = self.raw(r);
1107        self.rsi.push(p);
1108        self.hi.push(r);
1109        self.lo.push(r);
1110        self.kd.push(raw);
1111    }
1112}
1113
1114pub(crate) struct CciCalc(Sma);
1115
1116impl CciCalc {
1117    pub(crate) fn new(n: usize) -> Self {
1118        Self(Sma::new(n))
1119    }
1120}
1121
1122impl Calc for CciCalc {
1123    fn outputs(&self) -> usize {
1124        1
1125    }
1126    fn peek(&self, b: &Bar, out: &mut [f64]) {
1127        let tp = hlc3(b);
1128        let ma = self.0.peek(tp);
1129        if ma.is_nan() {
1130            out[0] = f64::NAN;
1131            return;
1132        }
1133        let w = self.0.window();
1134        let mut sum = 0.0;
1135        for c in w.iter().chain(std::iter::once(tp)) {
1136            sum += (c - ma).abs();
1137        }
1138        let md = sum / (w.cap() + 1) as f64;
1139        out[0] = div(tp - ma, 0.015 * md, 0.0);
1140    }
1141    fn push(&mut self, b: &Bar) {
1142        self.0.push(hlc3(b));
1143    }
1144}
1145
1146pub(crate) struct WillrCalc(MidRange);
1147
1148impl WillrCalc {
1149    pub(crate) fn new(n: usize) -> Self {
1150        Self(MidRange::new(n))
1151    }
1152}
1153
1154impl Calc for WillrCalc {
1155    fn outputs(&self) -> usize {
1156        1
1157    }
1158    fn peek(&self, b: &Bar, out: &mut [f64]) {
1159        let (h, l) = self.0.peek(b);
1160        out[0] = if h.is_nan() {
1161            f64::NAN
1162        } else {
1163            div(-100.0 * (h - b.close), h - l, -50.0)
1164        };
1165    }
1166    fn push(&mut self, b: &Bar) {
1167        self.0.push(b);
1168    }
1169}
1170
1171pub(crate) struct MfiCalc {
1172    prev_tp: Option<f64>,
1173    pos: RollingSum,
1174    neg: RollingSum,
1175}
1176
1177impl MfiCalc {
1178    pub(crate) fn new(n: usize) -> Self {
1179        Self {
1180            prev_tp: None,
1181            pos: RollingSum::new(n),
1182            neg: RollingSum::new(n),
1183        }
1184    }
1185
1186    fn flows(&self, b: &Bar) -> (f64, f64) {
1187        let tp = hlc3(b);
1188        let mf = tp * b.volume;
1189        self.prev_tp.map_or((f64::NAN, f64::NAN), |q| {
1190            (if tp > q { mf } else { 0.0 }, if tp < q { mf } else { 0.0 })
1191        })
1192    }
1193}
1194
1195impl Calc for MfiCalc {
1196    fn outputs(&self) -> usize {
1197        1
1198    }
1199    fn peek(&self, b: &Bar, out: &mut [f64]) {
1200        let (p, n) = self.flows(b);
1201        let (sp, sn) = (self.pos.peek(p), self.neg.peek(n));
1202        out[0] = if sp.is_nan() {
1203            f64::NAN
1204        } else {
1205            div(100.0 * sp, sp + sn, 50.0)
1206        };
1207    }
1208    fn push(&mut self, b: &Bar) {
1209        let (p, n) = self.flows(b);
1210        self.pos.push(p);
1211        self.neg.push(n);
1212        self.prev_tp = Some(hlc3(b));
1213    }
1214}
1215
1216/// Outputs: adx, `plus_di`, `minus_di`.
1217pub(crate) struct AdxCalc {
1218    prev: Option<Bar>,
1219    pdm: WilderSum,
1220    mdm: WilderSum,
1221    tr: WilderSum,
1222    adx: Smooth,
1223}
1224
1225impl AdxCalc {
1226    pub(crate) fn new(n: usize) -> Self {
1227        Self {
1228            prev: None,
1229            pdm: WilderSum::new(n),
1230            mdm: WilderSum::new(n),
1231            tr: WilderSum::new(n),
1232            adx: Smooth::rma(n),
1233        }
1234    }
1235
1236    /// (+DM, −DM, TR), NaN on the first bar.
1237    fn moves(&self, b: &Bar) -> (f64, f64, f64) {
1238        let Some(p) = self.prev else {
1239            return (f64::NAN, f64::NAN, f64::NAN);
1240        };
1241        let up = b.high - p.high;
1242        let down = p.low - b.low;
1243        (
1244            if up > down && up > 0.0 { up } else { 0.0 },
1245            if down > up && down > 0.0 { down } else { 0.0 },
1246            true_range(b, Some(p.close)),
1247        )
1248    }
1249
1250    /// (+DI, −DI, DX).
1251    fn di(&self, b: &Bar) -> (f64, f64, f64) {
1252        let (p, m, t) = self.moves(b);
1253        let (sp, sm, st) = (self.pdm.peek(p), self.mdm.peek(m), self.tr.peek(t));
1254        if st.is_nan() {
1255            return (f64::NAN, f64::NAN, f64::NAN);
1256        }
1257        let pdi = div(100.0 * sp, st, 0.0);
1258        let mdi = div(100.0 * sm, st, 0.0);
1259        (pdi, mdi, div(100.0 * (pdi - mdi).abs(), pdi + mdi, 0.0))
1260    }
1261}
1262
1263impl Calc for AdxCalc {
1264    fn outputs(&self) -> usize {
1265        3
1266    }
1267    fn peek(&self, b: &Bar, out: &mut [f64]) {
1268        let (pdi, mdi, dx) = self.di(b);
1269        out[0] = self.adx.peek(dx);
1270        out[1] = pdi;
1271        out[2] = mdi;
1272    }
1273    fn push(&mut self, b: &Bar) {
1274        let (_, _, dx) = self.di(b);
1275        let (p, m, t) = self.moves(b);
1276        self.pdm.push(p);
1277        self.mdm.push(m);
1278        self.tr.push(t);
1279        self.adx.push(dx);
1280        self.prev = Some(*b);
1281    }
1282}
1283
1284#[derive(Clone, Copy, Default)]
1285pub(crate) struct ObvCalc {
1286    prev: Option<(f64, f64)>,
1287}
1288
1289impl ObvCalc {
1290    fn step(&self, b: &Bar) -> f64 {
1291        match self.prev {
1292            None => b.volume,
1293            Some((c, obv)) if b.close > c => obv + b.volume,
1294            Some((c, obv)) if b.close < c => obv - b.volume,
1295            Some((_, obv)) => obv,
1296        }
1297    }
1298}
1299
1300impl Calc for ObvCalc {
1301    fn outputs(&self) -> usize {
1302        1
1303    }
1304    fn peek(&self, b: &Bar, out: &mut [f64]) {
1305        out[0] = self.step(b);
1306    }
1307    fn push(&mut self, b: &Bar) {
1308        self.prev = Some((b.close, self.step(b)));
1309    }
1310}
1311
1312pub(crate) struct CmfCalc {
1313    mfv: RollingSum,
1314    v: RollingSum,
1315}
1316
1317impl CmfCalc {
1318    pub(crate) fn new(n: usize) -> Self {
1319        Self {
1320            mfv: RollingSum::new(n),
1321            v: RollingSum::new(n),
1322        }
1323    }
1324}
1325
1326fn money_flow_volume(b: &Bar) -> f64 {
1327    div((b.close - b.low) - (b.high - b.close), b.high - b.low, 0.0) * b.volume
1328}
1329
1330impl Calc for CmfCalc {
1331    fn outputs(&self) -> usize {
1332        1
1333    }
1334    fn peek(&self, b: &Bar, out: &mut [f64]) {
1335        let sv = self.v.peek(b.volume);
1336        out[0] = div(self.mfv.peek(money_flow_volume(b)), sv, f64::NAN);
1337    }
1338    fn push(&mut self, b: &Bar) {
1339        self.mfv.push(money_flow_volume(b));
1340        self.v.push(b.volume);
1341    }
1342}
1343
1344/// ROC or Momentum: compares with the value `n` bars back.
1345pub(crate) struct ChangeCalc {
1346    src: Source,
1347    ratio: bool,
1348    back: Ring,
1349}
1350
1351impl ChangeCalc {
1352    pub(crate) fn roc(n: usize, src: Source) -> Self {
1353        Self {
1354            src,
1355            ratio: true,
1356            back: Ring::new(n.max(1)),
1357        }
1358    }
1359
1360    pub(crate) fn momentum(n: usize, src: Source) -> Self {
1361        Self {
1362            src,
1363            ratio: false,
1364            back: Ring::new(n.max(1)),
1365        }
1366    }
1367}
1368
1369impl Calc for ChangeCalc {
1370    fn outputs(&self) -> usize {
1371        1
1372    }
1373    fn peek(&self, b: &Bar, out: &mut [f64]) {
1374        let p = self.src.of(b);
1375        out[0] = if self.back.is_full() {
1376            let old = self.back.get(0);
1377            if !self.ratio {
1378                p - old
1379            } else if old == 0.0 {
1380                f64::NAN
1381            } else {
1382                100.0 * (p / old - 1.0)
1383            }
1384        } else {
1385            f64::NAN
1386        };
1387    }
1388    fn push(&mut self, b: &Bar) {
1389        self.back.push(self.src.of(b));
1390    }
1391}
1392
1393pub(crate) struct TrixCalc {
1394    src: Source,
1395    k: EmaChain,
1396    /// The committed newest triple EMA.
1397    prev: f64,
1398}
1399
1400impl TrixCalc {
1401    pub(crate) fn new(n: usize, src: Source) -> Self {
1402        Self {
1403            src,
1404            k: EmaChain::new(n),
1405            prev: f64::NAN,
1406        }
1407    }
1408}
1409
1410impl Calc for TrixCalc {
1411    fn outputs(&self) -> usize {
1412        1
1413    }
1414    fn peek(&self, b: &Bar, out: &mut [f64]) {
1415        let e3 = self.k.peek(self.src.of(b))[2];
1416        out[0] = if self.prev.is_nan() || self.prev == 0.0 {
1417            f64::NAN
1418        } else {
1419            100.0 * (e3 / self.prev - 1.0)
1420        };
1421    }
1422    fn push(&mut self, b: &Bar) {
1423        let p = self.src.of(b);
1424        let e3 = self.k.peek(p)[2];
1425        self.k.push(p);
1426        self.prev = e3;
1427    }
1428}
1429
1430/// Outputs: up, down.
1431pub(crate) struct AroonCalc {
1432    n: usize,
1433    hi: RollingExtreme,
1434    lo: RollingExtreme,
1435}
1436
1437impl AroonCalc {
1438    pub(crate) fn new(n: usize) -> Self {
1439        let n = n.max(1);
1440        Self {
1441            n,
1442            hi: RollingExtreme::max(n + 1),
1443            lo: RollingExtreme::min(n + 1),
1444        }
1445    }
1446}
1447
1448impl Calc for AroonCalc {
1449    fn outputs(&self) -> usize {
1450        2
1451    }
1452    fn peek(&self, b: &Bar, out: &mut [f64]) {
1453        let n = self.n as f64;
1454        let (h, since_high) = self.hi.peek_at(b.high);
1455        let (_, since_low) = self.lo.peek_at(b.low);
1456        if h.is_nan() {
1457            out[0] = f64::NAN;
1458            out[1] = f64::NAN;
1459        } else {
1460            out[0] = 100.0 * (n - since_high as f64) / n;
1461            out[1] = 100.0 * (n - since_low as f64) / n;
1462        }
1463    }
1464    fn push(&mut self, b: &Bar) {
1465        self.hi.push(b.high);
1466        self.lo.push(b.low);
1467    }
1468}
1469
1470#[cfg(test)]
1471pub(crate) mod tests {
1472    use super::*;
1473
1474    const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures");
1475
1476    /// Each indicator with the defaults of `docs/book/src/indicators.md` and the name of
1477    /// its fixture.
1478    pub(crate) fn all() -> Vec<(&'static str, Box<dyn Calc>)> {
1479        factories().into_iter().map(|(n, f)| (n, f())).collect()
1480    }
1481
1482    /// Like [`all`], as factories.
1483    pub(crate) fn factories() -> Vec<(&'static str, crate::runner::Factory)> {
1484        macro_rules! f {
1485            ($e:expr) => {
1486                Box::new(move || Box::new($e) as Box<dyn Calc>) as crate::runner::Factory
1487            };
1488        }
1489        let c = Source::Close;
1490        vec![
1491            ("sma", f!(SmaCalc::new(20, c))),
1492            ("ema", f!(EmaCalc::new(20, c))),
1493            ("wma", f!(WmaCalc::new(20, c))),
1494            ("hma", f!(HmaCalc::new(20, c))),
1495            ("vwma", f!(VwmaCalc::new(20, c))),
1496            ("dema", f!(DemaCalc::new(20, c))),
1497            ("tema", f!(TemaCalc::new(20, c))),
1498            ("volume_ma", f!(VolumeMaCalc::new(20))),
1499            ("boll", f!(BollCalc::new(20, 2.0, c))),
1500            ("keltner", f!(KeltnerCalc::new(20, 2.0, 10))),
1501            ("donchian", f!(DonchianCalc::new(20))),
1502            ("ichimoku", f!(IchimokuCalc::new(9, 26, 52))),
1503            ("sar", f!(SarCalc::new(0.02, 0.02, 0.2))),
1504            ("supertrend", f!(SuperTrendCalc::new(10, 3.0))),
1505            ("vwap", f!(VwapCalc::new(VwapAnchor::Day, 0))),
1506            ("vwap_month", f!(VwapCalc::new(VwapAnchor::Month, 0))),
1507            ("macd", f!(MacdCalc::new(12, 26, 9, c))),
1508            ("rsi", f!(RsiCalc::new(14, c))),
1509            ("stoch", f!(StochCalc::new(14, 3, 3))),
1510            ("stochrsi", f!(StochRsiCalc::new(14, 14, 3, 3, c))),
1511            ("cci", f!(CciCalc::new(20))),
1512            ("willr", f!(WillrCalc::new(14))),
1513            ("mfi", f!(MfiCalc::new(14))),
1514            ("adx", f!(AdxCalc::new(14))),
1515            ("atr", f!(AtrCalc::new(14))),
1516            ("obv", f!(ObvCalc::default())),
1517            ("cmf", f!(CmfCalc::new(20))),
1518            ("roc", f!(ChangeCalc::roc(10, c))),
1519            ("momentum", f!(ChangeCalc::momentum(10, c))),
1520            ("trix", f!(TrixCalc::new(15, c))),
1521            ("aroon", f!(AroonCalc::new(14))),
1522        ]
1523    }
1524
1525    fn read_csv(name: &str) -> (Vec<String>, Vec<Vec<f64>>) {
1526        let text = std::fs::read_to_string(format!("{FIXTURES}/{name}.csv")).unwrap();
1527        let mut lines = text.lines();
1528        let header = lines
1529            .next()
1530            .unwrap()
1531            .split(',')
1532            .map(str::to_owned)
1533            .collect();
1534        let rows = lines
1535            .map(|l| l.split(',').map(|v| v.parse().unwrap()).collect())
1536            .collect();
1537        (header, rows)
1538    }
1539
1540    pub(crate) fn input() -> Vec<Bar> {
1541        read_csv("input")
1542            .1
1543            .into_iter()
1544            .map(|r| Bar {
1545                time: r[0] as i64,
1546                open: r[1],
1547                high: r[2],
1548                low: r[3],
1549                close: r[4],
1550                volume: r[5],
1551            })
1552            .collect()
1553    }
1554
1555    /// Full computation without display shifts: `[output][bar]`.
1556    pub(crate) fn run_raw(calc: &mut dyn Calc, bars: &[Bar]) -> Vec<Vec<f64>> {
1557        let mut out = vec![vec![f64::NAN; bars.len()]; calc.outputs()];
1558        let mut y = vec![0.0; calc.outputs()];
1559        for (t, b) in bars.iter().enumerate() {
1560            calc.peek(b, &mut y);
1561            calc.push(b);
1562            for (o, &v) in y.iter().enumerate() {
1563                out[o][t] = v;
1564            }
1565        }
1566        out
1567    }
1568
1569    /// Full computation with the display shifts of indicator `name`'s
1570    /// public outputs (`OutputSpec::shift`): `[output][bar]`, as drawn.
1571    pub(crate) fn run(name: &str, calc: &mut dyn Calc, bars: &[Bar]) -> Vec<Vec<f64>> {
1572        use ferrochart_core::plugin::Indicator;
1573        let raw = run_raw(calc, bars);
1574        let shifts: Vec<i32> = if name == "ichimoku" {
1575            let ind = crate::ichimoku(9, 26, 52, 26).unwrap();
1576            ind.outputs().iter().map(|o| o.shift).collect()
1577        } else {
1578            vec![0; raw.len()]
1579        };
1580        raw.iter()
1581            .zip(shifts)
1582            .map(|(col, s)| {
1583                (0..bars.len())
1584                    .map(|t| {
1585                        t.checked_add_signed(-(s as isize))
1586                            .and_then(|src| col.get(src))
1587                            .copied()
1588                            .unwrap_or(f64::NAN)
1589                    })
1590                    .collect()
1591            })
1592            .collect()
1593    }
1594
1595    fn close(a: f64, b: f64) -> bool {
1596        (a.is_nan() && b.is_nan()) || (a - b).abs() <= 1e-9 * b.abs().max(1.0)
1597    }
1598
1599    #[test]
1600    #[allow(clippy::float_cmp)] // exact by construction
1601    fn sources_follow_the_spec() {
1602        let b = Bar {
1603            time: 0,
1604            open: 1.0,
1605            high: 4.0,
1606            low: 0.5,
1607            close: 2.0,
1608            volume: 1.0,
1609        };
1610        let got = [
1611            Source::Close,
1612            Source::Open,
1613            Source::High,
1614            Source::Low,
1615            Source::Hl2,
1616            Source::Hlc3,
1617            Source::Ohlc4,
1618        ]
1619        .map(|s| s.of(&b));
1620        assert_eq!(got, [2.0, 1.0, 4.0, 0.5, 2.25, 6.5 / 3.0, 7.5 / 4.0]);
1621    }
1622
1623    /// VWAP restarts at Monday 00:00 (week) or starts at `t0` (time).
1624    #[test]
1625    #[allow(clippy::float_cmp)] // exact by construction
1626    fn vwap_anchors() {
1627        const DAY: i64 = 86_400_000;
1628        // 1970-01-05 was a Monday; bars every 12 h from Saturday 1970-01-03.
1629        let bars: Vec<Bar> = (0..8)
1630            .map(|i| {
1631                let p = f64::from(i) + 1.0;
1632                Bar {
1633                    time: 2 * DAY + i64::from(i) * DAY / 2,
1634                    open: p,
1635                    high: p,
1636                    low: p,
1637                    close: p,
1638                    volume: 1.0,
1639                }
1640            })
1641            .collect();
1642        let week = run_raw(&mut VwapCalc::new(VwapAnchor::Week, 0), &bars)[0].clone();
1643        // Saturday and Sunday (4 bars) average 1..4, then Monday restarts.
1644        assert_eq!(&week[..6], &[1.0, 1.5, 2.0, 2.5, 5.0, 5.5]);
1645        let anchored = run_raw(&mut VwapCalc::new(VwapAnchor::Time(3 * DAY), 0), &bars)[0].clone();
1646        assert!(anchored[..2].iter().all(|v| v.is_nan()));
1647        assert_eq!(&anchored[2..5], &[3.0, 3.5, 4.0]);
1648        // A UTC offset moves the session boundary: +12 h makes bar 3 Monday.
1649        let shifted = run_raw(&mut VwapCalc::new(VwapAnchor::Week, DAY / 2), &bars)[0].clone();
1650        assert_eq!(shifted[3], 4.0);
1651    }
1652
1653    /// The indicators TA-Lib has match it, from the
1654    /// first value on, or after the bars `docs/book/src/indicators.md` names where the
1655    /// seeds differ (MACD 250, ADX/DMI 450).
1656    #[test]
1657    fn indicators_match_ta_lib() {
1658        let bars = input();
1659        let calc = |name: &str| -> Box<dyn Calc> {
1660            match name {
1661                // TA-Lib's STOCHRSI does not smooth %K.
1662                "stochrsi" => Box::new(StochRsiCalc::new(14, 14, 1, 3, Source::Close)),
1663                _ => factories().into_iter().find(|(n, _)| *n == name).unwrap().1(),
1664            }
1665        };
1666        let names = [
1667            ("sma", 0),
1668            ("ema", 0),
1669            ("wma", 0),
1670            ("dema", 0),
1671            ("tema", 0),
1672            ("boll", 0),
1673            ("sar", 0),
1674            ("macd", 250),
1675            ("rsi", 0),
1676            ("stoch", 0),
1677            ("stochrsi", 0),
1678            ("cci", 0),
1679            ("willr", 0),
1680            ("mfi", 0),
1681            ("adx", 450),
1682            ("atr", 0),
1683            ("obv", 0),
1684            ("roc", 0),
1685            ("momentum", 0),
1686            ("trix", 0),
1687            ("aroon", 0),
1688        ];
1689        let mut failed = Vec::new();
1690        for (name, skip) in names {
1691            let (header, rows) = read_csv(&format!("talib/{name}"));
1692            let got = run(name, calc(name).as_mut(), &bars);
1693            for (o, col) in header.iter().enumerate() {
1694                let mut compared = 0;
1695                for t in skip..bars.len() {
1696                    let want = rows[t][o];
1697                    if want.is_nan() {
1698                        continue;
1699                    }
1700                    compared += 1;
1701                    if !close(got[o][t], want) {
1702                        failed.push(format!("{name}.{col}[{t}]: got {} want {want}", got[o][t]));
1703                        break;
1704                    }
1705                }
1706                assert!(compared > 500, "{name}.{col}: compared only {compared}");
1707            }
1708        }
1709        assert!(failed.is_empty(), "{}", failed.join("\n"));
1710    }
1711
1712    /// `docs/book/src/indicators.md`: every indicator matches the numpy reference.
1713    #[test]
1714    fn indicators_match_the_reference() {
1715        let bars = input();
1716        let mut failed = Vec::new();
1717        for (name, mut calc) in all() {
1718            let (header, rows) = read_csv(name);
1719            assert_eq!(header.len(), calc.outputs(), "{name}: outputs");
1720            let got = run(name, calc.as_mut(), &bars);
1721            for (o, col) in header.iter().enumerate() {
1722                let finite = rows.iter().filter(|r| r[o].is_finite()).count();
1723                assert!(
1724                    finite > bars.len() / 10,
1725                    "{name}.{col}: only {finite} values"
1726                );
1727                let bad = (0..bars.len()).find(|&t| !close(got[o][t], rows[t][o]));
1728                if let Some(t) = bad {
1729                    failed.push(format!(
1730                        "{name}.{col}[{t}]: got {} want {}",
1731                        got[o][t], rows[t][o]
1732                    ));
1733                }
1734            }
1735        }
1736        assert!(failed.is_empty(), "{}", failed.join("\n"));
1737    }
1738}