nanobook 0.17.0

Deterministic Rust execution engine for trading backtests: limit-order book, portfolio simulation, metrics, risk checks, and Python bindings
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
//! Technical analysis indicators.
//!
//! Drop-in replacements for TA-Lib's RSI, MACD, Bollinger Bands, and ATR.
//! All functions use the same algorithms and conventions as TA-Lib so that
//! outputs are numerically identical (within floating-point tolerance).
//!
//! # Conventions
//!
//! - Input slices are `&[f64]` (closing prices, or OHLC for ATR).
//! - Output `Vec<f64>` has the same length as input; elements within the
//!   lookback period are filled with `f64::NAN`.
//! - **Wilder's smoothing** (RSI, ATR): `alpha = 1/period`, NOT `2/(period+1)`.
//! - **Standard EMA** (MACD): `alpha = 2/(period+1)`.
//!
//! # References
//!
//! - TA-Lib source: `ta_RSI.c`, `ta_MACD.c`, `ta_BBANDS.c`, `ta_ATR.c`
//!   <https://github.com/TA-Lib/ta-lib/tree/main/src/ta_func>

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Standard exponential moving average (alpha = 2/(period+1)).
///
/// Used by MACD (fast EMA, slow EMA, signal line).
pub fn ema(values: &[f64], period: usize) -> Vec<f64> {
    let n = values.len();
    let mut out = vec![f64::NAN; n];
    if n < period || period == 0 {
        return out;
    }

    // Seed: simple average of first `period` values
    let seed: f64 = values[..period].iter().sum::<f64>() / period as f64;
    out[period - 1] = seed;

    let multiplier = 2.0 / (period as f64 + 1.0);
    for i in period..n {
        out[i] = (values[i] - out[i - 1]) * multiplier + out[i - 1];
    }
    out
}

/// Simple moving average.
pub fn sma(values: &[f64], period: usize) -> Vec<f64> {
    let n = values.len();
    let mut out = vec![f64::NAN; n];
    if n < period || period == 0 {
        return out;
    }

    let mut window_sum: f64 = values[..period].iter().sum();
    out[period - 1] = window_sum / period as f64;

    for i in period..n {
        window_sum += values[i] - values[i - period];
        out[i] = window_sum / period as f64;
    }
    out
}

/// Population standard deviation (ddof=0) over a rolling window.
///
/// Returns NaN for the lookback period.
///
/// # Numerical notes
///
/// Earlier implementations used an O(1) sliding state with the formula
/// `sum_sq / k - mean^2`. This formula suffers catastrophic cancellation
/// on high-mean, low-variance series (e.g., a $1000 stock with sub-cent
/// moves): both terms are large and nearly equal, so their difference
/// loses most of its precision to rounding. The `.max(0.0)` guard then
/// silently clamps the (now slightly negative) cancelled variance to
/// zero, so `rolling_std_pop` returned exactly 0 — and Bollinger bands
/// collapsed to the middle band.
///
/// This rewrite recomputes Welford per window, O(window) per step.
fn rolling_std_pop(values: &[f64], period: usize) -> Vec<f64> {
    let n = values.len();
    let mut out = vec![f64::NAN; n];
    if n < period || period == 0 {
        return out;
    }

    let k = period as f64;
    for i in (period - 1)..n {
        let slice = &values[i + 1 - period..=i];
        let (_mean, m2) = crate::stats::welford_mean_m2(slice);
        out[i] = (m2 / k).max(0.0).sqrt();
    }
    out
}

// ---------------------------------------------------------------------------
// Public indicators
// ---------------------------------------------------------------------------

/// Compute RSI value from average gain/loss (TA-Lib convention).
///
/// - Both zero (flat price) returns 0.0.
/// - Zero loss (always up) returns 100.0.
/// - Otherwise: 100 - 100/(1 + gain/loss).
fn rsi_from_avgs(avg_gain: f64, avg_loss: f64) -> f64 {
    if avg_gain == 0.0 && avg_loss == 0.0 {
        0.0
    } else if avg_loss == 0.0 {
        100.0
    } else {
        100.0 - 100.0 / (1.0 + avg_gain / avg_loss)
    }
}

/// Relative Strength Index (Wilder's smoothing).
///
/// Matches TA-Lib `ta_RSI.c` behavior:
/// - Lookback: first `period` elements are NaN.
/// - When all gains are zero (flat price), returns 0.0 (not 50.0).
/// - When all losses are zero (always up), returns 100.0.
///
/// # Insufficient data
///
/// Returns a vector of `close.len()` NaN values when
/// `close.len() <= period` or `period == 0`. At least `period + 1` prices
/// are required to produce the first non-NaN RSI value (one extra point
/// to compute the `period` price changes used for the initial
/// gain/loss averages). Matches TA-Lib.
///
/// # Arguments
///
/// * `close` — Closing prices.
/// * `period` — Lookback period (typically 14).
///
/// # Example
///
/// ```
/// use nanobook::indicators::rsi;
///
/// let close = vec![44.0, 44.25, 44.50, 43.75, 44.50, 44.25, 43.50,
///                  44.00, 44.50, 43.25, 43.00, 43.50, 44.00, 44.50,
///                  44.25, 44.00, 43.50, 43.75, 44.00, 43.25];
/// let result = rsi(&close, 14);
/// assert!(result[13].is_nan());  // lookback period
/// assert!(!result[14].is_nan()); // first valid RSI
/// ```
pub fn rsi(close: &[f64], period: usize) -> Vec<f64> {
    let n = close.len();
    let mut out = vec![f64::NAN; n];
    if n <= period || period == 0 {
        return out;
    }

    // Seed with simple average over first `period` changes (indices 1..=period)
    let mut avg_gain = 0.0_f64;
    let mut avg_loss = 0.0_f64;
    for i in 1..=period {
        let diff = close[i] - close[i - 1];
        if diff > 0.0 {
            avg_gain += diff;
        } else {
            avg_loss -= diff;
        }
    }
    avg_gain /= period as f64;
    avg_loss /= period as f64;

    // First RSI value
    out[period] = rsi_from_avgs(avg_gain, avg_loss);

    // Subsequent values with Wilder's smoothing
    for i in (period + 1)..n {
        let diff = close[i] - close[i - 1];
        let gain = if diff > 0.0 { diff } else { 0.0 };
        let loss = if diff < 0.0 { -diff } else { 0.0 };
        avg_gain = (avg_gain * (period as f64 - 1.0) + gain) / period as f64;
        avg_loss = (avg_loss * (period as f64 - 1.0) + loss) / period as f64;

        out[i] = rsi_from_avgs(avg_gain, avg_loss);
    }

    out
}

