traquer 0.7.0

technical analysis library
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
//! Volume Indicators
//!
//! Provides technical indicators that measures the efficiency of price movement
//! by analyzing the relationship between price changes and trading volume.
//! Depending on the indicator, it may be a momentum indicator or trend indicator.
use std::iter;

use itertools::izip;
use num_traits::cast::ToPrimitive;

use crate::smooth;

fn vforce<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    close: &'a [T],
    volume: &'a [U],
) -> impl Iterator<Item = f64> + 'a {
    izip!(&high[1..], &low[1..], &close[1..], &volume[1..]).scan(
        (
            high[0].to_f64().unwrap(),
            low[0].to_f64().unwrap(),
            close[0].to_f64().unwrap(),
            0.0,
            0.0,
            0.0,
        ),
        |state, (h, l, c, v)| {
            // state = (h, l, c, trend, cm, dm)
            let (h, l, c, v) = (
                h.to_f64().unwrap(),
                l.to_f64().unwrap(),
                c.to_f64().unwrap(),
                v.to_f64().unwrap(),
            );
            let trend = ((h + l + c) - (state.0 + state.1 + state.2)).signum();
            let dm = h - l;
            let cm = if trend == state.3 {
                state.4 + dm
            } else {
                state.5 + dm
            };
            *state = (h, l, c, trend, cm, dm);
            Some(v * ((dm / cm) - 1.0) * trend * 200.0)
        },
    )
}

fn vforce_alt<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    close: &'a [T],
    volume: &'a [U],
) -> impl Iterator<Item = f64> + 'a {
    izip!(&high[1..], &low[1..], &close[1..], &volume[1..]).scan(
        (
            high[0].to_f64().unwrap(),
            low[0].to_f64().unwrap(),
            close[0].to_f64().unwrap(),
            0.0,
        ),
        |state, (h, l, c, v)| {
            let (h, l, c, v) = (
                h.to_f64().unwrap(),
                l.to_f64().unwrap(),
                c.to_f64().unwrap(),
                v.to_f64().unwrap(),
            );
            let trend = ((h + l + c) - (state.0 + state.1 + state.2)).signum();
            *state = (h, l, c, trend);
            Some(v * trend)
        },
    )
}

/// Klinger Volume Oscillator (KVO)
///
/// Developed by Stephen Klinger. It helps determine the long-term trend of money flow
/// while remaining sensitive enough to detect short-term fluctuations.
///
/// An alt algorithm is available which computes the vforce value as simply
/// volume * trend. This behaviour matches some existing popular tools.
///
/// ## Usage
///
/// When the value is above its signal line and/or it crosses above 0, it suggests an uptrend.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/terms/k/klingeroscillator.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::kvo(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     3, 6, None).collect::<Vec<f64>>();
///
/// ```
pub fn kvo<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    close: &'a [T],
    volume: &'a [U],
    short: usize,
    long: usize,
    alt: Option<bool>,
) -> impl Iterator<Item = f64> + 'a {
    let vf = if alt.unwrap_or(true) {
        vforce_alt(high, low, close, volume).collect::<Vec<f64>>()
    } else {
        vforce(high, low, close, volume).collect::<Vec<f64>>()
    };
    let short_ma = smooth::ewma(&vf, short);
    let long_ma = smooth::ewma(&vf, long);
    iter::once(f64::NAN).chain(
        short_ma
            .zip(long_ma)
            .map(|(x, y)| x - y)
            .collect::<Vec<f64>>(),
    )
}

fn wilder_sum<T: ToPrimitive>(data: &[T], window: usize) -> impl Iterator<Item = f64> + '_ {
    let initial = data[..(window - 1)]
        .iter()
        .filter_map(|x| x.to_f64())
        .sum::<f64>();
    data[(window - 1)..].iter().scan(initial, move |state, x| {
        let ma = *state * (window - 1) as f64 / window as f64 + x.to_f64().unwrap();
        *state = ma;
        Some(ma)
    })
}

