rust_ti 2.2.0

A fully configurable technical indicators library with over 70 unique indicators written in pure Rust
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
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
//! # Basic Indicators
//!
//! The `basic_indicators` module provides foundational statistical calculations for time series price data.
//! These are essential building blocks for more advanced technical indicators and can be used directly.
//!
//! ## When to Use
//! Use these functions when you need raw statistics (mean, median, mode, etc.) or want to compose your own indicators.
//!
//! ## Structure
//! - **single**: Functions that return a single value for a slice of prices.
//! - **bulk**: Functions that compute values of a slice of prices over a period and return a vector.
//!
//! ## Included Indicators
//!
//! ### Bulk
//! - [`absolute_deviation`](bulk::absolute_deviation): Mean/Median/Mode absolute deviation over each period
//! - [`cauchy_iqr_scale`](bulk::cauchy_iqr_scale): Cauchy IQR-based scale parameter over each period
//! - [`laplace_std_equivalent`](bulk::laplace_std_equivalent): Laplace standard deviation equivalent over each period
//! - [`log`](bulk::log): Natural logarithm of each price
//! - [`log_difference`](bulk::log_difference): Difference in log(price) at t and t-1
//! - [`log_standard_deviation`](bulk::log_standard_deviation): Log standard deviation over each period
//! - [`mean`](bulk::mean): Average
//! - [`median`](bulk::median): Median
//! - [`mode`](bulk::mode): Mode
//! - [`price_distribution`](bulk::price_distribution): Distribution of prices (count of each unique price) over each period
//! - [`standard_deviation`](bulk::standard_deviation): Standard deviation
//! - [`student_t_adjusted_std`](bulk::student_t_adjusted_std): Student's t-adjusted standard deviation over each period
//! - [`variance`](bulk::variance): Variance
//!
//! ### Single
//! - [`absolute_deviation`](single::absolute_deviation): Mean/Median/Mode absolute deviation
//! - [`cauchy_iqr_scale`](single::cauchy_iqr_scale): Cauchy IQR-based scale parameter
//! - [`laplace_std_equivalent`](single::laplace_std_equivalent): Laplace standard deviation equivalent
//! - [`log_difference`](single::log_difference): Log difference between two prices
//! - [`log_standard_deviation`](single::log_standard_deviation): Log standard deviation
//! - [`max`](single::max): Maximum price
//! - [`mean`](single::mean): Mean price
//! - [`median`](single::median): Median price
//! - [`min`](single::min): Minimum price
//! - [`mode`](single::mode): Mode price
//! - [`price_distribution`](single::price_distribution): Distribution of prices (count of each unique price)
//! - [`standard_deviation`](single::standard_deviation): Standard deviation
//! - [`student_t_adjusted_std`](single::student_t_adjusted_std): Student's t-adjusted standard deviation
//! - [`variance`](single::variance): Variance
//!
//! ---

/// **single**: Functions that return a single value for a slice of prices
pub mod single {
    use crate::{AbsDevConfig, CentralPoint, DeviationAggregate};
    use std::cmp::Ordering;
    use std::collections::HashMap;