/// Moving Average Convergence Divergence (MACD).
///
/// Matches TA-Lib `ta_MACD.c` behavior:
/// - Fast/slow lines use standard EMA (alpha = 2/(period+1)).
/// - Signal line is EMA of the MACD line.
/// - Histogram = MACD line − signal line.
///
/// Returns `(macd_line, signal_line, histogram)`.
///
/// NaN is filled for the lookback period: `slow_period + signal_period - 2` elements.
///
/// # Arguments
///
/// * `close` — Closing prices.
/// * `fast_period` — Fast EMA period (typically 12).
/// * `slow_period` — Slow EMA period (typically 26).
/// * `signal_period` — Signal line EMA period (typically 9).
pub fn macd(
    close: &[f64],
    fast_period: usize,
    slow_period: usize,
    signal_period: usize,
) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
    let n = close.len();
    let nan_vec = || vec![f64::NAN; n];

    if n < slow_period
        || fast_period == 0
        || slow_period == 0
        || signal_period == 0
        || fast_period >= slow_period
    {
        return (nan_vec(), nan_vec(), nan_vec());
    }

    // TA-Lib aligns both EMAs so they first produce a value at index slow_period-1.
    // The fast EMA is seeded from close[slow_period-fast_period..slow_period],
    // NOT from close[0..fast_period]. This ensures both EMAs start from the same bar.
    let offset = slow_period - fast_period;
    let fast_ema = ema(&close[offset..], fast_period);
    let slow_ema = ema(close, slow_period);

    // MACD line = fast EMA - slow EMA (internally valid from slow_period - 1).
    let slow_first = slow_period - 1;
    let mut macd_internal = vec![f64::NAN; n];
    for i in slow_first..n {
        let fi = i - offset;
        if !fast_ema[fi].is_nan() && !slow_ema[i].is_nan() {
            macd_internal[i] = fast_ema[fi] - slow_ema[i];
        }
    }

    // Signal line = EMA of the MACD line (seeded from slow_first).
    let signal_raw = ema(&macd_internal[slow_first..], signal_period);

    // TA-Lib exposes macd/signal/histogram only once the signal EMA is
    // warm: lookback = slow_period + signal_period - 2 (first index =
    // slow_first + signal_period - 1).
    let output_first = slow_first + signal_period - 1;

    let mut macd_line = vec![f64::NAN; n];
    let mut signal_line = vec![f64::NAN; n];
    let mut histogram = vec![f64::NAN; n];

    for (j, &sig) in signal_raw.iter().enumerate() {
        let i = slow_first + j;
        if i >= output_first && !macd_internal[i].is_nan() && !sig.is_nan() {
            macd_line[i] = macd_internal[i];
            signal_line[i] = sig;
            histogram[i] = macd_internal[i] - sig;
        }
    }

    (macd_line, signal_line, histogram)
}

/// Bollinger Bands (SMA +/- k * population standard deviation).
///
/// Matches TA-Lib `ta_BBANDS.c` behavior:
/// - Middle band = SMA.
/// - Upper band = SMA + num_std_up * stddev.
/// - Lower band = SMA - num_std_dn * stddev.
/// - Uses **population** standard deviation (ddof=0), matching TA-Lib.
///
/// Returns `(upper, middle, lower)`.
///
/// # Arguments
///
/// * `close` — Closing prices.
/// * `period` — SMA/stddev period (typically 20).
/// * `num_std_up` — Number of standard deviations above SMA (typically 2.0).
/// * `num_std_dn` — Number of standard deviations below SMA (typically 2.0).
///
/// # Zero-width bands
///
/// If `num_std_up == 0.0` the upper band equals the middle band
/// (SMA) exactly; likewise for `num_std_dn == 0.0` and the lower band.
/// No warning or error is emitted — this is a supported configuration
/// for callers who want a plain SMA returned alongside only one band, or
/// a bare SMA via `bbands(..., 0.0, 0.0)`.
pub fn bbands(
    close: &[f64],
    period: usize,
    num_std_up: f64,
    num_std_dn: f64,
) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
    let n = close.len();
    let middle = sma(close, period);
    let std = rolling_std_pop(close, period);

    let mut upper = vec![f64::NAN; n];
    let mut lower = vec![f64::NAN; n];

    for i in 0..n {
        if !middle[i].is_nan() {
            upper[i] = middle[i] + num_std_up * std[i];
            lower[i] = middle[i] - num_std_dn * std[i];
        }
    }

    (upper, middle, lower)
}

/// Explicit Bollinger Bands alias with the canonical public name.
pub fn bollinger(
    close: &[f64],
    period: usize,
    num_std_up: f64,
    num_std_dn: f64,
) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
    bbands(close, period, num_std_up, num_std_dn)
}

/// Average True Range (Wilder's smoothing of True Range).
///
/// Matches TA-Lib `ta_ATR.c` behavior:
/// - True Range = max(H-L, |H-C_prev|, |L-C_prev|).
/// - First ATR value = simple average of first `period` True Range values.
/// - Subsequent values use Wilder's smoothing (alpha = 1/period).
///
/// # Arguments
///
/// * `high` — High prices.
/// * `low` — Low prices.
/// * `close` — Closing prices.
/// * `period` — Lookback period (typically 14).
pub fn wilder_atr(high: &[f64], low: &[f64], close: &[f64], period: usize) -> Vec<f64> {
    let n = high.len();
    if n != low.len() || n != close.len() {
        return vec![f64::NAN; n];
    }
    if n <= period || period == 0 {
        return vec![f64::NAN; n];
    }

    // Compute True Range series
    let mut tr = vec![0.0_f64; n];
    tr[0] = high[0] - low[0]; // First bar: just H-L (no previous close)
    for i in 1..n {
        let hl = high[i] - low[i];
        let hc = (high[i] - close[i - 1]).abs();
        let lc = (low[i] - close[i - 1]).abs();
        tr[i] = hl.max(hc).max(lc);
    }

    // Apply Wilder's smoothing to True Range (starting from index 1)
    // ATR lookback is `period` bars of True Range (from index 1 onward)
    let mut out = vec![f64::NAN; n];

    // Seed: simple average of first `period` True Range values (starting from index 1)
    let seed: f64 = tr[1..=period].iter().sum::<f64>() / period as f64;
    out[period] = seed;

    // Wilder's recursive smoothing
    for i in (period + 1)..n {
        out[i] = (out[i - 1] * (period as f64 - 1.0) + tr[i]) / period as f64;
    }

    out
}

/// Backward-compatible alias for Wilder ATR.
pub fn atr(high: &[f64], low: &[f64], close: &[f64], period: usize) -> Vec<f64> {
    wilder_atr(high, low, close, period)
}

/// Raw stochastic %K: `(close - LL) / (HH - LL) * 100` over `period`.
fn stoch_raw_k(close: f64, high_window: &[f64], low_window: &[f64]) -> f64 {
    let hh = high_window
        .iter()
        .copied()
        .fold(f64::NEG_INFINITY, f64::max);
    let ll = low_window.iter().copied().fold(f64::INFINITY, f64::min);
    let denom = hh - ll;
    if denom == 0.0 {
        50.0
    } else {
        (close - ll) / denom * 100.0
    }
}