/// Twiggs Money Flow
///
/// Developed by Colin Twiggs that measures the flow of money into and out of a security.
/// It's similar to the Accumulation/Distribution Line. A rising TMF indicates buying pressure,
/// as more money is flowing into the security.
///
/// ## Usage
///
/// A value above 0 suggests an uptrend.
///
/// ## Sources
///
/// [[1]](https://www.marketvolume.com/technicalanalysis/twiggsmoneyflow.asp)
/// [[2]](https://www.incrediblecharts.com/indicators/twiggs_money_flow.php)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::twiggs(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     6).collect::<Vec<f64>>();
///
/// ```
pub fn twiggs<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    close: &'a [T],
    volume: &'a [U],
    window: usize,
) -> impl Iterator<Item = f64> + 'a {
    let data = izip!(&high[1..], &low[1..], &close[1..], &volume[1..]);
    // not using wilder moving average to minimise drift caused by floating point math
    iter::repeat(f64::NAN).take(window).chain(
        wilder_sum(
            &data
                .scan(close[0].to_f64().unwrap(), |state, (h, l, c, vol)| {
                    let (h, l, c, vol) = (
                        h.to_f64().unwrap(),
                        l.to_f64().unwrap(),
                        c.to_f64().unwrap(),
                        vol.to_f64().unwrap(),
                    );
                    let range_vol = vol
                        * ((2.0 * c - f64::min(l, *state) - f64::max(h, *state))
                            / (f64::max(h, *state) - f64::min(l, *state)));
                    *state = c;
                    Some(range_vol)
                })
                .collect::<Vec<f64>>(),
            window,
        )
        .zip(wilder_sum(&volume[1..], window))
        .map(|(range, vol)| range / vol)
        .collect::<Vec<f64>>(),
    )
}

/// Accumulation/Distribution (A/D) indicator
///
/// Developed by Marc Chaikin. A momentum indicator that measures the flow of money into
/// and out of a security.
///
/// Calculated by multiplying the money flow multiplier (which is based on the security's
/// price and volume) by the money flow volume (which is the volume at the current price level).
/// This function supports alternate logic to consider prior close like yahoo
///
/// ## Usage
///
/// An increasing value suggests an uptrend.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/terms/a/accumulationdistribution.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::ad(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     None).collect::<Vec<f64>>();
///
/// ```
pub fn ad<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    close: &'a [T],
    volume: &'a [U],
    alt: Option<bool>,
) -> Box<dyn Iterator<Item = f64> + 'a> {
    if !alt.unwrap_or(false) {
        Box::new(
            izip!(high, low, close, volume).scan(0.0, |state, (h, l, c, vol)| {
                let (h, l, c, vol) = (
                    h.to_f64().unwrap(),
                    l.to_f64().unwrap(),
                    c.to_f64().unwrap(),
                    vol.to_f64().unwrap(),
                );
                let mfm = ((c - l) - (h - c)) / (h - l);
                let mfv = mfm * vol;
                let adl = *state + mfv;
                *state = adl;
                Some(adl)
            }),
        )
    } else {
        // alternate logic to consider prior close like yahoo
        Box::new(iter::once(f64::NAN).chain(
            izip!(&high[1..], &low[1..], &close[1..], &volume[1..]).scan(
                (close[0].to_f64().unwrap(), 0.0),
                |state, (h, l, c, vol)| {
                    let (h, l, c, vol) = (
                        h.to_f64().unwrap(),
                        l.to_f64().unwrap(),
                        c.to_f64().unwrap(),
                        vol.to_f64().unwrap(),
                    );
                    let mfm = if c > state.0 {
                        c - f64::min(l, state.0)
                    } else {
                        c - f64::max(h, state.0)
                    };
                    let mfv = mfm * vol;
                    let adl = state.1 + mfv;
                    *state = (c, adl);
                    Some(adl)
                },
            ),
        ))
    }
}

/// Elder Force Index
///
/// Calculated by multiplying the change in price by the volume traded during that period.
/// A high EFI value indicates a strong price move with high volume, which can be a sign of
/// a strong trend
///
/// ## Usage
///
/// A value above 0 suggests an uptrend.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/articles/trading/03/031203.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::elder_force(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     6).collect::<Vec<f64>>();
///
/// ```
pub fn elder_force<'a, T: ToPrimitive, U: ToPrimitive>(
    close: &'a [T],
    volume: &'a [U],
    window: usize,
) -> impl Iterator<Item = f64> + 'a {
    iter::once(f64::NAN).chain(
        smooth::ewma(
            &izip!(&close[..close.len() - 1], &close[1..], &volume[1..])
                .map(|(prev, curr, vol)| {
                    (curr.to_f64().unwrap() - prev.to_f64().unwrap()) * vol.to_f64().unwrap()
                })
                .collect::<Vec<f64>>(),
            window,
        )
        .collect::<Vec<f64>>(),
    )
}