    /// Calculates the mean (average) of a slice of prices
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 103.0, 101.0];
    /// let mean = rust_ti::basic_indicators::single::mean(&prices);
    /// assert_eq!(101.5, mean);
    /// ```
    #[inline]
    pub fn mean(prices: &[f64]) -> f64 {
        if prices.is_empty() {
            panic!("Prices ({:?}) is empty", prices);
        };
        prices.iter().sum::<f64>() / prices.len() as f64
    }

    /// Calculates the median (middle value) of a slice of prices.
    ///
    /// Orders numbers and takes the middle value. For even length, takes the average of two middles.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Odd number of prices
    /// let prices = vec![100.0, 102.0, 103.0, 101.0, 100.0];
    /// let median = rust_ti::basic_indicators::single::median(&prices);
    /// assert_eq!(101.0, median);
    ///
    /// // Even number of prices
    /// let prices = vec![100.0, 102.0, 103.0, 101.0];
    /// let median = rust_ti::basic_indicators::single::median(&prices);
    /// assert_eq!(101.5, median);
    /// ```
    #[inline]
    pub fn median(prices: &[f64]) -> f64 {
        if prices.is_empty() {
            panic!("Prices ({:?}) is empty", prices);
        };

        let mut values: Vec<f64> = prices.iter().copied().filter(|f| !f.is_nan()).collect();
        values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
        let mid = values.len() / 2;

        if values.len() % 2 == 0 {
            (values[mid - 1] + values[mid]) / 2.0
        } else {
            values[mid]
        }
    }

    /// Calculates the mode (most common price) of a slice of prices.
    ///
    /// Rounds prices to the nearest integer for frequency counting.
    /// If multiple modes exist, returns their average.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 101.0, 101.0, 100.0];
    /// let mode = rust_ti::basic_indicators::single::mode(&prices);
    /// assert_eq!(100.5, mode); // 100.0 and 101.0 occur equally often, so average is 100.5
    ///
    /// let prices = vec![100.0, 102.0, 103.0, 101.0, 100.0];
    /// let mode = rust_ti::basic_indicators::single::mode(&prices);
    /// assert_eq!(100.0, mode); // 100.0 occurs most often
    /// ```
    #[inline]
    pub fn mode(prices: &[f64]) -> f64 {
        if prices.is_empty() {
            panic!("Prices ({:?}) is empty", prices);
        };
        let mut frequency: HashMap<i64, usize> = HashMap::new();
        for &price in prices {
            *frequency.entry(price.round() as i64).or_insert(0) += 1;
        }
        let max_count = frequency.values().copied().max().unwrap();
        let modes: Vec<i64> = frequency
            .iter()
            .filter_map(|(&value, &count)| {
                if count == max_count {
                    Some(value)
                } else {
                    None
                }
            })
            .collect();

        modes.iter().sum::<i64>() as f64 / modes.len() as f64
    }

    /// Calculates the difference between the natural logarithm at t and t-1
    ///
    /// # Arguments
    ///
    /// * `price_t` - price at t
    /// * `price_t_1` - price at t-1
    ///
    /// # Panics
    ///
    /// If `price_t` or `price_t_1` is <= 0.0
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 103.0, 101.0];
    /// let log_difference = rust_ti::basic_indicators::single::log_difference(prices[3], prices[2]);
    /// assert_eq!(-0.01960847138837618, log_difference);
    /// ```
    #[inline]
    pub fn log_difference(price_t: f64, price_t_1: f64) -> f64 {
        if price_t <= 0.0 || price_t_1 <= 0.0 {
            panic!(
                "price_t ({}) and price_t_1 ({}) need to be greater than 0.0",
                price_t, price_t_1
            );
        }
        price_t.ln() - price_t_1.ln()
    }

    /// Calculates the variance of a slice of prices
    ///
    /// Assumes a normal distribution
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 103.0, 101.0];
    /// let variance = rust_ti::basic_indicators::single::variance(&prices);
    /// assert_eq!(1.25, variance);
    /// ```
    #[inline]
    pub fn variance(prices: &[f64]) -> f64 {
        if prices.is_empty() {
            panic!("Prices ({:?}) is empty", prices);
        }
        let prices_mean = mean(prices);
        let mean_diff_sq: Vec<f64> = prices.iter().map(|x| (x - prices_mean).powi(2)).collect();
        mean(&mean_diff_sq)
    }

    /// Calculates the standard deviation of a slice of prices
    ///
    /// Assumes a normal distribution
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```
    /// let prices = vec![100.0, 102.0, 103.0, 101.0];
    /// let standard_deviation = rust_ti::basic_indicators::single::standard_deviation(&prices);
    /// assert_eq!(1.118033988749895, standard_deviation);
    /// ```
    #[inline]
    pub fn standard_deviation(prices: &[f64]) -> f64 {
        variance(prices).sqrt()
    }

    /// Calculates the absolute deviation from the mean, median, or mode.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `central_point` - Variant of [`CentralPoint`]
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 103.0, 101.0, 100.0];
    /// let mean_absolute_deviation =
    ///     rust_ti::basic_indicators::single::absolute_deviation(
    ///         &prices,
    ///         rust_ti::AbsDevConfig{ center: rust_ti::CentralPoint::Mean, aggregate: rust_ti::DeviationAggregate::Mean }
    ///     );
    /// // The answer is `1.04` but `f64` implementation we get `1.0400000000000005`
    /// assert_eq!(1.0400000000000005, mean_absolute_deviation);
    ///
    /// let median_absolute_deviation =
    ///     rust_ti::basic_indicators::single::absolute_deviation(
    ///         &prices,
    ///         rust_ti::AbsDevConfig{ center: rust_ti::CentralPoint::Median, aggregate: rust_ti::DeviationAggregate::Median }
    ///    );
    /// assert_eq!(1.0, median_absolute_deviation);
    ///
    /// let mode_absolute_deviation =
    ///     rust_ti::basic_indicators::single::absolute_deviation(
    ///         &prices,
    ///         rust_ti::AbsDevConfig{ center: rust_ti::CentralPoint::Mode, aggregate: rust_ti::DeviationAggregate::Mode }
    ///   );
    /// assert_eq!(0.0, mode_absolute_deviation);
    /// ```
    #[inline]
    pub fn absolute_deviation(prices: &[f64], config: AbsDevConfig) -> f64 {
        if prices.is_empty() {
            panic!("Prices is empty")
        };
        let mid_point = match config.center {
            CentralPoint::Mean => mean(prices),
            CentralPoint::Median => median(prices),
            CentralPoint::Mode => mode(prices),
            _ => panic!("Unsupported central_point {:?}", config.center),
        };

        let devs: Vec<f64> = prices.iter().map(|&x| (x - mid_point).abs()).collect();

        match config.aggregate {
            DeviationAggregate::Mean => mean(&devs),
            DeviationAggregate::Median => median(&devs),
            DeviationAggregate::Mode => mode(&devs),
        }
    }

    /// Calculates the log standard deviation of a slice of prices.
    ///
    /// Computes the standard deviation of log-transformed prices.
    /// Useful for analyzing multiplicative/percentage-based volatility.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices (must all be positive)
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `prices.is_empty()`
    ///     * Any price is <= 0
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::f64::consts::E;
    /// let prices = vec![1.0, E, E.powi(2)];
    /// let log_std = rust_ti::basic_indicators::single::log_standard_deviation(&prices);
    /// assert!(log_std > 0.0);
    /// ```
    #[inline]
    pub fn log_standard_deviation(prices: &[f64]) -> f64 {
        if prices.is_empty() {
            panic!("Prices ({:?}) is empty", prices);
        }
        let mut logs = Vec::with_capacity(prices.len());
        for &x in prices {
            if x <= 0.0 {
                panic!("LogStandardDeviation requires positive prices; found {}", x);
            }
            logs.push(x.ln());
        }
        standard_deviation(&logs)
    }

    /// Calculates the Student's t-adjusted standard deviation.
    ///
    /// Adjusts the sample standard deviation by the factor sqrt(df/(df-2))
    /// to match the standard deviation of a Student's t-distribution.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `df` - Degrees of freedom (must be > 2)
    ///
    /// # Panics
    ///
    /// Panics if `df` <= 2.0
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![1.0, 2.0, 3.0];
    /// let student_std = rust_ti::basic_indicators::single::student_t_adjusted_std(&prices, 5.0);
    /// assert!(student_std > 0.0);
    /// ```
    #[inline]
    pub fn student_t_adjusted_std(prices: &[f64], df: f64) -> f64 {
        if df <= 2.0 {
            panic!("Degrees of freedom ({}) must be greater than 2", df);
        }
        let s = standard_deviation(prices);
        s * (df / (df - 2.0)).sqrt()
    }

    /// Calculates the Laplace standard deviation equivalent.
    ///
    /// Estimates the scale parameter of a Laplace distribution as sqrt(2) * MAD,
    /// where MAD is the median absolute deviation from the median.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![0.0, 1.0, 2.0, 3.0, 4.0];
    /// let laplace_std = rust_ti::basic_indicators::single::laplace_std_equivalent(&prices);
    /// assert!(laplace_std > 0.0);
    /// ```
    #[inline]
    pub fn laplace_std_equivalent(prices: &[f64]) -> f64 {
        // b_hat = MAD about median; σ_laplace = sqrt(2) * b
        let mad = absolute_deviation(
            prices,
            AbsDevConfig {
                center: CentralPoint::Median,
                aggregate: DeviationAggregate::Median,
            },
        );
        mad * 2.0f64.sqrt()
    }

    /// Calculates the Cauchy IQR-based scale parameter.
    ///
    /// Estimates the scale parameter (gamma) of a Cauchy distribution as (Q3 - Q1) / 2,
    /// where Q1 and Q3 are the first and third quartiles.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices (must have at least 4 values)
    ///
    /// # Panics
    ///
    /// Panics if `prices.len()` < 4
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![1.0, 2.0, 3.0, 4.0];
    /// let cauchy_scale = rust_ti::basic_indicators::single::cauchy_iqr_scale(&prices);
    /// assert!(cauchy_scale > 0.0);
    /// ```
    #[inline]
    pub fn cauchy_iqr_scale(prices: &[f64]) -> f64 {
        if prices.len() < 4 {
            panic!(
                "CauchyIQRScale requires at least 4 values; received {}",
                prices.len()
            );
        }
        // Compute Q1, Q3 via sorted slice and Tukey hinges (simple, fast)
        let mut v = prices.to_vec();
        v.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let n = v.len();
        let mid = n / 2;
        let (lower, upper) = if n % 2 == 0 {
            (&v[..mid], &v[mid..])
        } else {
            (&v[..mid], &v[mid + 1..])
        };
        let q1 = percentile50(lower); // median of lower half
        let q3 = percentile50(upper); // median of upper half
        (q3 - q1) / 2.0
    }

    #[inline]
    fn percentile50(slice: &[f64]) -> f64 {
        let m = slice.len();
        if m == 0 {
            return f64::NAN;
        }
        if m % 2 == 1 {
            slice[m / 2]
        } else {
            0.5 * (slice[m / 2 - 1] + slice[m / 2])
        }
    }

    /// Calculates the maximum of a slice of prices (ignoring NaN)
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```
    /// let prices = vec![100.0, 102.0, 103.0, 101.0, 100.0];
    /// let max = rust_ti::basic_indicators::single::max(&prices);
    /// assert_eq!(103.0, max);
    /// ```
    #[inline]
    pub fn max(prices: &[f64]) -> f64 {
        if prices.is_empty() {
            panic!("Prices is empty")
        };
        prices
            .iter()
            .copied()
            .filter(|f| !f.is_nan())
            .fold(f64::NAN, f64::max)
    }

    /// Calculates the minimum of a slice of prices (ignores NaN)
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 103.0, 101.0, 100.0];
    /// let min = rust_ti::basic_indicators::single::min(&prices);
    /// assert_eq!(100.0, min);
    /// ```
    #[inline]
    pub fn min(prices: &[f64]) -> f64 {
        if prices.is_empty() {
            panic!("Prices is empty")
        };
        prices
            .iter()
            .copied()
            .filter(|f| !f.is_nan())
            .fold(f64::NAN, f64::min)
    }

    /// Calculates the distribution of prices (count of each unique price) in a slice
    ///
    /// Returns a vector of tuples containing (price, count) sorted by price in ascending order.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `precision` - Precision to group prices (e.g., 1.0 for whole numbers, 0.1 for one decimal place)
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 100.0, 103.0, 102.0, 100.0];
    /// let distribution = rust_ti::basic_indicators::single::price_distribution(&prices, 1.0);
    /// assert_eq!(vec![(100.0, 3), (102.0, 2), (103.0, 1)], distribution);
    /// ```
    #[inline]
    pub fn price_distribution(prices: &[f64], precision: f64) -> Vec<(f64, usize)> {
        if prices.is_empty() {
            panic!("Prices ({:?}) is empty", prices);
        }
        if !(precision > 0.0) {
            panic!("precision ({}) must be > 0.0 and not NaN", precision);
        }

        let mut frequency: HashMap<i64, usize> = HashMap::new();
        for &price in prices {
            if !price.is_nan() {
                // Use a scaling factor to handle floating point precision
                let key = (price / precision).round() as i64;
                *frequency.entry(key).or_insert(0) += 1;
            }
        }

        let mut result: Vec<(f64, usize)> = frequency
            .into_iter()
            .map(|(key, count)| ((key as f64) * precision, count))
            .collect();

        // Sort by price in ascending order
        result.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));

        result
    }

    #[inline]
    fn empirical_quantile_from_distribution(
        prices: &[f64],
        precision: f64,
        q: f64,
    ) -> f64 {
        if !(q > 0.0 && q < 1.0) {
            panic!("Quantile ({}) must be in (0,1)", q);
        }
        let hist = price_distribution(prices, precision);
        let n: usize = hist.iter().map(|(_, c)| *c).sum();
        if n == 0 {
            return f64::NAN;
        }
        // Rank using (n - 1) interpolation baseline
        let target = q * (n.saturating_sub(1)) as f64;

        // Walk cumulative counts
        let mut cum = 0usize;
        for (i, (price, count)) in hist.iter().enumerate() {
            let prev_cum = cum;
            cum += *count;

            if (target as usize) < cum {
                // Inside this bucket. Interpolate toward the next bucket center if any.
                let within = if *count > 1 {
                    // Fraction within this bucket: distance from prev_cum to target
                    (target - prev_cum as f64) / (*count as f64)
                } else {
                    0.0
                };
                if i + 1 < hist.len() {
                    let (next_price, _) = hist[i + 1];
                    return price + within.clamp(0.0, 1.0) * (next_price - price);
                } else {
                    return *price;
                }
            }
        }
        // Fallback (shouldn’t happen): return last price
        hist.last().map(|(p, _)| *p).unwrap_or(f64::NAN)
    }

    /// Computes an empirical quantile from the histogram produced by `price_distribution`,
    /// using linear interpolation across adjacent buckets.
    ///
    /// The histogram is constructed by bucketing values to the provided `precision`. For example,
    /// `precision = 1.0` groups by whole numbers; `precision = 0.01` groups by cents.
    ///
    /// Quantile definition:
    /// - Uses target rank `q * (n - 1)` where `n` is the total count in the histogram.
    /// - Walks cumulative counts until the bucket containing the rank is found.
    /// - Interpolates linearly toward the next bucket center by the within-bucket fraction.
    ///   If no next bucket exists (last bucket), returns the current bucket center.
    ///
    /// Panics:
    /// - If `q` is not in (0, 1).
    /// - If `precision <= 0.0` or `precision` is NaN (via `price_distribution`).
    ///
    /// Examples
    /// ```
    /// let prices = vec![1.0, 2.0, 3.0, 4.0];
    /// let q25 = rust_ti::basic_indicators::single::empirical_quantile_range_from_distribution(&prices, 1.0, 0.25, 0.75);
    /// assert_eq!(2.0, q25);
    /// ```
    #[inline]
    pub fn empirical_quantile_range_from_distribution(
        prices: &[f64],
        precision: f64,
        low: f64,
        high: f64,
    ) -> f64 {
        if !(precision > 0.0) {
            panic!("precision ({}) must be > 0.0 and not NaN", precision);
        }
        if !(low > 0.0 && low < 1.0 && high > 0.0 && high < 1.0 && low < high) {
            panic!(
                "Invalid quantile bounds: low ({}) and high ({}) must be in (0,1) and low < high",
                low, high
            );
        }
        let ql = empirical_quantile_from_distribution(prices, precision, low);
        let qh = empirical_quantile_from_distribution(prices, precision, high);
        qh - ql
    }

}