/// Stochastic oscillator (slow %K and %D).
///
/// Matches TA-Lib `STOCH` with SMA smoothing (`matype=0`). Both outputs
/// are exposed only once `%D` is warm: lookback =
/// `(fastk + slowk + slowd) - 3` leading NaNs.
pub fn stoch(
    high: &[f64],
    low: &[f64],
    close: &[f64],
    fastk_period: usize,
    slowk_period: usize,
    slowd_period: usize,
) -> (Vec<f64>, Vec<f64>) {
    let n = close.len();
    let nan_pair = || (vec![f64::NAN; n], vec![f64::NAN; n]);
    if n == 0 || fastk_period == 0 || slowk_period == 0 || slowd_period == 0 || n < fastk_period {
        return nan_pair();
    }

    let mut raw_k = vec![f64::NAN; n];
    for i in (fastk_period - 1)..n {
        let hw = &high[i + 1 - fastk_period..=i];
        let lw = &low[i + 1 - fastk_period..=i];
        raw_k[i] = stoch_raw_k(close[i], hw, lw);
    }

    let mut slow_k = vec![f64::NAN; n];
    let k_smooth_start = fastk_period - 1 + slowk_period - 1;
    for i in k_smooth_start..n {
        let w = &raw_k[i + 1 - slowk_period..=i];
        slow_k[i] = w.iter().sum::<f64>() / slowk_period as f64;
    }

    let mut slow_d = vec![f64::NAN; n];
    let d_start = k_smooth_start + slowd_period - 1;
    for i in d_start..n {
        let w = &slow_k[i + 1 - slowd_period..=i];
        slow_d[i] = w.iter().sum::<f64>() / slowd_period as f64;
    }

    let output_first = fastk_period - 1 + slowk_period - 1 + slowd_period - 1;
    let mut out_k = vec![f64::NAN; n];
    let mut out_d = vec![f64::NAN; n];
    out_k[output_first..n].copy_from_slice(&slow_k[output_first..n]);
    out_d[output_first..n].copy_from_slice(&slow_d[output_first..n]);
    (out_k, out_d)
}

/// Fast stochastic oscillator (%K and %D).
///
/// Matches TA-Lib `STOCHF` with SMA `%D`. Outputs align once `%D` is warm.
pub fn stochf(
    high: &[f64],
    low: &[f64],
    close: &[f64],
    fastk_period: usize,
    fastd_period: usize,
) -> (Vec<f64>, Vec<f64>) {
    let n = close.len();
    let nan_pair = || (vec![f64::NAN; n], vec![f64::NAN; n]);
    if n == 0 || fastk_period == 0 || fastd_period == 0 || n < fastk_period {
        return nan_pair();
    }

    let mut raw_k = vec![f64::NAN; n];
    for i in (fastk_period - 1)..n {
        let hw = &high[i + 1 - fastk_period..=i];
        let lw = &low[i + 1 - fastk_period..=i];
        raw_k[i] = stoch_raw_k(close[i], hw, lw);
    }

    let mut fast_d = vec![f64::NAN; n];
    let d_start = fastk_period - 1 + fastd_period - 1;
    for i in d_start..n {
        let w = &raw_k[i + 1 - fastd_period..=i];
        fast_d[i] = w.iter().sum::<f64>() / fastd_period as f64;
    }

    let output_first = d_start;
    let mut out_k = vec![f64::NAN; n];
    let mut out_d = vec![f64::NAN; n];
    out_k[output_first..n].copy_from_slice(&raw_k[output_first..n]);
    out_d[output_first..n].copy_from_slice(&fast_d[output_first..n]);
    (out_k, out_d)
}

/// Stochastic RSI (%K and %D of RSI).
///
/// Matches TA-Lib `STOCHRSI` with SMA `%D`.
pub fn stochrsi(
    close: &[f64],
    timeperiod: usize,
    fastk_period: usize,
    fastd_period: usize,
) -> (Vec<f64>, Vec<f64>) {
    let rsi_series = rsi(close, timeperiod);
    // TA-Lib RSI(period) first finite value is at index `period`.
    stoch_on_series(&rsi_series, timeperiod, fastk_period, fastd_period)
}

/// One-period directional movement (+DM1, -DM1) per TA-Lib rules.
fn dm1(prev_high: f64, prev_low: f64, high: f64, low: f64) -> (f64, f64) {
    let diff_p = high - prev_high;
    let diff_m = prev_low - low;
    let plus = if diff_p > 0.0 && diff_p > diff_m {
        diff_p
    } else {
        0.0
    };
    let minus = if diff_m > 0.0 && diff_p < diff_m {
        diff_m
    } else {
        0.0
    };
    (plus, minus)
}

/// True range for one bar (H-L, |H-C_prev|, |L-C_prev|).
fn tr1(high: f64, low: f64, prev_close: f64) -> f64 {
    let hl = high - low;
    let hc = (high - prev_close).abs();
    let lc = (low - prev_close).abs();
    hl.max(hc).max(lc)
}

/// Directional index from smoothed +DI and -DI.
fn dx_from_di(plus_di: f64, minus_di: f64) -> f64 {
    let sum = plus_di + minus_di;
    if sum == 0.0 {
        0.0
    } else {
        100.0 * (plus_di - minus_di).abs() / sum
    }
}

/// Plus Directional Indicator (Wilder DM + TR smoothing).
///
/// Matches TA-Lib `PLUS_DI`. First finite value at index `period`.
pub fn plus_di(high: &[f64], low: &[f64], close: &[f64], period: usize) -> Vec<f64> {
    let n = high.len();
    let mut out = vec![f64::NAN; n];
    if n == 0 || period == 0 || high.len() != low.len() || high.len() != close.len() || n <= period
    {
        return out;
    }

    let mut today = 0usize;
    let mut prev_high = high[today];
    let mut prev_low = low[today];
    let mut prev_close = close[today];
    let mut prev_plus_dm = 0.0_f64;
    let mut prev_tr = 0.0_f64;

    for _ in 0..(period - 1) {
        today += 1;
        let (plus_dm, _) = dm1(prev_high, prev_low, high[today], low[today]);
        prev_high = high[today];
        prev_low = low[today];
        prev_plus_dm += plus_dm;
        prev_tr += tr1(prev_high, prev_low, prev_close);
        prev_close = close[today];
    }

    today += 1;
    let (plus_dm, _) = dm1(prev_high, prev_low, high[today], low[today]);
    prev_high = high[today];
    prev_low = low[today];
    prev_plus_dm -= prev_plus_dm / period as f64;
    prev_plus_dm += plus_dm;
    let tr = tr1(prev_high, prev_low, prev_close);
    prev_tr = prev_tr - prev_tr / period as f64 + tr;
    prev_close = close[today];
    out[today] = if prev_tr == 0.0 {
        0.0
    } else {
        100.0 * prev_plus_dm / prev_tr
    };

    while today + 1 < n {
        today += 1;
        let (plus_dm, _) = dm1(prev_high, prev_low, high[today], low[today]);
        prev_high = high[today];
        prev_low = low[today];
        prev_plus_dm -= prev_plus_dm / period as f64;
        prev_plus_dm += plus_dm;
        let tr = tr1(prev_high, prev_low, prev_close);
        prev_tr = prev_tr - prev_tr / period as f64 + tr;
        prev_close = close[today];
        out[today] = if prev_tr == 0.0 {
            0.0
        } else {
            100.0 * prev_plus_dm / prev_tr
        };
    }

    out
}