/// Money Flow Index
///
/// Calculated by using the typical price and the volume traded during that period.
/// A high MFI value (above 80) indicates that the security is overbought, and a
/// correction may be due.
///
/// ## Usage
///
/// Typically, a value above 80 suggests overbought and a value below 20, oversold.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/terms/m/mfi.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::mfi(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     6).collect::<Vec<f64>>();
///
/// ```
pub fn mfi<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    close: &'a [T],
    volume: &'a [U],
    window: usize,
) -> impl Iterator<Item = f64> + 'a {
    let (pos_mf, neg_mf): (Vec<f64>, Vec<f64>) =
        izip!(&high[1..], &low[1..], &close[1..], &volume[1..])
            .scan(
                (high[0].to_f64().unwrap() + low[0].to_f64().unwrap() + close[0].to_f64().unwrap())
                    / 3.0,
                |state, (h, l, c, vol)| {
                    let (h, l, c, vol) = (
                        h.to_f64().unwrap(),
                        l.to_f64().unwrap(),
                        c.to_f64().unwrap(),
                        vol.to_f64().unwrap(),
                    );
                    let hlc = (h + l + c) / 3.0;
                    let pos_mf = if hlc > *state { hlc * vol } else { 0.0 };
                    let neg_mf = if hlc < *state { hlc * vol } else { 0.0 };
                    *state = hlc;
                    Some((pos_mf, neg_mf))
                },
            )
            .unzip();
    iter::repeat(f64::NAN).take(window).chain(
        pos_mf
            .windows(window)
            .zip(neg_mf.windows(window))
            .map(|(pos, neg)| {
                100.0 - (100.0 / (1.0 + pos.iter().sum::<f64>() / neg.iter().sum::<f64>()))
            })
            .collect::<Vec<f64>>(),
    )
}

/// Chaikin Money Flow
///
/// Calculated by multiplying the money flow multiplier (which is based on the
/// security's price and volume) by the money flow volume (which is the volume at
/// the current price level). A positive CMF value indicates that money is flowing into
/// the security, which can be a sign of buying pressure.
///
/// ## Usage
///
/// A value above 0 suggests an uptrend.
///
/// ## Sources
///
/// [[1]](https://corporatefinanceinstitute.com/resources/equities/chaikin-money-flow-cmf/)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::cmf(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     6).collect::<Vec<f64>>();
///
/// ```
pub fn cmf<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    close: &'a [T],
    volume: &'a [U],
    window: usize,
) -> impl Iterator<Item = f64> + 'a {
    iter::repeat(f64::NAN).take(window - 1).chain(
        izip!(high, low, close, volume)
            .map(|(h, l, c, vol)| {
                let (h, l, c, vol) = (
                    h.to_f64().unwrap(),
                    l.to_f64().unwrap(),
                    c.to_f64().unwrap(),
                    vol.to_f64().unwrap(),
                );
                vol * ((c - l) - (h - c)) / (h - l)
            })
            .collect::<Vec<f64>>()
            .windows(window)
            .zip(volume.windows(window))
            .map(|(mfv_win, v_win)| {
                mfv_win.iter().sum::<f64>() / v_win.iter().filter_map(|x| x.to_f64()).sum::<f64>()
            })
            .collect::<Vec<f64>>(),
    )
}

/// Trade Volume Index
///
/// Measures the flow of money into and out of a security by analyzing the trading volume at
/// different price levels.
///
/// ## Usage
///
/// An increasing value suggests an uptrend.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/terms/t/tradevolumeindex.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::tvi(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     0.5).collect::<Vec<f64>>();
///
/// ```
pub fn tvi<'a, T: ToPrimitive, U: ToPrimitive>(
    close: &'a [T],
    volume: &'a [U],
    min_tick: f64,
) -> impl Iterator<Item = f64> + 'a {
    iter::once(f64::NAN).chain(
        izip!(&close[..close.len() - 1], &close[1..], &volume[1..],).scan(
            (1, 0.0),
            move |state, (prev, curr, vol)| {
                let (prev, curr, vol) = (
                    prev.to_f64().unwrap(),
                    curr.to_f64().unwrap(),
                    vol.to_f64().unwrap(),
                );
                let direction = if curr - prev > min_tick {
                    1
                } else if prev - curr > min_tick {
                    -1
                } else {
                    state.0
                };
                let tvi = state.1 + direction as f64 * vol;
                *state = (direction, tvi);
                Some(tvi)
            },
        ),
    )
}