/// **bulk**: Functions that compute values of a slice of prices over a period and return a vector.
pub mod bulk {
    use crate::basic_indicators::single;
    use crate::AbsDevConfig;

    /// Calculates the mean (averages) of a slice of prices over a given period
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `period` - Period over which to calculate the mean
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![101.0, 102.0, 103.0, 101.0];
    /// let mean = rust_ti::basic_indicators::bulk::mean(&prices, 3);
    /// assert_eq!(vec![102.0, 102.0], mean);
    /// ```
    #[inline]
    pub fn mean(prices: &[f64], period: usize) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period);
        }
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of prices ({})",
                period,
                prices.len()
            );
        };
        let mut result = Vec::with_capacity(prices.len());
        for window in prices.windows(period) {
            result.push(single::mean(window))
        }
        result
    }

    /// Calculates the median (middle value) of a slice of prices over a given periods.
    ///
    /// If the number of prices is even it will take the average of the two middle values.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `period` - Period over which to calculate the median
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![101.0, 102.0, 103.0, 101.0];
    /// let median = rust_ti::basic_indicators::bulk::median(&prices, 3);
    /// assert_eq!(vec![102.0, 102.0], median);
    /// ```
    #[inline]
    pub fn median(prices: &[f64], period: usize) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period);
        };
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of provided prices ({})",
                period,
                prices.len()
            );
        };
        let mut result = Vec::with_capacity(prices.len());
        for window in prices.windows(period) {
            result.push(single::median(window))
        }
        result
    }

    /// Calculates the mode (most common price) of a slice of prices over a given period.
    ///
    /// If multiple modes are found it will the average of those
    /// numbers.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `period` - Period over which to calculate the mode
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![101.0, 102.0, 101.0, 102.0];
    /// let mode = rust_ti::basic_indicators::bulk::mode(&prices, 3);
    /// assert_eq!(vec![101.0, 102.0], mode);
    /// ```
    #[inline]
    pub fn mode(prices: &[f64], period: usize) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period);
        };
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of provided prices ({})",
                period,
                prices.len()
            );
        };
        let mut result = Vec::with_capacity(prices.len());
        for window in prices.windows(period) {
            result.push(single::mode(window))
        }
        result
    }

    /// Calculates the natural logarithm of slice of prices
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty.()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![101.0, 102.0, 103.0, 101.0];
    /// let log = rust_ti::basic_indicators::bulk::log(&prices);
    /// assert_eq!(
    ///     vec![4.61512051684126, 4.624972813284271, 4.634728988229636, 4.61512051684126],
    ///     log
    /// );
    /// ```
    #[inline]
    pub fn log(prices: &[f64]) -> Vec<f64> {
        if prices.is_empty() {
            panic!("Prices ({:?}) is empty", prices);
        }
        prices.iter().map(|&p| p.ln()).collect()
    }

    /// Calculates the difference between the natural logarithm at t and t-1
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    ///
    /// # Panics
    ///
    /// Panics if `prices.is_empty()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 103.0, 101.0];
    /// let log_difference = rust_ti::basic_indicators::bulk::log_difference(&prices);
    /// assert_eq!(
    ///     vec![0.019802627296178876, 0.009756174945365181, -0.01960847138837618],
    ///     log_difference
    /// );
    /// ```
    #[inline]
    pub fn log_difference(prices: &[f64]) -> Vec<f64> {
        if prices.is_empty() {
            panic!("Prices ({:?}) is empty", prices);
        }
        prices
            .windows(2)
            .map(|w| single::log_difference(w[1], w[0]))
            .collect()
    }

    /// Calculates the variance of slice of prices over a given period.
    ///
    /// Assumes a normal distribution
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `period` - Period over which to calculate the variance
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 103.0, 101.0];
    /// let period: usize = 3;
    /// let variance = rust_ti::basic_indicators::bulk::variance(&prices, period);
    /// assert_eq!(vec![1.5555555555555556, 0.6666666666666666], variance);
    /// ```
    #[inline]
    pub fn variance(prices: &[f64], period: usize) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period)
        };
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of provided prices ({})",
                period,
                prices.len()
            );
        };
        let mut result = Vec::with_capacity(prices.len());
        for window in prices.windows(period) {
            result.push(single::variance(window))
        }
        result
    }

    /// Calculates the standard deviation of a slice of prices over a given period
    ///
    /// Assumes a normal distribution
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `period` - Period over which to calculate the standard deviation
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 103.0, 101.0];
    /// let period: usize = 3;
    /// let standard_deviation =
    ///     rust_ti::basic_indicators::bulk::standard_deviation(&prices, period);
    /// assert_eq!(vec![1.247219128924647, 0.816496580927726], standard_deviation);
    /// ```
    #[inline]
    pub fn standard_deviation(prices: &[f64], period: usize) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period)
        };
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of provided prices ({})",
                period,
                prices.len()
            );
        };
        let mut result = Vec::with_capacity(prices.len());
        for window in prices.windows(period) {
            result.push(single::standard_deviation(window));
        }
        result
    }

    /// Calculates the absolute deviation from the mean, median, or mode over a given period.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `period` - Period over which to calculate the standard deviation
    /// * `central_point` - Variant of [`CentralPoint`]
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rust_ti::{CentralPoint, DeviationAggregate};
    /// let prices = vec![100.0, 102.0, 103.0, 101.0, 100.0];
    /// let period: usize = 3;
    ///
    /// let mean_absolute_deviation =
    ///     rust_ti::basic_indicators::bulk::absolute_deviation(
    ///         &prices,
    ///         period,
    ///         rust_ti::AbsDevConfig{ center: CentralPoint::Mean, aggregate: DeviationAggregate::Mean }
    ///     );
    /// assert_eq!(
    ///     vec![1.1111111111111096, 0.6666666666666666, 1.1111111111111096],
    ///     mean_absolute_deviation
    /// );
    ///
    /// let median_absolute_deviation =
    ///     rust_ti::basic_indicators::bulk::absolute_deviation(
    ///         &prices,
    ///         period,
    ///         rust_ti::AbsDevConfig{ center: CentralPoint::Median, aggregate: DeviationAggregate::Median }
    ///     );
    /// assert_eq!(vec![1.0, 1.0, 1.0], median_absolute_deviation);
    ///
    /// let mode_absolute_deviation =
    ///     rust_ti::basic_indicators::bulk::absolute_deviation(
    ///         &prices,
    ///         period,
    ///         rust_ti::AbsDevConfig{ center: CentralPoint::Mode, aggregate: DeviationAggregate::Mode }
    ///     );
    /// assert_eq!(
    ///     vec![1.0, 1.0, 1.0],
    ///     mode_absolute_deviation
    /// );
    /// ```
    #[inline]
    pub fn absolute_deviation(prices: &[f64], period: usize, config: AbsDevConfig) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period)
        };
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of provided prices ({})",
                period,
                prices.len()
            );
        };
        prices
            .windows(period)
            .map(|w| single::absolute_deviation(w, config))
            .collect()
    }

    /// Calculates the distribution of prices (count of each unique price) over a given period
    ///
    /// For each sliding window of the specified period, returns a vector of tuples containing
    /// (price, count) sorted by price in ascending order.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `precision` - Precision to group prices (e.g., 1.0 for whole numbers, 0.1 for one decimal place)
    /// * `period` - Period over which to calculate the price distribution
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 100.0, 103.0, 102.0];
    /// let distribution = rust_ti::basic_indicators::bulk::price_distribution(&prices, 3, 1.0);
    /// assert_eq!(
    ///     vec![
    ///         vec![(100.0, 2), (102.0, 1)],
    ///         vec![(100.0, 1), (102.0, 1), (103.0, 1)],
    ///         vec![(100.0, 1), (102.0, 1), (103.0, 1)]
    ///     ],
    ///     distribution
    /// );
    /// ```
    #[inline]
    pub fn price_distribution(
        prices: &[f64],
        period: usize,
        precision: f64,
    ) -> Vec<Vec<(f64, usize)>> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period);
        }
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of provided prices ({})",
                period,
                prices.len()
            );
        }

        prices
            .windows(period)
            .map(|w| single::price_distribution(w, precision))
            .collect()
    }

    /// Calculates the log standard deviation of a slice of prices over a given period.
    ///
    /// Computes the standard deviation of log-transformed prices in each window.
    /// Useful for analyzing multiplicative/percentage-based volatility.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices (must be positive)
    /// * `period` - Period over which to calculate the log standard deviation
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///     * Any price in a window is <= 0
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![100.0, 102.0, 103.0, 101.0, 99.0];
    /// let log_std = rust_ti::basic_indicators::bulk::log_standard_deviation(&prices, 3);
    /// assert_eq!(3, log_std.len());
    /// ```
    #[inline]
    pub fn log_standard_deviation(prices: &[f64], period: usize) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period);
        }
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of prices ({})",
                period,
                prices.len()
            );
        }
        let mut result = Vec::with_capacity(prices.len());
        for window in prices.windows(period) {
            result.push(single::log_standard_deviation(window))
        }
        result
    }

    /// Calculates the Student's t-adjusted standard deviation over a given period.
    ///
    /// Adjusts the sample standard deviation by the factor sqrt(df/(df-2))
    /// to match the standard deviation of a Student's t-distribution.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `period` - Period over which to calculate the standard deviation
    /// * `df` - Degrees of freedom (must be > 2)
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///     * `df` <= 2.0
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    /// let student_std = rust_ti::basic_indicators::bulk::student_t_adjusted_std(&prices, 3, 5.0);
    /// assert_eq!(3, student_std.len());
    /// ```
    #[inline]
    pub fn student_t_adjusted_std(prices: &[f64], period: usize, df: f64) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period);
        }
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of prices ({})",
                period,
                prices.len()
            );
        }
        let mut result = Vec::with_capacity(prices.len());
        for window in prices.windows(period) {
            result.push(single::student_t_adjusted_std(window, df))
        }
        result
    }

    /// Calculates the Laplace standard deviation equivalent over a given period.
    ///
    /// Estimates the scale parameter of a Laplace distribution as sqrt(2) * MAD,
    /// where MAD is the median absolute deviation from the median.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `period` - Period over which to calculate the Laplace std equivalent
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` == 0
    ///     * `period` > `prices.len()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![0.0, 1.0, 2.0, 3.0, 4.0];
    /// let laplace_std = rust_ti::basic_indicators::bulk::laplace_std_equivalent(&prices, 3);
    /// assert_eq!(3, laplace_std.len());
    /// ```
    #[inline]
    pub fn laplace_std_equivalent(prices: &[f64], period: usize) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period);
        }
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of prices ({})",
                period,
                prices.len()
            );
        }
        let mut result = Vec::with_capacity(prices.len());
        for window in prices.windows(period) {
            result.push(single::laplace_std_equivalent(window))
        }
        result
    }

    /// Calculates the Cauchy IQR-based scale parameter over a given period.
    ///
    /// Estimates the scale parameter (gamma) of a Cauchy distribution as (Q3 - Q1) / 2,
    /// where Q1 and Q3 are the first and third quartiles.
    ///
    /// # Arguments
    ///
    /// * `prices` - Slice of prices
    /// * `period` - Period over which to calculate the Cauchy scale (must be >= 4)
    ///
    /// # Panics
    ///
    /// Panics if:
    ///     * `period` < 4
    ///     * `period` > `prices.len()`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let prices = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
    /// let cauchy_scale = rust_ti::basic_indicators::bulk::cauchy_iqr_scale(&prices, 4);
    /// assert_eq!(3, cauchy_scale.len());
    /// ```
    #[inline]
    pub fn cauchy_iqr_scale(prices: &[f64], period: usize) -> Vec<f64> {
        if period < 4 {
            panic!(
                "Period ({}) must be at least 4 for Cauchy IQR scale",
                period
            );
        }
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of prices ({})",
                period,
                prices.len()
            );
        }
        let mut result = Vec::with_capacity(prices.len());
        for window in prices.windows(period) {
            result.push(single::cauchy_iqr_scale(window))
        }
        result
    }

    /// Empirical quantile range `q_high - q_low` computed from the price histogram.
    ///
    /// This function is a building block for an empirical deviation model: choose a lower and
    /// upper quantile (e.g., 0.25 and 0.75 for IQR) and a `precision` that matches the instrument’s
    /// tick size to get a robust, distribution-free scale for each window or slice.
    ///
    /// - Histogram: prices are grouped to `precision` and counted by `price_distribution`.
    /// - Quantiles: computed via [`empirical_quantile_from_distribution`] with linear interpolation.
    /// - Result: `q(high) - q(low)` as a width (not a variance-derived standard deviation).
    ///
    /// Panics:
    /// - If `precision <= 0.0` or NaN.
    /// - If `low`, `high` are not in (0, 1) or `low >= high`.
    ///
    /// Examples
    /// ```
    /// // IQR for [1,2,3,4] at precision 1.0 is 3.25 - 1.75 = 1.5
    /// let prices = vec![1.0, 2.0, 3.0, 4.0];
    /// let iqr = rust_ti::basic_indicators::bulk::empirical_quantile_range_from_distribution(&prices, 3, 1.0, 0.25, 0.75);
    /// assert_eq!(vec![1.0, 1.0], iqr);
    /// ```
    #[inline]
    pub fn empirical_quantile_range_from_distribution(
        prices: &[f64],
        period: usize,
        precision: f64,
        low: f64,
        high: f64,
    ) -> Vec<f64> {
        if period == 0 {
            panic!("Period ({}) must be greater than 0", period);
        }
        if period > prices.len() {
            panic!(
                "Period ({}) cannot be longer than the length of provided prices ({})",
                period,
                prices.len()
            );
        }
        prices
            .windows(period)
            .map(|w| single::empirical_quantile_range_from_distribution(w, precision, low, high))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::f64::consts::E;

    #[test]
    fn single_mean() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        assert_eq!(100.352, single::mean(&prices));
    }

    #[test]
    fn single_mean_identical_prices() {
        let prices = vec![100.0, 100.0, 100.0];
        assert_eq!(100.0, single::mean(&prices));
    }

    #[test]
    #[should_panic]
    fn single_mean_empty_prices() {
        let prices = Vec::new();
        single::mean(&prices);
    }

    #[test]
    fn bulk_mean() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period: usize = 3;
        assert_eq!(
            vec![100.39666666666666, 100.45666666666666, 100.36666666666667],
            bulk::mean(&prices, period)
        );
    }

    #[test]
    #[should_panic]
    fn bulk_mean_long_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period: usize = 30;
        bulk::mean(&prices, period);
    }

    #[test]
    #[should_panic]
    fn bulk_mean_no_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period: usize = 0;
        bulk::mean(&prices, period);
    }

    #[test]
    fn single_median_odd() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        assert_eq!(100.38, single::median(&prices));
    }

    #[test]
    fn single_median_even() {
        let prices = vec![100.2, 100.46, 100.53, 100.38];
        // Should be
        // assert_eq!(100.42, single::median(&prices));
        // but due to how floating points are calculated we have to assert on
        assert_eq!(100.41999999999999, single::median(&prices));
    }

    #[test]
    #[should_panic]
    fn single_median_panic() {
        let prices = Vec::new();
        single::median(&prices);
    }

    #[test]
    fn bulk_median() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period: usize = 3;
        assert_eq!(vec![100.46, 100.46, 100.38], bulk::median(&prices, period));
    }

    #[test]
    #[should_panic]
    fn bulk_median_long_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period: usize = 30;
        bulk::median(&prices, period);
    }

    #[test]
    #[should_panic]
    fn bulk_median_no_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period: usize = 0;
        bulk::median(&prices, period);
    }

    #[test]
    fn single_mode_round_up() {
        let prices = vec![100.2, 100.46, 100.53, 101.08, 101.19];
        assert_eq!(101.0, single::mode(&prices));
    }

    #[test]
    fn single_mode_round_down() {
        let prices = vec![100.2, 100.46, 100.35, 101.08, 101.19];
        assert_eq!(100.0, single::mode(&prices));
    }

    #[test]
    fn single_mode_average() {
        let prices = vec![100.46, 100.35, 101.08, 101.19];
        assert_eq!(100.5, single::mode(&prices));
    }

    #[test]
    #[should_panic]
    fn single_mode_panic() {
        let prices = Vec::new();
        single::mode(&prices);
    }

    #[test]
    fn bulk_mode() {
        let prices = vec![100.2, 100.46, 100.53, 101.08, 101.19];
        let period: usize = 3;
        assert_eq!(vec![100.0, 101.0, 101.0], bulk::mode(&prices, period));
    }

    #[test]
    #[should_panic]
    fn bulk_mode_long_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 101.08, 101.19];
        let period: usize = 30;
        bulk::mode(&prices, period);
    }

    #[test]
    #[should_panic]
    fn bulk_mode_no_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 101.08, 101.19];
        let period: usize = 0;
        bulk::mode(&prices, period);
    }

    #[test]
    fn bulk_log() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        assert_eq!(
            vec![
                4.607168188650764,
                4.609759638321899,
                4.610456190417329,
                4.608962984226787,
                4.607068383271171
            ],
            bulk::log(&prices)
        );
    }

    #[test]
    #[should_panic]
    fn bulk_log_panic() {
        let prices = Vec::new();
        bulk::log(&prices);
    }

    #[test]
    fn single_log_difference() {
        assert_eq!(
            -0.0018946009556159993,
            single::log_difference(100.19, 100.38)
        );
    }

    #[test]
    #[should_panic]
    fn single_log_difference_panic() {
        single::log_difference(0.0, 100.38);
    }

    #[test]
    #[should_panic]
    fn single_log_difference_panic_2() {
        single::log_difference(100.19, -100.38);
    }

    #[test]
    fn bulk_log_difference() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        assert_eq!(
            vec![
                0.0025914496711347823,
                0.0006965520954302917,
                -0.0014932061905419403,
                -0.0018946009556159993
            ],
            bulk::log_difference(&prices)
        );
    }

    #[test]
    #[should_panic]
    fn bulk_log_difference_difference() {
        bulk::log_difference(&Vec::new());
    }

    #[test]
    fn single_variance() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        assert_eq!(0.018695999999999734, single::variance(&prices));
    }

    #[test]
    #[should_panic]
    fn single_variance_panic() {
        let prices = Vec::new();
        single::variance(&prices);
    }

    #[test]
    fn bulk_variance() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period = 3;
        assert_eq!(
            vec![
                0.02015555555555502,
                0.0037555555555558295,
                0.019355555555555907
            ],
            bulk::variance(&prices, period)
        );
    }

    #[test]
    #[should_panic]
    fn bulk_variance_long_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period = 30;
        bulk::variance(&prices, period);
    }

    #[test]
    #[should_panic]
    fn bulk_variance_no_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period = 0;
        bulk::variance(&prices, period);
    }

    #[test]
    fn single_standard_deviation() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        assert_eq!(0.1367333170810967, single::standard_deviation(&prices));
    }

    #[test]
    #[should_panic]
    fn single_standard_deviation_panic() {
        let prices = Vec::new();
        single::standard_deviation(&prices);
    }

    #[test]
    fn bulk_standard_deviation() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period = 3;
        assert_eq!(
            vec![
                0.14197026292697715,
                0.06128258770283635,
                0.13912424503139598
            ],
            bulk::standard_deviation(&prices, period)
        );
    }

    #[test]
    #[should_panic]
    fn bulk_standard_deviation_long_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period = 30;
        bulk::standard_deviation(&prices, period);
    }

    #[test]
    #[should_panic]
    fn bulk_standard_deviation_no_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period = 0;
        bulk::standard_deviation(&prices, period);
    }

    #[test]
    fn single_absolute_deviation() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        assert_eq!(
            0.12559999999999719,
            single::absolute_deviation(
                &prices,
                crate::AbsDevConfig {
                    center: crate::CentralPoint::Mean,
                    aggregate: crate::DeviationAggregate::Mean
                }
            )
        );
        assert_eq!(
            0.15000000000000568,
            single::absolute_deviation(
                &prices,
                crate::AbsDevConfig {
                    center: crate::CentralPoint::Median,
                    aggregate: crate::DeviationAggregate::Median
                }
            )
        );
        assert_eq!(
            0.0,
            single::absolute_deviation(
                &prices,
                crate::AbsDevConfig {
                    center: crate::CentralPoint::Mode,
                    aggregate: crate::DeviationAggregate::Mode
                }
            )
        );
    }

    #[test]
    #[should_panic]
    fn singe_absolute_deviation_panic() {
        let prices = Vec::new();
        single::absolute_deviation(
            &prices,
            crate::AbsDevConfig {
                center: crate::CentralPoint::Mean,
                aggregate: crate::DeviationAggregate::Mean,
            },
        );
    }

    #[test]
    fn bulk_absolute_deviation() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period: usize = 3;

        assert_eq!(
            vec![
                0.1311111111111103,
                0.051111111111111995,
                0.11777777777777487
            ],
            bulk::absolute_deviation(
                &prices,
                period,
                crate::AbsDevConfig {
                    center: crate::CentralPoint::Mean,
                    aggregate: crate::DeviationAggregate::Mean
                }
            )
        );
        assert_eq!(
            vec![
                0.07000000000000739,
                0.07000000000000739,
                0.15000000000000568
            ],
            bulk::absolute_deviation(
                &prices,
                period,
                crate::AbsDevConfig {
                    center: crate::CentralPoint::Median,
                    aggregate: crate::DeviationAggregate::Median
                }
            )
        );
        assert_eq!(
            vec![0.0, 0.0, 0.0],
            bulk::absolute_deviation(
                &prices,
                period,
                crate::AbsDevConfig {
                    center: crate::CentralPoint::Mode,
                    aggregate: crate::DeviationAggregate::Mode
                }
            )
        );
    }

    #[test]
    #[should_panic]
    fn bulk_absolute_deviation_long_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period: usize = 30;
        bulk::absolute_deviation(
            &prices,
            period,
            crate::AbsDevConfig {
                center: crate::CentralPoint::Median,
                aggregate: crate::DeviationAggregate::Median,
            },
        );
    }

    #[test]
    #[should_panic]
    fn bulk_absolute_deviation_no_period_panic() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        let period: usize = 30;
        bulk::absolute_deviation(
            &prices,
            period,
            crate::AbsDevConfig {
                center: crate::CentralPoint::Median,
                aggregate: crate::DeviationAggregate::Median,
            },
        );
    }

    #[test]
    fn test_single_max() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        assert_eq!(100.53, single::max(&prices));
    }

    #[test]
    #[should_panic]
    fn test_single_max_panic() {
        let prices = Vec::new();
        single::max(&prices);
    }

    #[test]
    fn test_single_min() {
        let prices = vec![100.2, 100.46, 100.53, 100.38, 100.19];
        assert_eq!(100.19, single::min(&prices));
    }

    #[test]
    #[should_panic]
    fn test_single_min_panic() {
        let prices = Vec::new();
        single::min(&prices);
    }

    #[test]
    fn test_single_price_distribution() {
        let prices = vec![100.0, 102.0, 100.0, 103.0, 102.0, 100.0];
        let distribution = single::price_distribution(&prices, 1.0);
        assert_eq!(vec![(100.0, 3), (102.0, 2), (103.0, 1)], distribution);
    }

    #[test]
    fn test_single_price_distribution_unique() {
        let prices = vec![100.0, 101.0, 102.0, 103.0];
        let distribution = single::price_distribution(&prices, 1.0);
        assert_eq!(
            vec![(100.0, 1), (101.0, 1), (102.0, 1), (103.0, 1)],
            distribution
        );
    }

    #[test]
    fn test_single_price_distribution_same() {
        let prices = vec![100.0, 100.0, 100.0];
        let distribution = single::price_distribution(&prices, 1.0);
        assert_eq!(vec![(100.0, 3)], distribution);
    }

    #[test]
    #[should_panic]
    fn test_single_price_distribution_panic() {
        let prices = Vec::new();
        single::price_distribution(&prices, 1.0);
    }

    #[test]
    #[should_panic]
    fn test_single_price_distribution_bad_precision() {
        single::price_distribution(&[1.0], 0.0);
    }

    #[test]
    fn test_single_price_distribution_precision_examples() {
        let prices = vec![5949.41];
        assert_eq!(
            vec![(6000.0, 1)],
            single::price_distribution(&prices, 1000.0)
        );
        assert_eq!(
            vec![(5900.0, 1)],
            single::price_distribution(&prices, 100.0)
        );
        assert_eq!(vec![(5950.0, 1)], single::price_distribution(&prices, 10.0));
        assert_eq!(vec![(5949.0, 1)], single::price_distribution(&prices, 1.0));
        assert_eq!(
            vec![(5949.400000000001, 1)],
            single::price_distribution(&prices, 0.1)
        );
    }

    #[test]
    fn test_single_price_distribution_half_precision() {
        let prices = vec![100.2, 100.46, 100.53, 101.08, 101.19];
        // precision 1.0
        assert_eq!(
            vec![(100.0, 2), (101.0, 3)],
            single::price_distribution(&prices, 1.0)
        );
        // precision 0.5
        assert_eq!(
            vec![(100.0, 1), (100.5, 2), (101.0, 2)],
            single::price_distribution(&prices, 0.5)
        );
    }

    #[test]
    fn test_single_price_distribution_nan_ignored() {
        let prices = vec![100.0, f64::NAN, 100.4, 100.49, 100.51];
        // precision 0.5 -> 100.0, 100.5 buckets
        assert_eq!(
            vec![(100.0, 1), (100.5, 3)],
            single::price_distribution(&prices, 0.5)
        );
    }

    #[test]
    fn test_bulk_price_distribution() {
        let prices = vec![100.0, 102.0, 100.0, 103.0, 102.0];
        let distribution = bulk::price_distribution(&prices, 3, 1.0);
        assert_eq!(
            vec![
                vec![(100.0, 2), (102.0, 1)],
                vec![(100.0, 1), (102.0, 1), (103.0, 1)],
                vec![(100.0, 1), (102.0, 1), (103.0, 1)]
            ],
            distribution
        );
    }

    #[test]
    fn test_bulk_price_distribution_half_precision() {
        let prices = vec![100.2, 100.46, 100.53, 101.08];
        // period 3, precision 0.5
        // windows:
        // [100.2,100.46,100.53] -> 100.0 (1), 100.5 (2)
        // [100.46,100.53,101.08] -> 100.5 (2), 101.0 (1)
        let distribution = bulk::price_distribution(&prices, 3, 0.5);
        assert_eq!(
            vec![vec![(100.0, 1), (100.5, 2)], vec![(100.5, 2), (101.0, 1)],],
            distribution
        );
    }

    #[test]
    #[should_panic]
    fn test_bulk_price_distribution_period_too_long() {
        let prices = vec![100.0, 102.0, 100.0];
        bulk::price_distribution(&prices, 5, 1.0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_price_distribution_zero_period() {
        let prices = vec![100.0, 102.0, 100.0];
        bulk::price_distribution(&prices, 0, 1.0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_price_distribution_bad_precision() {
        let prices = vec![100.0, 101.0, 102.0];
        bulk::price_distribution(&prices, 2, -1.0);
    }

    #[test]
    fn test_log_standard_deviation_simple_series() {
        // prices = [1, e, e^2] -> logs = [0, 1, 2], sample std = 1
        let prices = vec![1.0, E, E.powi(2)];
        let s = single::log_standard_deviation(&prices);
        assert_eq!(0.816496580927726, s);
    }

    #[test]
    #[should_panic]
    fn test_log_standard_deviation_panics_on_non_positive() {
        let prices = vec![1.0, 0.0];
        let _ = single::log_standard_deviation(&prices);
    }

    #[test]
    fn test_student_t_adjusted_std_factor_works() {
        // base series with sample std = 1.0
        let prices = vec![1.0, 2.0, 3.0];
        // df = 5 => adjustment sqrt(df/(df-2)) = sqrt(5/3)
        let df = 5.0;
        let s = single::student_t_adjusted_std(&prices, df);
        assert_eq!(1.0540925533894598, s);
    }

    #[test]
    #[should_panic]
    fn test_student_t_adjusted_std_panics_on_low_df() {
        let prices = vec![1.0, 2.0, 3.0];
        let _ = single::student_t_adjusted_std(&prices, 2.0);
    }

    #[test]
    fn test_laplace_std_equivalent_matches_sqrt2_mad() {
        // median = 1, deviations = [1,1,1,0,1,1,1], MAD = 1 => σ_laplace = √2
        let prices = vec![0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0];
        let s = single::laplace_std_equivalent(&prices);
        let expected = 2.0_f64.sqrt();
        assert!(
            (s - expected).abs() < 1e-12,
            "expected {}, got {}",
            expected,
            s
        );
    }

    #[test]
    fn test_cauchy_iqr_scale_basic() {
        // [1,2,3,4], Q1 = 1.5, Q3 = 3.5 => IQR = 2 => gamma = 1
        let prices = vec![1.0, 2.0, 3.0, 4.0];
        let s = single::cauchy_iqr_scale(&prices);
        assert!((s - 1.0).abs() < 1e-12, "expected 1.0, got {}", s);
    }

    #[test]
    #[should_panic]
    fn test_cauchy_iqr_scale_panics_on_short_input() {
        let prices = vec![1.0, 2.0, 3.0];
        let _ = single::cauchy_iqr_scale(&prices);
    }

    // Bulk tests for new functions

    #[test]
    fn test_bulk_log_standard_deviation() {
        let prices = vec![1.0, E, E.powi(2), E.powi(3), E.powi(4)];
        let log_std = bulk::log_standard_deviation(&prices, 3);
        assert_eq!(3, log_std.len());
        // Each window should have similar behavior to single version
        assert!(log_std[0] > 0.0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_log_standard_deviation_zero_period() {
        let prices = vec![1.0, 2.0, 3.0];
        let _ = bulk::log_standard_deviation(&prices, 0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_log_standard_deviation_period_too_long() {
        let prices = vec![1.0, 2.0, 3.0];
        let _ = bulk::log_standard_deviation(&prices, 5);
    }

    #[test]
    #[should_panic]
    fn test_bulk_log_standard_deviation_panics_on_non_positive() {
        let prices = vec![1.0, 0.0, 2.0, 3.0];
        let _ = bulk::log_standard_deviation(&prices, 2);
    }

    #[test]
    fn test_bulk_student_t_adjusted_std() {
        let prices = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let df = 5.0;
        let student_std = bulk::student_t_adjusted_std(&prices, 3, df);
        assert_eq!(3, student_std.len());
        // Each value should be adjusted by sqrt(df/(df-2))
        assert!(student_std[0] > 0.0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_student_t_adjusted_std_zero_period() {
        let prices = vec![1.0, 2.0, 3.0];
        let _ = bulk::student_t_adjusted_std(&prices, 0, 5.0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_student_t_adjusted_std_period_too_long() {
        let prices = vec![1.0, 2.0, 3.0];
        let _ = bulk::student_t_adjusted_std(&prices, 5, 5.0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_student_t_adjusted_std_panics_on_low_df() {
        let prices = vec![1.0, 2.0, 3.0, 4.0];
        let _ = bulk::student_t_adjusted_std(&prices, 2, 2.0);
    }

    #[test]
    fn test_bulk_laplace_std_equivalent() {
        let prices = vec![0.0, 1.0, 2.0, 3.0, 4.0];
        let laplace_std = bulk::laplace_std_equivalent(&prices, 3);
        assert_eq!(3, laplace_std.len());
        assert!(laplace_std[0] > 0.0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_laplace_std_equivalent_zero_period() {
        let prices = vec![1.0, 2.0, 3.0];
        let _ = bulk::laplace_std_equivalent(&prices, 0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_laplace_std_equivalent_period_too_long() {
        let prices = vec![1.0, 2.0, 3.0];
        let _ = bulk::laplace_std_equivalent(&prices, 5);
    }

    #[test]
    fn test_bulk_cauchy_iqr_scale() {
        let prices = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let cauchy_scale = bulk::cauchy_iqr_scale(&prices, 4);
        assert_eq!(3, cauchy_scale.len());
        assert!(cauchy_scale[0] > 0.0);
    }

    #[test]
    #[should_panic]
    fn test_bulk_cauchy_iqr_scale_period_less_than_four() {
        let prices = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let _ = bulk::cauchy_iqr_scale(&prices, 3);
    }

    #[test]
    #[should_panic]
    fn test_bulk_cauchy_iqr_scale_period_too_long() {
        let prices = vec![1.0, 2.0, 3.0, 4.0];
        let _ = bulk::cauchy_iqr_scale(&prices, 5);
    }
    #[test]
    fn test_single_empirical_quantile_range_from_distribution_simple() {
        // For [1,2,3,4] with precision 1.0, q25=1.75, q75=3.25 => IQR=1.5 (linear interpolation)
        let prices = vec![1.0, 2.0, 3.0, 4.0];
        let iqr = single::empirical_quantile_range_from_distribution(&prices, 1.0, 0.25, 0.75);
        assert_eq!(2.0, iqr,);
    }

    #[test]
    fn test_bulk_empirical_quantile_range_from_distribution() {
        let prices = vec![1.0, 2.0, 3.0, 4.0];
        let v = bulk::empirical_quantile_range_from_distribution(&prices, 3, 1.0, 0.25, 0.75);
        // windows: [1,2,3] -> IQR=1.0; [2,3,4] -> IQR=1.0
        assert_eq!(vec![1.0, 1.0], v);
    }

    #[test]
    #[should_panic]
    fn test_single_empirical_quantile_invalid_bounds() {
        let prices = vec![1.0, 2.0, 3.0];
        let _ = single::empirical_quantile_range_from_distribution(&prices, 1.0, 0.8, 0.2);
    }

}