/// Minus Directional Indicator (Wilder DM + TR smoothing).
///
/// Matches TA-Lib `MINUS_DI`. First finite value at index `period`.
pub fn minus_di(high: &[f64], low: &[f64], close: &[f64], period: usize) -> Vec<f64> {
    let n = high.len();
    let mut out = vec![f64::NAN; n];
    if n == 0 || period == 0 || high.len() != low.len() || high.len() != close.len() || n <= period
    {
        return out;
    }

    let mut today = 0usize;
    let mut prev_high = high[today];
    let mut prev_low = low[today];
    let mut prev_close = close[today];
    let mut prev_minus_dm = 0.0_f64;
    let mut prev_tr = 0.0_f64;

    for _ in 0..(period - 1) {
        today += 1;
        let (_, minus_dm) = dm1(prev_high, prev_low, high[today], low[today]);
        prev_high = high[today];
        prev_low = low[today];
        prev_minus_dm += minus_dm;
        prev_tr += tr1(prev_high, prev_low, prev_close);
        prev_close = close[today];
    }

    today += 1;
    let (_, minus_dm) = dm1(prev_high, prev_low, high[today], low[today]);
    prev_high = high[today];
    prev_low = low[today];
    prev_minus_dm -= prev_minus_dm / period as f64;
    prev_minus_dm += minus_dm;
    let tr = tr1(prev_high, prev_low, prev_close);
    prev_tr = prev_tr - prev_tr / period as f64 + tr;
    prev_close = close[today];
    out[today] = if prev_tr == 0.0 {
        0.0
    } else {
        100.0 * prev_minus_dm / prev_tr
    };

    while today + 1 < n {
        today += 1;
        let (_, minus_dm) = dm1(prev_high, prev_low, high[today], low[today]);
        prev_high = high[today];
        prev_low = low[today];
        prev_minus_dm -= prev_minus_dm / period as f64;
        prev_minus_dm += minus_dm;
        let tr = tr1(prev_high, prev_low, prev_close);
        prev_tr = prev_tr - prev_tr / period as f64 + tr;
        prev_close = close[today];
        out[today] = if prev_tr == 0.0 {
            0.0
        } else {
            100.0 * prev_minus_dm / prev_tr
        };
    }

    out
}

/// Directional Movement Index.
///
/// Matches TA-Lib `DX`. First finite value at index `period`.
pub fn dx(high: &[f64], low: &[f64], close: &[f64], period: usize) -> Vec<f64> {
    let n = high.len();
    let mut out = vec![f64::NAN; n];
    if n == 0 || period == 0 || high.len() != low.len() || high.len() != close.len() || n <= period
    {
        return out;
    }

    let mut today = 0usize;
    let mut prev_high = high[today];
    let mut prev_low = low[today];
    let mut prev_close = close[today];
    let mut prev_plus_dm = 0.0_f64;
    let mut prev_minus_dm = 0.0_f64;
    let mut prev_tr = 0.0_f64;

    for _ in 0..(period - 1) {
        today += 1;
        let (plus_dm, minus_dm) = dm1(prev_high, prev_low, high[today], low[today]);
        prev_high = high[today];
        prev_low = low[today];
        prev_plus_dm += plus_dm;
        prev_minus_dm += minus_dm;
        prev_tr += tr1(prev_high, prev_low, prev_close);
        prev_close = close[today];
    }

    today += 1;
    let (plus_dm, minus_dm) = dm1(prev_high, prev_low, high[today], low[today]);
    prev_high = high[today];
    prev_low = low[today];
    prev_plus_dm -= prev_plus_dm / period as f64;
    prev_plus_dm += plus_dm;
    prev_minus_dm -= prev_minus_dm / period as f64;
    prev_minus_dm += minus_dm;
    let tr = tr1(prev_high, prev_low, prev_close);
    prev_tr = prev_tr - prev_tr / period as f64 + tr;
    prev_close = close[today];
    if prev_tr != 0.0 {
        let plus_di = 100.0 * prev_plus_dm / prev_tr;
        let minus_di = 100.0 * prev_minus_dm / prev_tr;
        out[today] = dx_from_di(plus_di, minus_di);
    } else {
        out[today] = 0.0;
    }

    while today + 1 < n {
        today += 1;
        let (plus_dm, minus_dm) = dm1(prev_high, prev_low, high[today], low[today]);
        prev_high = high[today];
        prev_low = low[today];
        prev_plus_dm -= prev_plus_dm / period as f64;
        prev_plus_dm += plus_dm;
        prev_minus_dm -= prev_minus_dm / period as f64;
        prev_minus_dm += minus_dm;
        let tr = tr1(prev_high, prev_low, prev_close);
        prev_tr = prev_tr - prev_tr / period as f64 + tr;
        prev_close = close[today];
        if prev_tr != 0.0 {
            let plus_di = 100.0 * prev_plus_dm / prev_tr;
            let minus_di = 100.0 * prev_minus_dm / prev_tr;
            out[today] = dx_from_di(plus_di, minus_di);
        } else {
            out[today] = 0.0;
        }
    }

    out
}

/// Average Directional Movement Index.
///
/// Matches TA-Lib `ADX`. First finite value at index `2 * period - 1`.
pub fn adx(high: &[f64], low: &[f64], close: &[f64], period: usize) -> Vec<f64> {
    let n = high.len();
    let mut out = vec![f64::NAN; n];
    if n == 0
        || period < 2
        || high.len() != low.len()
        || high.len() != close.len()
        || n < 2 * period
    {
        return out;
    }

    let lookback = 2 * period - 1;
    let mut today = 0usize;
    let mut prev_high = high[today];
    let mut prev_low = low[today];
    let mut prev_close = close[today];
    let mut prev_plus_dm = 0.0_f64;
    let mut prev_minus_dm = 0.0_f64;
    let mut prev_tr = 0.0_f64;

    for _ in 0..(period - 1) {
        today += 1;
        let (plus_dm, minus_dm) = dm1(prev_high, prev_low, high[today], low[today]);
        prev_high = high[today];
        prev_low = low[today];
        prev_plus_dm += plus_dm;
        prev_minus_dm += minus_dm;
        prev_tr += tr1(prev_high, prev_low, prev_close);
        prev_close = close[today];
    }

    let mut sum_dx = 0.0_f64;
    for _ in 0..period {
        today += 1;
        let (plus_dm, minus_dm) = dm1(prev_high, prev_low, high[today], low[today]);
        prev_high = high[today];
        prev_low = low[today];
        prev_minus_dm -= prev_minus_dm / period as f64;
        prev_minus_dm += minus_dm;
        prev_plus_dm -= prev_plus_dm / period as f64;
        prev_plus_dm += plus_dm;
        let tr = tr1(prev_high, prev_low, prev_close);
        prev_tr = prev_tr - prev_tr / period as f64 + tr;
        prev_close = close[today];
        if prev_tr != 0.0 {
            let plus_di = 100.0 * prev_plus_dm / prev_tr;
            let minus_di = 100.0 * prev_minus_dm / prev_tr;
            sum_dx += dx_from_di(plus_di, minus_di);
        }
    }

    let mut prev_adx = sum_dx / period as f64;
    out[today] = prev_adx;

    while today + 1 < n {
        today += 1;
        let (plus_dm, minus_dm) = dm1(prev_high, prev_low, high[today], low[today]);
        prev_high = high[today];
        prev_low = low[today];
        prev_minus_dm -= prev_minus_dm / period as f64;
        prev_minus_dm += minus_dm;
        prev_plus_dm -= prev_plus_dm / period as f64;
        prev_plus_dm += plus_dm;
        let tr = tr1(prev_high, prev_low, prev_close);
        prev_tr = prev_tr - prev_tr / period as f64 + tr;
        prev_close = close[today];
        if prev_tr != 0.0 {
            let plus_di = 100.0 * prev_plus_dm / prev_tr;
            let minus_di = 100.0 * prev_minus_dm / prev_tr;
            let dx = dx_from_di(plus_di, minus_di);
            prev_adx = (prev_adx * (period as f64 - 1.0) + dx) / period as f64;
        }
        out[today] = prev_adx;
    }

    // TA-Lib lookback is 2*period-1; ensure leading NaNs through lookback-1.
    for v in out.iter_mut().take(lookback) {
        *v = f64::NAN;
    }

    out
}