/// Ease of Movement
///
/// Ease shows the amount of volume required to move prices by a certain amount.
/// A high Ease value indicates that prices can move easily with low volume, while a
/// low Ease value indicates that prices are difficult to move and require high volume.
///
/// ## Usage
///
/// A value above 0 suggests an uptrend.
///
/// ## Sources
/// [[1]](https://www.investopedia.com/terms/e/easeofmovement.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::ease(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     6).collect::<Vec<f64>>();
///
/// ```
pub fn ease<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    volume: &'a [U],
    window: usize,
) -> impl Iterator<Item = f64> + 'a {
    iter::once(f64::NAN).chain(
        smooth::sma(
            &(1..high.len())
                .map(|i| {
                    (high[i].to_f64().unwrap() + low[i].to_f64().unwrap()
                        - high[i - 1].to_f64().unwrap()
                        - low[i - 1].to_f64().unwrap())
                        / 2.0
                        / (volume[i].to_f64().unwrap()
                            / 100000000.0
                            / (high[i].to_f64().unwrap() - low[i].to_f64().unwrap()))
                })
                .collect::<Vec<f64>>(),
            window,
        )
        .collect::<Vec<f64>>(),
    )
}

/// On-Balance Volume
///
/// Shows the cumulative total of volume traded on up days minus the cumulative total of
/// volume traded on down days.
///
/// ## Usage
///
/// An increasing value suggests an uptrend.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/terms/o/onbalancevolume.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::obv(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0]).collect::<Vec<f64>>();
///
/// ```
pub fn obv<'a, T: ToPrimitive, U: ToPrimitive>(
    close: &'a [T],
    volume: &'a [U],
) -> impl Iterator<Item = f64> + 'a {
    iter::once(f64::NAN).chain(close.windows(2).enumerate().scan(0.0, |state, (i, pairs)| {
        *state += (pairs[1].to_f64().unwrap() - pairs[0].to_f64().unwrap()).signum()
            * volume[i + 1].to_f64().unwrap();
        Some(*state)
    }))
}

/// Market Facilitation Index
///
/// Shows the amount of price change per unit of volume traded. A high BW MFI value
/// indicates that prices are moving efficiently with low volume, while a low BW MFI
/// value indicates that prices are moving inefficiently with high volume.
///
/// ## Usage
///
/// If both value and volume increases, suggests uptrend.
///
/// ## Sources
///
/// [[1]](https://www.metatrader5.com/en/terminal/help/indicators/bw_indicators/market_facilitation)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::bw_mfi(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0]).collect::<Vec<f64>>();
///
/// ```
pub fn bw_mfi<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    volume: &'a [U],
) -> impl Iterator<Item = f64> + 'a {
    high.iter().zip(low).zip(volume).map(|((h, l), vol)| {
        (h.to_f64().unwrap() - l.to_f64().unwrap()) / vol.to_f64().unwrap() * (10.0_f64).powi(6)
    })
}

/// Positive Volume Index
///
/// Based on price moves depending on whether the current volume is higher than
/// the previous period.
///
/// ## Usage
///
/// When above the one year average, confirmation of uptrend.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/terms/p/pvi.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::pvi(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0]).collect::<Vec<f64>>();
///
/// ```
pub fn pvi<'a, T: ToPrimitive, U: ToPrimitive>(
    data: &'a [T],
    volume: &'a [U],
) -> impl Iterator<Item = f64> + 'a {
    iter::once(f64::NAN).chain(data.windows(2).zip(volume.windows(2)).scan(
        100.0,
        |state, (c, vol)| {
            if vol[1].to_f64().unwrap() > vol[0].to_f64().unwrap() {
                *state *= c[1].to_f64().unwrap() / c[0].to_f64().unwrap();
            }
            Some(*state)
        },
    ))
}