/// Typical price for CCI / ULTOSC.
fn typical_price(high: f64, low: f64, close: f64) -> f64 {
    (high + low + close) / 3.0
}

/// Commodity Channel Index.
///
/// Matches TA-Lib `CCI`. First finite value at index `period - 1`.
pub fn cci(high: &[f64], low: &[f64], close: &[f64], period: usize) -> Vec<f64> {
    let n = close.len();
    let mut out = vec![f64::NAN; n];
    if n < period || period < 2 || high.len() != low.len() || high.len() != close.len() {
        return out;
    }

    for (i, out_i) in out.iter_mut().enumerate().skip(period - 1) {
        let start = i + 1 - period;
        let mut sum = 0.0_f64;
        let mut tp_vals = Vec::with_capacity(period);
        for j in start..=i {
            let tp = typical_price(high[j], low[j], close[j]);
            tp_vals.push(tp);
            sum += tp;
        }
        let avg = sum / period as f64;
        let last_tp = tp_vals[period - 1];
        let mean_dev: f64 = tp_vals.iter().map(|v| (v - avg).abs()).sum();
        let diff = last_tp - avg;
        *out_i = if diff != 0.0 && mean_dev != 0.0 {
            diff / (0.015 * (mean_dev / period as f64))
        } else {
            0.0
        };
    }

    out
}

/// Williams' %R.
///
/// Matches TA-Lib `WILLR`. First finite value at index `period - 1`.
pub fn willr(high: &[f64], low: &[f64], close: &[f64], period: usize) -> Vec<f64> {
    let n = close.len();
    let mut out = vec![f64::NAN; n];
    if n < period || period < 2 || high.len() != low.len() || high.len() != close.len() {
        return out;
    }

    for i in (period - 1)..n {
        let start = i + 1 - period;
        let highest = high[start..=i]
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max);
        let lowest = low[start..=i].iter().copied().fold(f64::INFINITY, f64::min);
        let denom = highest - lowest;
        out[i] = if denom == 0.0 {
            0.0
        } else {
            -100.0 * (highest - close[i]) / denom
        };
    }

    out
}

/// Ultimate Oscillator terms for one bar.
fn ultosc_terms(high: f64, low: f64, close: f64, prev_close: f64) -> (f64, f64) {
    let true_low = low.min(prev_close);
    let close_minus_true_low = close - true_low;
    let mut true_range = high - low;
    let hc = (prev_close - high).abs();
    if hc > true_range {
        true_range = hc;
    }
    let lc = (prev_close - low).abs();
    if lc > true_range {
        true_range = lc;
    }
    (close_minus_true_low, true_range)
}

/// Ultimate Oscillator.
///
/// Matches TA-Lib `ULTOSC` with default periods 7/14/28. First finite
/// value at index `max(period1, period2, period3)`.
pub fn ultosc(
    high: &[f64],
    low: &[f64],
    close: &[f64],
    period1: usize,
    period2: usize,
    period3: usize,
) -> Vec<f64> {
    let n = close.len();
    let mut out = vec![f64::NAN; n];
    if n == 0 || period1 == 0 || period2 == 0 || period3 == 0 {
        return out;
    }
    if high.len() != low.len() || high.len() != close.len() {
        return out;
    }

    let mut periods = [period1, period2, period3];
    periods.sort_unstable();
    let p_short = periods[0];
    let p_mid = periods[1];
    let p_long = periods[2];
    let lookback = p_long;
    if n <= lookback {
        return out;
    }

    let mut a1 = 0.0_f64;
    let mut b1 = 0.0_f64;
    let mut a2 = 0.0_f64;
    let mut b2 = 0.0_f64;
    let mut a3 = 0.0_f64;
    let mut b3 = 0.0_f64;

    let start = lookback;
    for i in (start - p_long + 1)..start {
        let (bp, tr) = ultosc_terms(high[i], low[i], close[i], close[i - 1]);
        a3 += bp;
        b3 += tr;
        if i > start - p_mid {
            a2 += bp;
            b2 += tr;
        }
        if i > start - p_short {
            a1 += bp;
            b1 += tr;
        }
    }

    for today in start..n {
        let trailing1 = today + 1 - p_short;
        let trailing2 = today + 1 - p_mid;
        let trailing3 = today + 1 - p_long;
        let (bp, tr) = ultosc_terms(high[today], low[today], close[today], close[today - 1]);
        a1 += bp;
        a2 += bp;
        a3 += bp;
        b1 += tr;
        b2 += tr;
        b3 += tr;

        let mut output = 0.0_f64;
        if b1 != 0.0 {
            output += 4.0 * (a1 / b1);
        }
        if b2 != 0.0 {
            output += 2.0 * (a2 / b2);
        }
        if b3 != 0.0 {
            output += a3 / b3;
        }
        out[today] = 100.0 * (output / 7.0);

        let (bp1, tr1) = ultosc_terms(
            high[trailing1],
            low[trailing1],
            close[trailing1],
            close[trailing1 - 1],
        );
        a1 -= bp1;
        b1 -= tr1;
        let (bp2, tr2) = ultosc_terms(
            high[trailing2],
            low[trailing2],
            close[trailing2],
            close[trailing2 - 1],
        );
        a2 -= bp2;
        b2 -= tr2;
        let (bp3, tr3) = ultosc_terms(
            high[trailing3],
            low[trailing3],
            close[trailing3],
            close[trailing3 - 1],
        );
        a3 -= bp3;
        b3 -= tr3;
    }

    out
}

/// Momentum: `close - close[period]`.
///
/// Matches TA-Lib `MOM`. First finite value at index `period`.
pub fn mom(close: &[f64], period: usize) -> Vec<f64> {
    let n = close.len();
    let mut out = vec![f64::NAN; n];
    if n <= period || period == 0 {
        return out;
    }
    for i in period..n {
        out[i] = close[i] - close[i - period];
    }
    out
}

/// Rate of change (percent): `100 * (close - close[period]) / close[period]`.
///
/// Matches TA-Lib `ROC`.
pub fn roc(close: &[f64], period: usize) -> Vec<f64> {
    let n = close.len();
    let mut out = vec![f64::NAN; n];
    if n <= period || period == 0 {
        return out;
    }
    for i in period..n {
        let prev = close[i - period];
        out[i] = if prev == 0.0 {
            0.0
        } else {
            100.0 * (close[i] - prev) / prev
        };
    }
    out
}

/// Rate of change (ratio): `(close - close[period]) / close[period]`.
///
/// Matches TA-Lib `ROCP`.
pub fn rocp(close: &[f64], period: usize) -> Vec<f64> {
    let n = close.len();
    let mut out = vec![f64::NAN; n];
    if n <= period || period == 0 {
        return out;
    }
    for i in period..n {
        let prev = close[i - period];
        out[i] = if prev == 0.0 {
            0.0
        } else {
            (close[i] - prev) / prev
        };
    }
    out
}

/// Rate of change ratio: `close / close[period]`.
///
/// Matches TA-Lib `ROCR`.
pub fn rocr(close: &[f64], period: usize) -> Vec<f64> {
    let n = close.len();
    let mut out = vec![f64::NAN; n];
    if n <= period || period == 0 {
        return out;
    }
    for i in period..n {
        let prev = close[i - period];
        out[i] = if prev == 0.0 { 0.0 } else { close[i] / prev };
    }
    out
}

/// Chaikin money-flow contribution for one bar.
fn ad_money_flow(high: f64, low: f64, close: f64, volume: f64) -> f64 {
    let hl = high - low;
    if hl > 0.0 {
        (((close - low) - (high - close)) / hl) * volume
    } else {
        0.0
    }
}

/// On Balance Volume.
///
/// Matches TA-Lib `OBV`: seeds with `volume[0]`, then adds/subtracts volume on
/// close up/down moves.
pub fn obv(close: &[f64], volume: &[f64]) -> Vec<f64> {
    let n = close.len();
    if n == 0 || volume.len() != n {
        return Vec::new();
    }

    let mut out = vec![0.0; n];
    let mut prev_obv = volume[0];
    let mut prev_close = close[0];
    out[0] = prev_obv;

    for i in 1..n {
        if close[i] > prev_close {
            prev_obv += volume[i];
        } else if close[i] < prev_close {
            prev_obv -= volume[i];
        }
        out[i] = prev_obv;
        prev_close = close[i];
    }
    out
}

/// Chaikin Accumulation/Distribution Line.
///
/// Matches TA-Lib `AD`.
pub fn ad(high: &[f64], low: &[f64], close: &[f64], volume: &[f64]) -> Vec<f64> {
    let n = close.len();
    if n == 0 || high.len() != n || low.len() != n || volume.len() != n {
        return Vec::new();
    }

    let mut out = vec![0.0; n];
    let mut cum = 0.0;
    for i in 0..n {
        cum += ad_money_flow(high[i], low[i], close[i], volume[i]);
        out[i] = cum;
    }
    out
}

/// Chaikin A/D Oscillator: `EMA(fast, AD) - EMA(slow, AD)`.
///
/// Matches TA-Lib `ADOSC` (EMA applied to the cumulative AD series).
pub fn adosc(
    high: &[f64],
    low: &[f64],
    close: &[f64],
    volume: &[f64],
    fast_period: usize,
    slow_period: usize,
) -> Vec<f64> {
    let n = close.len();
    let mut out = vec![f64::NAN; n];
    if n == 0
        || high.len() != n
        || low.len() != n
        || volume.len() != n
        || fast_period < 2
        || slow_period < 2
    {
        return out;
    }

    let slowest = fast_period.max(slow_period);
    let lookback = slowest - 1;
    if n <= lookback {
        return out;
    }

    let fast_k = 2.0 / (fast_period as f64 + 1.0);
    let one_minus_fast_k = 1.0 - fast_k;
    let slow_k = 2.0 / (slow_period as f64 + 1.0);
    let one_minus_slow_k = 1.0 - slow_k;

    let start_idx = lookback;
    let mut today = 0usize;
    let mut ad_cum = 0.0_f64;

    ad_cum += ad_money_flow(high[today], low[today], close[today], volume[today]);
    today += 1;
    let mut fast_ema = ad_cum;
    let mut slow_ema = ad_cum;

    while today < start_idx {
        ad_cum += ad_money_flow(high[today], low[today], close[today], volume[today]);
        today += 1;
        fast_ema = fast_k * ad_cum + one_minus_fast_k * fast_ema;
        slow_ema = slow_k * ad_cum + one_minus_slow_k * slow_ema;
    }

    let mut out_idx = start_idx;
    while today < n {
        ad_cum += ad_money_flow(high[today], low[today], close[today], volume[today]);
        today += 1;
        fast_ema = fast_k * ad_cum + one_minus_fast_k * fast_ema;
        slow_ema = slow_k * ad_cum + one_minus_slow_k * slow_ema;
        out[out_idx] = fast_ema - slow_ema;
        out_idx += 1;
    }

    out
}

/// True Range (unsmoothed).
///
/// Matches TA-Lib `TRANGE`: index 0 is NaN; valid from index 1.
pub fn trange(high: &[f64], low: &[f64], close: &[f64]) -> Vec<f64> {
    let n = high.len();
    let mut out = vec![f64::NAN; n];
    if n == 0 || low.len() != n || close.len() != n {
        return out;
    }
    if n < 2 {
        return out;
    }

    for i in 1..n {
        let hl = high[i] - low[i];
        let hc = (high[i] - close[i - 1]).abs();
        let lc = (low[i] - close[i - 1]).abs();
        out[i] = hl.max(hc).max(lc);
    }
    out
}

/// Wilder-smoothed ATR from a precomputed TRANGE series.
fn wilder_atr_from_trange(tr: &[f64], period: usize) -> Vec<f64> {
    let n = tr.len();
    let mut out = vec![f64::NAN; n];
    if n <= period || period == 0 {
        return out;
    }

    let seed: f64 = tr[1..=period].iter().sum::<f64>() / period as f64;
    out[period] = seed;

    for i in (period + 1)..n {
        out[i] = (out[i - 1] * (period as f64 - 1.0) + tr[i]) / period as f64;
    }
    out
}

/// Normalized Average True Range: `ATR / close * 100`.
///
/// Matches TA-Lib `NATR`.
pub fn natr(high: &[f64], low: &[f64], close: &[f64], period: usize) -> Vec<f64> {
    let n = high.len();
    let mut out = vec![f64::NAN; n];
    if n == 0 || low.len() != n || close.len() != n || period == 0 {
        return out;
    }

    let tr = trange(high, low, close);
    let atr = wilder_atr_from_trange(&tr, period);

    for i in 0..n {
        if !atr[i].is_nan() {
            out[i] = if close[i] == 0.0 {
                0.0
            } else {
                atr[i] / close[i] * 100.0
            };
        }
    }
    out
}