/// Negative Volume Index
///
/// Based on price moves depending on whether the current volume is higher than
/// the previous period.
///
/// ## Usage
///
/// When above the one year average, confirmation of downtrend.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/terms/n/nvi.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::nvi(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0]).collect::<Vec<f64>>();
///
/// ```
pub fn nvi<'a, T: ToPrimitive, U: ToPrimitive>(
    data: &'a [T],
    volume: &'a [U],
) -> impl Iterator<Item = f64> + 'a {
    iter::once(f64::NAN).chain(data.windows(2).zip(volume.windows(2)).scan(
        100.0,
        |state, (c, vol)| {
            if vol[1].to_f64().unwrap() < vol[0].to_f64().unwrap() {
                *state *= c[1].to_f64().unwrap() / c[0].to_f64().unwrap();
            }
            Some(*state)
        },
    ))
}

/// Volume Weighted Average Price (VWAP)
///
/// Measures the average typical price by volume. Tracks similar to a moving average.
///
/// ## Usage
///
/// Designed for intraday data, instruments with prices below VWAP may be considered undervalued.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/terms/v/vwap.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::vwap(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0], None).collect::<Vec<f64>>();
///
/// ```
pub fn vwap<'a, T: ToPrimitive, U: ToPrimitive>(
    high: &'a [T],
    low: &'a [T],
    close: &'a [T],
    volume: &'a [U],
    reset_idx: Option<&'a [usize]>,
) -> impl Iterator<Item = f64> + 'a {
    // NOTE: assumes reset_idx is sorted
    let mut reset_idx = reset_idx.unwrap_or(&[close.len()]).to_vec();
    izip!(high, low, close, volume).enumerate().scan(
        (0.0, 0.0),
        move |state, (idx, (h, l, c, vol))| {
            let (h, l, c, vol) = (
                h.to_f64().unwrap(),
                l.to_f64().unwrap(),
                c.to_f64().unwrap(),
                vol.to_f64().unwrap(),
            );
            let (mut tpv_sum, mut vol_sum) = state;
            if idx == reset_idx[0] {
                tpv_sum = 0.0;
                vol_sum = 0.0;
                reset_idx.rotate_left(1);
            }
            tpv_sum += (h + l + c) / 3.0 * vol;
            vol_sum += vol;
            *state = (tpv_sum, vol_sum);
            Some(tpv_sum / vol_sum)
        },
    )
}

/// Volume Weighted Moving Average
///
/// Measures price by volume. Tracks similar to a moving average. A period with a
/// higher volume will significantly influence the value more than a period with a lower volume.
///
/// ## Usage
///
/// Show trend like any normal moving average.
///
/// ## Sources
///
/// [[1]](https://howtotrade.com/indicators/volume-weighted-moving-average/)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::vwma(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0], 3).collect::<Vec<f64>>();
///
/// ```
pub fn vwma<'a, T: ToPrimitive, U: ToPrimitive>(
    data: &'a [T],
    volume: &'a [U],
    window: usize,
) -> impl Iterator<Item = f64> + 'a {
    iter::repeat(f64::NAN).take(window - 1).chain(
        data.windows(window)
            .zip(volume.windows(window))
            .map(|(data_w, vol_w)| {
                data_w.iter().zip(vol_w).fold(0.0, |acc, (x, v)| {
                    acc + x.to_f64().unwrap() * v.to_f64().unwrap()
                }) / vol_w.iter().filter_map(|x| x.to_f64()).sum::<f64>()
            }),
    )
}

/// Volume Price Trend
///
/// Consists of a cumulative volume line that adds or subtracts a multiple of the
/// percentage change in a share price’s trend and current volume.
///
/// ## Usage
///
/// Increasing value suggests an uptrend.
///
/// ## Sources
///
/// [[1]](https://www.investopedia.com/ask/answers/030315/what-volume-price-trend-indicator-vpt-formula-and-how-it-calculated.asp)
///
/// # Examples
///
/// ```
/// use traquer::volume;
///
/// volume::vpt(
///     &[1.0,2.0,3.0,4.0,5.0,6.0,4.0,5.0],
///     &[1,2,3,4,5,6,4,5]).collect::<Vec<f64>>();
///
/// ```
pub fn vpt<'a, T: ToPrimitive, U: ToPrimitive>(
    data: &'a [T],
    volume: &'a [U],
) -> impl Iterator<Item = f64> + 'a {
    iter::once(f64::NAN).chain(
        data.windows(2)
            .zip(&volume[1..])
            .scan(0.0, |state, (w, v)| {
                *state += v.to_f64().unwrap() * (w[1].to_f64().unwrap() - w[0].to_f64().unwrap())
                    / w[0].to_f64().unwrap();
                Some(*state)
            }),
    )
}