/// Apply fast stochastic smoothing to an existing series (used by STOCHRSI).
fn stoch_on_series(
    series: &[f64],
    series_first: usize,
    fastk_period: usize,
    fastd_period: usize,
) -> (Vec<f64>, Vec<f64>) {
    let n = series.len();
    let nan_pair = || (vec![f64::NAN; n], vec![f64::NAN; n]);
    if n == 0 || fastk_period == 0 || fastd_period == 0 {
        return nan_pair();
    }

    let mut raw_k = vec![f64::NAN; n];
    let raw_start = series_first + fastk_period - 1;
    for i in raw_start..n {
        let w = &series[i + 1 - fastk_period..=i];
        if w.iter().any(|v| v.is_nan()) {
            continue;
        }
        let hh = w.iter().copied().fold(f64::NEG_INFINITY, f64::max);
        let ll = w.iter().copied().fold(f64::INFINITY, f64::min);
        let denom = hh - ll;
        raw_k[i] = if denom == 0.0 {
            50.0
        } else {
            (series[i] - ll) / denom * 100.0
        };
    }

    let mut fast_d = vec![f64::NAN; n];
    let d_start = raw_start + fastd_period - 1;
    for i in d_start..n {
        let w = &raw_k[i + 1 - fastd_period..=i];
        if w.iter().any(|v| v.is_nan()) {
            continue;
        }
        fast_d[i] = w.iter().sum::<f64>() / fastd_period as f64;
    }

    let output_first = series_first + fastk_period - 1 + fastd_period - 1;
    let mut out_k = vec![f64::NAN; n];
    let mut out_d = vec![f64::NAN; n];
    out_k[output_first..n].copy_from_slice(&raw_k[output_first..n]);
    out_d[output_first..n].copy_from_slice(&fast_d[output_first..n]);
    (out_k, out_d)
}

// ---------------------------------------------------------------------------
// Discoverability (mirrors tests/parity/indicator_registry.json)
// ---------------------------------------------------------------------------

/// Metadata for a supported technical indicator.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndicatorMeta {
    pub name: &'static str,
    pub category: &'static str,
    pub input_type: &'static str,
    pub rust_fn: &'static str,
    pub has_parity: bool,
}

/// Return every indicator with golden parity coverage (Group A today).
pub fn list_supported() -> &'static [IndicatorMeta] {
    const SUPPORTED: &[IndicatorMeta] = &[
        IndicatorMeta {
            name: "sma",
            category: "overlap",
            input_type: "close",
            rust_fn: "sma",
            has_parity: true,
        },
        IndicatorMeta {
            name: "ema",
            category: "overlap",
            input_type: "close",
            rust_fn: "ema",
            has_parity: true,
        },
        IndicatorMeta {
            name: "rsi",
            category: "momentum",
            input_type: "close",
            rust_fn: "rsi",
            has_parity: true,
        },
        IndicatorMeta {
            name: "macd",
            category: "momentum",
            input_type: "close",
            rust_fn: "macd",
            has_parity: true,
        },
        IndicatorMeta {
            name: "bbands",
            category: "overlap",
            input_type: "close",
            rust_fn: "bbands",
            has_parity: true,
        },
        IndicatorMeta {
            name: "atr",
            category: "volatility",
            input_type: "ohlc",
            rust_fn: "atr",
            has_parity: true,
        },
        IndicatorMeta {
            name: "stoch",
            category: "momentum",
            input_type: "ohlc",
            rust_fn: "stoch",
            has_parity: true,
        },
        IndicatorMeta {
            name: "stochf",
            category: "momentum",
            input_type: "ohlc",
            rust_fn: "stochf",
            has_parity: true,
        },
        IndicatorMeta {
            name: "stochrsi",
            category: "momentum",
            input_type: "close",
            rust_fn: "stochrsi",
            has_parity: true,
        },
        IndicatorMeta {
            name: "adx",
            category: "momentum",
            input_type: "ohlc",
            rust_fn: "adx",
            has_parity: true,
        },
        IndicatorMeta {
            name: "plus_di",
            category: "momentum",
            input_type: "ohlc",
            rust_fn: "plus_di",
            has_parity: true,
        },
        IndicatorMeta {
            name: "minus_di",
            category: "momentum",
            input_type: "ohlc",
            rust_fn: "minus_di",
            has_parity: true,
        },
        IndicatorMeta {
            name: "dx",
            category: "momentum",
            input_type: "ohlc",
            rust_fn: "dx",
            has_parity: true,
        },
        IndicatorMeta {
            name: "cci",
            category: "momentum",
            input_type: "ohlc",
            rust_fn: "cci",
            has_parity: true,
        },
        IndicatorMeta {
            name: "willr",
            category: "momentum",
            input_type: "ohlc",
            rust_fn: "willr",
            has_parity: true,
        },
        IndicatorMeta {
            name: "ultosc",
            category: "momentum",
            input_type: "ohlc",
            rust_fn: "ultosc",
            has_parity: true,
        },
        IndicatorMeta {
            name: "mom",
            category: "momentum",
            input_type: "close",
            rust_fn: "mom",
            has_parity: true,
        },
        IndicatorMeta {
            name: "roc",
            category: "momentum",
            input_type: "close",
            rust_fn: "roc",
            has_parity: true,
        },
        IndicatorMeta {
            name: "rocp",
            category: "momentum",
            input_type: "close",
            rust_fn: "rocp",
            has_parity: true,
        },
        IndicatorMeta {
            name: "rocr",
            category: "momentum",
            input_type: "close",
            rust_fn: "rocr",
            has_parity: true,
        },
        IndicatorMeta {
            name: "obv",
            category: "volume",
            input_type: "close_volume",
            rust_fn: "obv",
            has_parity: true,
        },
        IndicatorMeta {
            name: "ad",
            category: "volume",
            input_type: "ohlcv",
            rust_fn: "ad",
            has_parity: true,
        },
        IndicatorMeta {
            name: "adosc",
            category: "volume",
            input_type: "ohlcv",
            rust_fn: "adosc",
            has_parity: true,
        },
        IndicatorMeta {
            name: "natr",
            category: "volatility",
            input_type: "ohlc",
            rust_fn: "natr",
            has_parity: true,
        },
        IndicatorMeta {
            name: "trange",
            category: "volatility",
            input_type: "ohlc",
            rust_fn: "trange",
            has_parity: true,
        },
    ];
    SUPPORTED
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn sma_basic() {
        let result = sma(&[1.0, 2.0, 3.0, 4.0], 2);
        assert!(result[0].is_nan());
        assert_eq!(result[1], 1.5);
        assert_eq!(result[2], 2.5);
        assert_eq!(result[3], 3.5);
    }

    #[test]
    fn ema_basic() {
        let result = ema(&[1.0, 2.0, 3.0, 4.0], 2);
        assert!(result[0].is_nan());
        assert_eq!(result[1], 1.5);
        assert!((result[2] - 2.5).abs() < 1e-12);
        assert!((result[3] - 3.5).abs() < 1e-12);
    }

    #[test]
    fn bollinger_alias_matches_bbands() {
        let close = [1.0, 2.0, 3.0, 4.0, 5.0];
        let bb = bbands(&close, 3, 2.0, 2.0);
        let alias = bollinger(&close, 3, 2.0, 2.0);
        for (left, right) in [(&bb.0, &alias.0), (&bb.1, &alias.1), (&bb.2, &alias.2)] {
            for (a, b) in left.iter().zip(right.iter()) {
                assert!(a == b || (a.is_nan() && b.is_nan()));
            }
        }
    }

    #[test]
    fn wilder_atr_alias_matches_atr() {
        let high = [11.0, 12.0, 13.0, 14.0];
        let low = [9.0, 10.0, 11.0, 12.0];
        let close = [10.0, 11.0, 12.0, 13.0];
        let wilder = wilder_atr(&high, &low, &close, 2);
        let alias = atr(&high, &low, &close, 2);
        for (a, b) in wilder.iter().zip(alias.iter()) {
            assert!(a == b || (a.is_nan() && b.is_nan()));
        }
    }

    #[test]
    fn rsi_monotonic_up() {
        let close: Vec<f64> = (1..=100).map(|x| x as f64).collect();
        let result = rsi(&close, 14);
        // All gains, no losses → RSI should be 100
        let last = result.last().unwrap();
        assert!((*last - 100.0).abs() < 1e-10);
    }

    #[test]
    fn rsi_monotonic_down() {
        let close: Vec<f64> = (1..=100).rev().map(|x| x as f64).collect();
        let result = rsi(&close, 14);
        // All losses, no gains → RSI should be 0
        let last = result.last().unwrap();
        assert!(last.abs() < 1e-10);
    }

    #[test]
    fn rsi_constant_price() {
        let close = vec![100.0; 50];
        let result = rsi(&close, 14);
        // Flat price: TA-Lib returns 0.0
        let last = result.last().unwrap();
        assert!(
            last.abs() < 1e-10,
            "expected 0.0 for flat price, got {last}"
        );
    }

    #[test]
    fn rsi_bounds() {
        let close = vec![
            44.0, 44.25, 44.50, 43.75, 44.50, 44.25, 43.50, 44.0, 44.50, 43.25, 43.0, 43.50, 44.0,
            44.50, 44.25, 44.0, 43.50, 43.75, 44.0, 43.25,
        ];
        let result = rsi(&close, 14);
        for (i, &v) in result.iter().enumerate() {
            if !v.is_nan() {
                assert!(
                    (0.0..=100.0).contains(&v),
                    "RSI out of bounds at index {i}: {v}"
                );
            }
        }
    }

    #[test]
    fn rsi_lookback_nan() {
        let close: Vec<f64> = (1..=30).map(|x| x as f64).collect();
        let result = rsi(&close, 14);
        // First 14 elements should be NaN (indices 0..14)
        for (i, v) in result.iter().take(14).enumerate() {
            assert!(v.is_nan(), "expected NaN at index {i}");
        }
        assert!(!result[14].is_nan(), "expected valid RSI at index 14");
    }

    #[test]
    fn macd_basic() {
        let close: Vec<f64> = (1..=50).map(|x| x as f64).collect();
        let (macd_line, signal, histogram) = macd(&close, 12, 26, 9);
        assert_eq!(macd_line.len(), 50);
        assert_eq!(signal.len(), 50);
        assert_eq!(histogram.len(), 50);
        // MACD of uptrend should be positive
        let last_macd = macd_line.last().unwrap();
        assert!(!last_macd.is_nan());
        assert!(*last_macd > 0.0);
    }

    #[test]
    fn bbands_basic() {
        let close: Vec<f64> = (1..=30).map(|x| x as f64).collect();
        let (upper, middle, lower) = bbands(&close, 20, 2.0, 2.0);
        assert_eq!(upper.len(), 30);

        // Check ordering: lower < middle < upper
        for i in 19..30 {
            assert!(
                lower[i] < middle[i] && middle[i] < upper[i],
                "band ordering violated at index {i}"
            );
        }
    }

    #[test]
    fn bbands_constant_price() {
        let close = vec![100.0; 30];
        let (upper, middle, lower) = bbands(&close, 20, 2.0, 2.0);
        // Constant price: std = 0, so upper == middle == lower
        let last = close.len() - 1;
        assert!((upper[last] - 100.0).abs() < 1e-10);
        assert!((middle[last] - 100.0).abs() < 1e-10);
        assert!((lower[last] - 100.0).abs() < 1e-10);
    }

    #[test]
    fn atr_basic() {
        // Simple case: constant range
        let high = vec![102.0; 20];
        let low = vec![98.0; 20];
        let close = vec![100.0; 20];
        let result = atr(&high, &low, &close, 14);

        // True range is always 4.0, so ATR should converge to 4.0
        let last = result.last().unwrap();
        assert!((*last - 4.0).abs() < 0.1, "expected ATR ~4.0, got {last}");
    }

    #[test]
    fn atr_lookback_nan() {
        let high = vec![102.0; 20];
        let low = vec![98.0; 20];
        let close = vec![100.0; 20];
        let result = atr(&high, &low, &close, 14);
        // First 14 elements should be NaN (indices 0..14)
        for (i, v) in result.iter().take(14).enumerate() {
            assert!(v.is_nan(), "expected NaN at index {i}");
        }
        assert!(!result[14].is_nan(), "expected valid ATR at index 14");
    }

    #[test]
    fn empty_input() {
        let empty: Vec<f64> = vec![];
        assert!(rsi(&empty, 14).is_empty());
        let (m, s, h) = macd(&empty, 12, 26, 9);
        assert!(m.is_empty() && s.is_empty() && h.is_empty());
        let (u, mid, l) = bbands(&empty, 20, 2.0, 2.0);
        assert!(u.is_empty() && mid.is_empty() && l.is_empty());
        assert!(atr(&empty, &empty, &empty, 14).is_empty());
    }

    #[test]
    fn insufficient_data() {
        let short = vec![1.0, 2.0, 3.0];
        let result = rsi(&short, 14);
        assert!(result.iter().all(|v| v.is_nan()));
    }

    #[test]
    fn obv_flat_price_unchanged() {
        let close = vec![10.0; 5];
        let volume = vec![100.0, 200.0, 300.0, 400.0, 500.0];
        let result = obv(&close, &volume);
        assert_eq!(result[0], 100.0);
        for i in 1..5 {
            assert_eq!(result[i], result[i - 1]);
        }
    }

    #[test]
    fn ad_zero_range_bar_unchanged() {
        let high = vec![10.0, 11.0];
        let low = vec![10.0, 10.0];
        let close = vec![10.0, 10.5];
        let volume = vec![1000.0, 2000.0];
        let result = ad(&high, &low, &close, &volume);
        assert_eq!(result[0], 0.0);
        assert_eq!(result[1], 0.0);
    }

    #[test]
    fn adosc_lookback_nan() {
        let high: Vec<f64> = (1..=20).map(|x| x as f64 + 1.0).collect();
        let low: Vec<f64> = (1..=20).map(|x| x as f64 - 1.0).collect();
        let close: Vec<f64> = (1..=20).map(|x| x as f64).collect();
        let volume = vec![1000.0; 20];
        let result = adosc(&high, &low, &close, &volume, 3, 10);
        for v in result.iter().take(9) {
            assert!(v.is_nan());
        }
        assert!(!result[9].is_nan());
    }

    #[test]
    fn trange_first_bar_nan() {
        let high = vec![11.0, 12.0, 13.0];
        let low = vec![9.0, 10.0, 11.0];
        let close = vec![10.0, 11.0, 12.0];
        let result = trange(&high, &low, &close);
        assert!(result[0].is_nan());
        assert!(!result[1].is_nan());
        assert!(result[1] > 0.0);
    }

    #[test]
    fn natr_positive_on_synthetic() {
        let high: Vec<f64> = (1..=30).map(|x| x as f64 + 0.5).collect();
        let low: Vec<f64> = (1..=30).map(|x| x as f64 - 0.5).collect();
        let close: Vec<f64> = (1..=30).map(|x| x as f64).collect();
        let result = natr(&high, &low, &close, 14);
        assert!(result.iter().take(14).all(|v| v.is_nan()));
        assert!(result[14] > 0.0);
    }
}