anofox-forecast 0.7.5

Time series forecasting library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
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
# API Reference

This document provides a comprehensive reference for all public APIs in the `anofox-forecast` crate. The crate provides 35+ forecasting models, 76+ time series features, and extensive utilities for time series analysis.

## Table of Contents

- [Core Types]#core-types
  - [TimeSeries]#timeseries
  - [TimeSeriesBuilder]#timeseriesbuilder
  - [Forecast]#forecast
  - [ForecastError]#forecasterror
- [Missing Value Imputation]#missing-value-imputation
  - [MissingValuePolicy]#missingvaluepolicy
  - [Imputation Methods]#imputation-methods
  - [Metadata Helpers]#metadata-helpers
- [Forecaster Trait]#forecaster-trait
- [Baseline Models]#baseline-models
  - [Naive]#naive
  - [SeasonalNaive]#seasonalnaive
  - [RandomWalkWithDrift]#randomwalkwithdrift
  - [HistoricAverage]#historicaverage
  - [WindowAverage]#windowaverage
  - [SeasonalWindowAverage]#seasonalwindowaverage
- [Exponential Smoothing]#exponential-smoothing
  - [SimpleExponentialSmoothing]#simpleexponentialsmoothing
  - [Holt]#holt
  - [HoltWinters]#holtwinters
  - [ETS]#ets
  - [AutoETS]#autoets
  - [SeasonalES]#seasonales
- [ARIMA Models]#arima-models
  - [ARIMA]#arima
  - [SARIMA]#sarima
  - [AutoARIMA]#autoarima
- [Theta Models]#theta-models
  - [Theta]#theta
  - [OptimizedTheta]#optimizedtheta
  - [DynamicTheta]#dynamictheta
  - [DynamicOptimizedTheta]#dynamicoptimizedtheta
  - [AutoTheta]#autotheta
- [Intermittent Demand Models]#intermittent-demand-models
  - [Croston]#croston
  - [TSB]#tsb
  - [ADIDA]#adida
  - [IMAPA]#imapa
- [Advanced Models]#advanced-models
  - [MFLES]#mfles
  - [MSTLForecaster]#mstlforecaster
  - [TBATS]#tbats
  - [AutoTBATS]#autotbats
  - [GARCH]#garch
- [Ensemble]#ensemble
- [Decomposition]#decomposition
  - [STL]#stl
  - [MSTL]#mstl
- [Spectral Analysis]#spectral-analysis
  - [Welch Periodogram]#welch-periodogram
- [Feature Extraction]#feature-extraction
- [Transformations]#transformations
- [Validation]#validation
- [Changepoint Detection]#changepoint-detection
- [Utilities]#utilities
- [Probabilistic Postprocessing]#probabilistic-postprocessing
  - [PointForecasts]#pointforecasts
  - [QuantileForecasts]#quantileforecasts
  - [PredictionIntervals]#predictionintervals
  - [ConformalPredictor]#conformalpredictor
  - [HistoricalSimulator]#historicalsimulator
  - [NormalPredictor]#normalpredictor
  - [IDRPredictor]#idrpredictor
  - [QRAPredictor]#qrapredictor
  - [PostProcessor]#postprocessor
  - [Backtesting]#backtesting
  - [Conformalize]#conformalize

---

## Core Types

### TimeSeries

Container for time series data with timestamps and multivariate values.

```rust
pub struct TimeSeries {
    // Fields are private, use methods to access
}
```

#### Constructor Methods

| Method | Description |
|--------|-------------|
| `TimeSeries::new(timestamps, values, labels)` | Create with full configuration |
| `TimeSeries::univariate(values)` | Create simple single-dimension series |

#### Key Methods

| Method | Returns | Description |
|--------|---------|-------------|
| `len()` | `usize` | Number of observations |
| `dimensions()` | `usize` | Number of dimensions |
| `is_empty()` | `bool` | Check if series is empty |
| `is_multivariate()` | `bool` | Check if multi-dimensional |
| `timestamps()` | `&[DateTime<Utc>]` | Get timestamps |
| `values(dimension)` | `Result<&[f64]>` | Get values for dimension |
| `primary_values()` | `&[f64]` | Get first dimension values |
| `slice(start, end)` | `Result<TimeSeries>` | Extract subsequence |
| `has_missing_values()` | `bool` | Check for NaN/Inf |
| `missing_mask()` | `Vec<bool>` | Boolean mask: true where NaN/Inf (primary dimension) |
| `missing_count()` | `Vec<usize>` | Count of missing values per dimension |
| `interpolated(fill_edges)` | `TimeSeries` | Linear interpolation for NaN values |
| `sanitized(policy)` | `Result<TimeSeries>` | Apply missing value policy |
| `imputed_forward_backward()` | `TimeSeries` | Forward-fill then backward-fill |
| `imputed_moving_average(window)` | `Result<TimeSeries>` | Centered moving average imputation |
| `imputed_seasonal(period)` | `Result<TimeSeries>` | Seasonal median imputation |
| `with_imputed_regressors(policy)` | `Result<TimeSeries>` | Impute NaN in regressor vectors |

[Back to top](#api-reference)

---

### TimeSeriesBuilder

Builder pattern for constructing TimeSeries.

```rust
let ts = TimeSeriesBuilder::new()
    .timestamps(timestamps)
    .values(values)
    .frequency(Duration::days(1))
    .build()?;
```

| Method | Description |
|--------|-------------|
| `new()` | Create new builder |
| `timestamps(Vec<DateTime<Utc>>)` | Set timestamps |
| `values(Vec<f64>)` | Set univariate values |
| `multivariate_values(Vec<Vec<f64>>, ValueLayout)` | Set multivariate values |
| `labels(Vec<String>)` | Set dimension labels |
| `frequency(Duration)` | Set time frequency |
| `build()` | Build the TimeSeries |

[Back to top](#api-reference)

---

### Forecast

Prediction output containing point forecasts and optional confidence intervals.

```rust
pub struct Forecast {
    // Fields are private, use methods to access
}
```

#### Constructor Methods

| Method | Description |
|--------|-------------|
| `Forecast::new()` | Create empty forecast |
| `Forecast::from_values(values)` | Create from point forecasts |
| `Forecast::from_values_with_intervals(values, lower, upper)` | Create with intervals |

#### Key Methods

| Method | Returns | Description |
|--------|---------|-------------|
| `horizon()` | `usize` | Number of forecast steps |
| `primary()` | `&[f64]` | Get point forecasts |
| `lower()` | `Option<&[Vec<f64>]>` | Get lower bounds |
| `upper()` | `Option<&[Vec<f64>]>` | Get upper bounds |
| `has_lower()` | `bool` | Check if lower bounds exist |
| `has_upper()` | `bool` | Check if upper bounds exist |

[Back to top](#api-reference)

---

### ForecastError

Error types for forecasting operations.

```rust
pub enum ForecastError {
    EmptyData,
    InsufficientData { needed: usize, got: usize, hint: Option<String> },
    InvalidParameter(String),
    DimensionMismatch { expected: usize, got: usize },
    FitRequired,
    MissingValues,
    ComputationError(String),
    // ... other variants
}
```

| Variant | Description |
|---------|-------------|
| `EmptyData` | Input data is empty |
| `InsufficientData` | Not enough data points |
| `InvalidParameter` | Invalid parameter value |
| `DimensionMismatch` | Dimension mismatch in data |
| `FitRequired` | Model not fitted before prediction |
| `MissingValues` | Missing values detected |
| `ComputationError` | Numerical computation error |

[Back to top](#api-reference)

---

## Missing Value Imputation

Tools for handling NaN/Inf values before model fitting. All models reject missing values at `fit()` time, so imputation must be applied beforehand.

### MissingValuePolicy

```rust
pub enum MissingValuePolicy {
    Drop,           // Remove observations with NaN/Inf
    Fill(f64),      // Replace with specific value
    ForwardFill,    // Carry last valid value forward
    BackwardFill,   // Carry next valid value backward
    FillMean,       // Replace with mean of finite values
    FillMedian,     // Replace with median of finite values
    Interpolate,    // Linear interpolation (edges filled)
    Error,          // Return error if any missing
}
```

**Usage:**
```rust
use anofox_forecast::core::{TimeSeries, MissingValuePolicy};

// Apply policy via sanitized()
let clean = ts.sanitized(MissingValuePolicy::FillMean)?;
let clean = ts.sanitized(MissingValuePolicy::BackwardFill)?;
let clean = ts.sanitized(MissingValuePolicy::Interpolate)?;
```

### Imputation Methods

| Method | Description |
|--------|-------------|
| `sanitized(policy)` | Apply any `MissingValuePolicy` variant |
| `imputed_forward_backward()` | Forward-fill then backward-fill — handles both leading and trailing NaN |
| `imputed_moving_average(window)` | Centered window mean with multi-pass for adjacent gaps. Window must be odd. Remaining NaN filled with global mean. |
| `imputed_seasonal(period)` | Fill NaN with median of same seasonal position across cycles. Requires at least 1 full cycle. Errors if >50% missing in any bucket. |
| `with_imputed_regressors(policy)` | Apply fill policy to each regressor vector independently. Supports `Fill`, `ForwardFill`, `BackwardFill`, `FillMean`, `FillMedian`, `Interpolate`. |

### Metadata Helpers

| Method | Returns | Description |
|--------|---------|-------------|
| `has_missing_values()` | `bool` | True if any NaN/Inf in any dimension |
| `missing_mask()` | `Vec<bool>` | Per-observation mask for primary dimension |
| `missing_count()` | `Vec<usize>` | Count of NaN/Inf per dimension |

**Example — seasonal imputation:**
```rust
// Weekly data with gaps
let clean = ts.imputed_seasonal(7)?;  // Fill using same-weekday median
```

**Example — regressor imputation:**
```rust
let clean = ts.with_imputed_regressors(MissingValuePolicy::FillMean)?;
```

[Back to top](#api-reference)

---

## Forecaster Trait

Main trait interface that all forecasting models implement.

```rust
pub trait Forecaster {
    fn fit(&mut self, series: &TimeSeries) -> Result<()>;
    fn predict(&self, horizon: usize) -> Result<Forecast>;
    fn predict_with_intervals(&self, horizon: usize, level: f64) -> Result<Forecast>;
    fn fitted_values(&self) -> Option<&[f64]>;
    fn residuals(&self) -> Option<&[f64]>;
    fn name(&self) -> &str;
    fn is_fitted(&self) -> bool;
}
```

| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| `fit` | `series: &TimeSeries` | `Result<()>` | Fit model to data |
| `predict` | `horizon: usize` | `Result<Forecast>` | Generate point forecasts |
| `predict_with_intervals` | `horizon: usize, level: f64` | `Result<Forecast>` | Forecasts with confidence intervals |
| `fitted_values` | - | `Option<&[f64]>` | Get in-sample fitted values |
| `residuals` | - | `Option<&[f64]>` | Get residuals (actual - fitted) |
| `name` | - | `&str` | Model name |
| `is_fitted` | - | `bool` | Check if model is fitted |

[Back to top](#api-reference)

---

## Baseline Models

### Naive

Repeats the last observed value for all forecast horizons.

```rust
pub struct Naive;

impl Naive {
    pub fn new() -> Self;
}
```

**Example:**
```rust
let mut model = Naive::new();
model.fit(&ts)?;
let forecast = model.predict(12)?;
```

[Back to top](#api-reference)

---

### SeasonalNaive

Repeats values from the same season in the previous cycle.

```rust
pub struct SeasonalNaive {
    period: usize,
}

impl SeasonalNaive {
    pub fn new(period: usize) -> Self;
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `period` | `usize` | Seasonal period (e.g., 12 for monthly data) |

[Back to top](#api-reference)

---

### RandomWalkWithDrift

Random walk model with trend drift component.

```rust
pub struct RandomWalkWithDrift;

impl RandomWalkWithDrift {
    pub fn new() -> Self;
}
```

The drift is estimated as the average change between consecutive observations.

[Back to top](#api-reference)

---

### HistoricAverage

Forecasts the mean of all historical observations.

```rust
pub struct HistoricAverage;

impl HistoricAverage {
    pub fn new() -> Self;
}
```

[Back to top](#api-reference)

---

### WindowAverage

Moving window average forecaster.

```rust
pub struct WindowAverage {
    window: usize,
}

impl WindowAverage {
    pub fn new(window: usize) -> Self;
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `window` | `usize` | Number of observations to average |

[Back to top](#api-reference)

---

### SeasonalWindowAverage

Seasonal window-based averaging.

```rust
pub struct SeasonalWindowAverage {
    period: usize,
    window: usize,
}

impl SeasonalWindowAverage {
    pub fn new(period: usize, window: usize) -> Self;
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `period` | `usize` | Seasonal period |
| `window` | `usize` | Number of seasonal cycles to average |

[Back to top](#api-reference)

---

## Exponential Smoothing

### SimpleExponentialSmoothing

Simple exponential smoothing for non-seasonal, non-trending data.

```rust
pub struct SimpleExponentialSmoothing {
    alpha: Option<f64>,
}

impl SimpleExponentialSmoothing {
    pub fn new(alpha: f64) -> Self;
    pub fn auto() -> Self;
    pub fn alpha(&self) -> Option<f64>;
    pub fn level(&self) -> Option<f64>;
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `alpha` | `f64` | Smoothing parameter (0 < alpha < 1) |

| Method | Returns | Description |
|--------|---------|-------------|
| `auto()` | `Self` | Create with auto-optimized alpha |
| `alpha()` | `Option<f64>` | Get fitted alpha value |
| `level()` | `Option<f64>` | Get final level |

[Back to top](#api-reference)

---

### Holt

Holt's linear trend method (double exponential smoothing).

```rust
pub struct Holt {
    alpha: Option<f64>,
    beta: Option<f64>,
}

impl Holt {
    pub fn new(alpha: f64, beta: f64) -> Self;
    pub fn auto() -> Self;
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `alpha` | `f64` | Level smoothing (0 < alpha < 1) |
| `beta` | `f64` | Trend smoothing (0 < beta < 1) |

[Back to top](#api-reference)

---

### HoltWinters

Holt-Winters seasonal exponential smoothing.

```rust
pub struct HoltWinters {
    period: usize,
    seasonal_type: SeasonalType,
    alpha: Option<f64>,
    beta: Option<f64>,
    gamma: Option<f64>,
}

impl HoltWinters {
    pub fn new(period: usize, seasonal_type: SeasonalType) -> Self;
    pub fn with_params(period: usize, seasonal_type: SeasonalType,
                       alpha: f64, beta: f64, gamma: f64) -> Self;
    pub fn auto(period: usize, seasonal_type: SeasonalType) -> Self;
}

pub enum SeasonalType {
    Additive,
    Multiplicative,
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `period` | `usize` | Seasonal period |
| `seasonal_type` | `SeasonalType` | Additive or Multiplicative |
| `alpha` | `f64` | Level smoothing |
| `beta` | `f64` | Trend smoothing |
| `gamma` | `f64` | Seasonal smoothing |

[Back to top](#api-reference)

---

### ETS

Error-Trend-Seasonal state-space model following the [FPP3 taxonomy](https://otexts.com/fpp3/taxonomy.html).

```rust
pub struct ETS {
    spec: ETSSpec,
}

impl ETS {
    pub fn new(spec: ETSSpec, period: usize) -> Self;
}

pub struct ETSSpec {
    pub error: ErrorType,
    pub trend: TrendType,
    pub seasonal: SeasonalType,
}

pub enum ErrorType { Additive, Multiplicative }
pub enum TrendType { None, Additive, AdditiveDamped }
pub enum SeasonalType { None, Additive, Multiplicative }
```

#### ETS Model Taxonomy

This implementation follows the ETS taxonomy from [Forecasting: Principles and Practice (FPP3)](https://otexts.com/fpp3/taxonomy.html).

**Valid ETS Specifications (16 of 18 combinations):**

| Code | Name | Constructor |
|------|------|-------------|
| ANN | Simple exponential smoothing | `ETSSpec::ann()` |
| AAN | Holt's linear method | `ETSSpec::aan()` |
| AAdN | Additive damped trend | `ETSSpec::aadn()` |
| ANA | Seasonal (no trend, additive) | `ETSSpec::ana()` |
| ANM | Seasonal (no trend, multiplicative) | `ETSSpec::anm()` |
| AAA | Holt-Winters additive | `ETSSpec::aaa()` |
| AAM | Holt-Winters multiplicative seasonal | `ETSSpec::aam()` |
| AAdA | Damped Holt-Winters additive | `ETSSpec::aada()` |
| AAdM | Damped Holt-Winters multiplicative | `ETSSpec::aadm()` |
| MNN | Multiplicative error simple smoothing | `ETSSpec::mnn()` |
| MAN | Multiplicative error with trend | `ETSSpec::man()` |
| MAdN | Multiplicative error damped trend | `ETSSpec::madn()` |
| MNM | Multiplicative error and seasonal | `ETSSpec::mnm()` |
| MAM | Multiplicative Holt-Winters | `ETSSpec::mam()` |
| MAdM | Damped multiplicative Holt-Winters | `ETSSpec::madm()` |

**Invalid/Unstable (rejected):**

| Code | Reason |
|------|--------|
| MAA | Multiplicative error + additive trend + additive seasonal |
| MAdA | Multiplicative error + damped trend + additive seasonal |

#### Parsing ETS Notation

```rust
impl ETSSpec {
    /// Parse from notation string like "AAA", "MAM", "AAdM"
    pub fn from_notation(notation: &str) -> Result<Self>;

    /// Check if this combination is valid
    pub fn is_valid(&self) -> bool;
}
```

**Example:**
```rust
use anofox_forecast::models::exponential::ETSSpec;

// Parse notation
let spec = ETSSpec::from_notation("AAA")?;  // Holt-Winters additive
let spec = ETSSpec::from_notation("MAdM")?; // Damped multiplicative

// Invalid combinations return error
assert!(ETSSpec::from_notation("MAA").is_err());
```

[Back to top](#api-reference)

---

### AutoETS

Automatic ETS model selection using information criteria.

```rust
pub struct AutoETS {
    config: AutoETSConfig,
}

impl AutoETS {
    pub fn new() -> Self;
    pub fn with_config(config: AutoETSConfig) -> Self;
    pub fn with_period(period: usize) -> Self;
}

pub struct AutoETSConfig {
    pub criterion: SelectionCriterion,
    pub seasonal_period: Option<usize>,
    pub allow_multiplicative: bool,
}

pub enum SelectionCriterion { AIC, BIC, AICc }
```

[Back to top](#api-reference)

---

### SeasonalES

Multiplicative seasonal exponential smoothing.

```rust
pub struct SeasonalES {
    period: usize,
}

impl SeasonalES {
    pub fn new(period: usize) -> Self;
}
```

[Back to top](#api-reference)

---

## ARIMA Models

### ARIMA

Non-seasonal ARIMA(p,d,q) model.

```rust
pub struct ARIMA {
    spec: ARIMASpec,
}

impl ARIMA {
    pub fn new(p: usize, d: usize, q: usize) -> Self;
    pub fn spec(&self) -> &ARIMASpec;
    pub fn ar_coefficients(&self) -> &[f64];
    pub fn ma_coefficients(&self) -> &[f64];
    pub fn intercept(&self) -> f64;
    pub fn aic(&self) -> Option<f64>;
    pub fn bic(&self) -> Option<f64>;
}

pub struct ARIMASpec {
    pub p: usize,  // AR order
    pub d: usize,  // Differencing order
    pub q: usize,  // MA order
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `p` | `usize` | Autoregressive order |
| `d` | `usize` | Differencing order |
| `q` | `usize` | Moving average order |

[Back to top](#api-reference)

---

### SARIMA

Seasonal ARIMA(p,d,q)(P,D,Q)\[s\] model.

```rust
pub struct SARIMA {
    spec: SARIMASpec,
}

impl SARIMA {
    pub fn new(p: usize, d: usize, q: usize,
               cap_p: usize, cap_d: usize, cap_q: usize, s: usize) -> Self;
}

pub struct SARIMASpec {
    pub p: usize, pub d: usize, pub q: usize,       // Non-seasonal
    pub cap_p: usize, pub cap_d: usize, pub cap_q: usize,  // Seasonal
    pub s: usize,  // Seasonal period
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `p, d, q` | `usize` | Non-seasonal orders |
| `P, D, Q` | `usize` | Seasonal orders |
| `s` | `usize` | Seasonal period |

[Back to top](#api-reference)

---

### AutoARIMA

Automatic ARIMA order selection.

```rust
pub struct AutoARIMA {
    config: AutoARIMAConfig,
}

impl AutoARIMA {
    pub fn new() -> Self;
    pub fn with_config(config: AutoARIMAConfig) -> Self;
}

pub struct AutoARIMAConfig {
    pub max_p: usize,
    pub max_d: usize,
    pub max_q: usize,
    pub seasonal_period: Option<usize>,
    pub criterion: SelectionCriterion,
    pub stepwise: bool,
    pub true_stepwise: bool,  // Neighbor-based hill climbing
}

impl AutoARIMAConfig {
    pub fn with_true_stepwise(self, enabled: bool) -> Self;
    pub fn exhaustive(self) -> Self;
}
```

| Parameter | Description |
|-----------|-------------|
| `stepwise` | Use stepwise search (faster, fewer models) |
| `true_stepwise` | Use neighbor-based hill climbing (60-70% fewer evaluations) |

**Parallel Execution:**

Enable with `--features parallel` for 4-8x speedup on multi-core systems:
```toml
[dependencies]
anofox-forecast = { version = "0.3", features = ["parallel"] }
```

[Back to top](#api-reference)

---

## Theta Models

### Theta

Standard Theta Model (STM) for forecasting.

```rust
pub struct Theta {
    theta: f64,
    seasonal_period: usize,
    decomposition: DecompositionType,
}

impl Theta {
    pub fn new() -> Self;
    pub fn with_theta(theta: f64) -> Self;
    pub fn seasonal(period: usize) -> Self;
    pub fn seasonal_with_type(period: usize, decomposition: DecompositionType) -> Self;
}

pub enum DecompositionType {
    Additive,
    Multiplicative,
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `theta` | `f64` | Theta parameter (default: 2.0) |
| `period` | `usize` | Seasonal period (0 for non-seasonal) |
| `decomposition` | `DecompositionType` | Seasonal decomposition type |

[Back to top](#api-reference)

---

### OptimizedTheta

Theta model with optimized alpha and theta parameters.

```rust
pub struct OptimizedTheta;

impl OptimizedTheta {
    pub fn new() -> Self;
}
```

Parameters are optimized using Nelder-Mead minimization of MSE.

[Back to top](#api-reference)

---

### DynamicTheta

Theta with dynamic linear coefficient updates.

```rust
pub struct DynamicTheta {
    period: Option<usize>,
}

impl DynamicTheta {
    pub fn new(period: Option<usize>) -> Self;
}
```

[Back to top](#api-reference)

---

### DynamicOptimizedTheta

Combines dynamic updates with parameter optimization.

```rust
pub struct DynamicOptimizedTheta {
    period: Option<usize>,
}

impl DynamicOptimizedTheta {
    pub fn new(period: Option<usize>) -> Self;
}
```

[Back to top](#api-reference)

---

### AutoTheta

Automatic Theta model selection.

```rust
pub struct AutoTheta;

impl AutoTheta {
    pub fn new() -> Self;
}
```

Selects the best Theta variant based on cross-validation performance.

[Back to top](#api-reference)

---

## Intermittent Demand Models

### Croston

Croston's method for intermittent demand forecasting.

```rust
pub struct Croston {
    variant: CrostonVariant,
    alpha: f64,
}

impl Croston {
    pub fn new() -> Self;           // Classic variant
    pub fn classic() -> Self;
    pub fn sba() -> Self;           // Syntetos-Babai adjusted
    pub fn with_alpha(alpha: f64) -> Self;
}

pub enum CrostonVariant {
    Classic,
    SBA,  // Syntetos-Babai Approximation
}
```

| Variant | Description |
|---------|-------------|
| `Classic` | Original Croston method |
| `SBA` | Bias-corrected Syntetos-Babai variant |

[Back to top](#api-reference)

---

### TSB

Teunter-Syntetos-Babai method for intermittent demand.

```rust
pub struct TSB {
    alpha: f64,
    beta: f64,
}

impl TSB {
    pub fn new() -> Self;
    pub fn with_params(alpha: f64, beta: f64) -> Self;
}
```

[Back to top](#api-reference)

---

### ADIDA

Aggregate-Disaggregate Intermittent Demand Approach.

```rust
pub struct ADIDA {
    aggregation_level: usize,
}

impl ADIDA {
    pub fn new() -> Self;
    pub fn with_aggregation(level: usize) -> Self;
}
```

[Back to top](#api-reference)

---

### IMAPA

Intermittent Multiple Aggregation Prediction Algorithm.

```rust
pub struct IMAPA;

impl IMAPA {
    pub fn new() -> Self;
}
```

Combines forecasts from multiple aggregation levels.

[Back to top](#api-reference)

---

## Advanced Models

### MFLES

Multiple Fourier Linear Exponential Smoothing - gradient boosted decomposition.

```rust
pub struct MFLES {
    seasonal_periods: Vec<usize>,
}

impl MFLES {
    pub fn new(seasonal_periods: Vec<usize>) -> Self;
    pub fn with_max_rounds(rounds: usize) -> Self;
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `seasonal_periods` | `Vec<usize>` | Seasonal periods to model |
| `max_rounds` | `usize` | Maximum boosting iterations |

[Back to top](#api-reference)

---

### MSTLForecaster

MSTL decomposition-based forecaster for multiple seasonalities.

```rust
pub struct MSTLForecaster {
    seasonal_periods: Vec<usize>,
}

impl MSTLForecaster {
    pub fn new(seasonal_periods: Vec<usize>) -> Self;
}
```

[Back to top](#api-reference)

---

### TBATS

Trigonometric seasonality, Box-Cox transformation, ARMA errors, Trend, Seasonal components.

```rust
pub struct TBATS {
    seasonal_periods: Vec<usize>,
}

impl TBATS {
    pub fn new(seasonal_periods: Vec<usize>) -> Self;
}
```

Handles complex seasonal patterns with trigonometric representation.

[Back to top](#api-reference)

---

### AutoTBATS

Automatic TBATS configuration selection.

```rust
pub struct AutoTBATS;

impl AutoTBATS {
    pub fn new(seasonal_periods: Vec<usize>) -> Self;
}
```

[Back to top](#api-reference)

---

### GARCH

Generalized Autoregressive Conditional Heteroskedasticity for volatility modeling.

```rust
pub struct GARCH {
    p: usize,
    q: usize,
}

impl GARCH {
    pub fn new(p: usize, q: usize) -> Self;
}
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `p` | `usize` | GARCH order (variance lags) |
| `q` | `usize` | ARCH order (squared residual lags) |

[Back to top](#api-reference)

---

## Ensemble

Combines multiple forecasting models.

```rust
pub struct Ensemble {
    models: Vec<Box<dyn Forecaster>>,
    method: CombinationMethod,
}

impl Ensemble {
    pub fn new(models: Vec<Box<dyn Forecaster>>) -> Self;
    pub fn with_method(method: CombinationMethod) -> Self;
    pub fn with_weights(weights: Vec<f64>) -> Self;
}

pub enum CombinationMethod {
    Mean,
    Median,
    WeightedMSE,
    Custom,
}
```

| Method | Description |
|--------|-------------|
| `Mean` | Simple average of forecasts |
| `Median` | Median of forecasts |
| `WeightedMSE` | Inverse MSE weighting |
| `Custom` | User-provided weights |

[Back to top](#api-reference)

---

## Decomposition

### STL

Seasonal-Trend decomposition using LOESS.

```rust
pub struct STL {
    period: usize,
}

impl STL {
    pub fn new(period: usize) -> Self;
    pub fn decompose(&self, series: &[f64]) -> Result<STLResult>;
}

pub struct STLResult {
    pub seasonal: Vec<f64>,
    pub trend: Vec<f64>,
    pub remainder: Vec<f64>,
}
```

[Back to top](#api-reference)

---

### MSTL

Multiple Seasonal-Trend decomposition using LOESS.

```rust
pub struct MSTL {
    periods: Vec<usize>,
}

impl MSTL {
    pub fn new(periods: Vec<usize>) -> Self;
    pub fn decompose(&self, series: &[f64]) -> Result<MSTLResult>;
}

pub struct MSTLResult {
    pub seasonal_components: Vec<Vec<f64>>,
    pub trend: Vec<f64>,
    pub remainder: Vec<f64>,
}
```

[Back to top](#api-reference)

---

## Spectral Analysis

### Welch Periodogram

Welch's method for reduced variance spectral estimation using overlapping windowed segments.

```rust
/// Welch's periodogram for reduced variance spectral estimation
pub fn welch_periodogram(
    signal: &[f64],
    window_size: usize,  // Segment size (power of 2 recommended)
    overlap: f64,        // Overlap ratio (0.0-0.9, typically 0.5)
) -> Vec<(usize, f64)>;
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `signal` | `&[f64]` | Input time series |
| `window_size` | `usize` | Segment size (power of 2 for efficiency) |
| `overlap` | `f64` | Overlap ratio between segments (0.0-0.9) |

**Returns:** Vector of `(period, power)` tuples sorted by period (largest first).

**Example:**
```rust
use anofox_forecast::detection::welch_periodogram;

let signal: Vec<f64> = (0..256)
    .map(|i| (2.0 * std::f64::consts::PI * i as f64 / 12.0).sin())
    .collect();

let psd = welch_periodogram(&signal, 64, 0.5);
if let Some((period, _)) = psd.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap()) {
    println!("Dominant period: {}", period);
}
```

> **Note:** For comprehensive periodicity detection (ACF, FFT, Autoperiod, CFD-Autoperiod, SAZED),
> see the [fdars](https://crates.io/crates/fdars-core) crate.

[Back to top](#api-reference)

---

## Feature Extraction

The crate provides 76+ time series features organized by category.

### Basic Features

```rust
pub fn mean(series: &[f64]) -> f64;
pub fn median(series: &[f64]) -> f64;
pub fn variance(series: &[f64]) -> f64;
pub fn standard_deviation(series: &[f64]) -> f64;
pub fn minimum(series: &[f64]) -> f64;
pub fn maximum(series: &[f64]) -> f64;
pub fn sum_values(series: &[f64]) -> f64;
pub fn abs_energy(series: &[f64]) -> f64;
pub fn mean_abs_change(series: &[f64]) -> f64;
pub fn mean_change(series: &[f64]) -> f64;
```

### Distribution Features

```rust
pub fn skewness(series: &[f64]) -> f64;
pub fn kurtosis(series: &[f64]) -> f64;
pub fn quantile(series: &[f64], q: f64) -> f64;
pub fn variation_coefficient(series: &[f64]) -> f64;
```

### Autocorrelation Features

```rust
pub fn autocorrelation(series: &[f64], lag: usize) -> f64;
pub fn partial_autocorrelation(series: &[f64], lag: usize) -> f64;
```

### Entropy Features

```rust
pub fn approximate_entropy(series: &[f64], m: usize, r: f64) -> f64;
pub fn sample_entropy(series: &[f64], m: usize, r: f64) -> f64;
pub fn permutation_entropy(series: &[f64], order: usize) -> f64;
```

### Complexity Features

```rust
pub fn cid_ce(series: &[f64], normalize: bool) -> f64;
pub fn lempel_ziv_complexity(series: &[f64], threshold: Option<f64>) -> f64;
```

### Trend Features

```rust
pub fn linear_trend(series: &[f64]) -> LinearTrendResult;
pub fn ar_coefficient(series: &[f64], k: usize) -> f64;
```

[Back to top](#api-reference)

---

## Transformations

### Box-Cox

```rust
pub fn boxcox(series: &[f64], lambda: f64) -> Result<BoxCoxResult>;
pub fn boxcox_auto(series: &[f64]) -> Result<BoxCoxResult>;
pub fn inv_boxcox(transformed: &[f64], lambda: f64) -> Result<Vec<f64>>;
pub fn boxcox_lambda(series: &[f64]) -> Result<f64>;

pub struct BoxCoxResult {
    pub transformed: Vec<f64>,
    pub lambda: f64,
}
```

### Scaling

```rust
pub fn standardize(series: &[f64]) -> ScaleResult;
pub fn normalize(series: &[f64]) -> ScaleResult;
pub fn robust_scale(series: &[f64]) -> ScaleResult;

pub struct ScaleResult {
    pub scaled: Vec<f64>,
    pub mean: f64,
    pub std: f64,
}
```

### Window Functions

```rust
pub fn rolling_mean(series: &[f64], window: usize, center: bool) -> Vec<f64>;
pub fn rolling_std(series: &[f64], window: usize, center: bool) -> Vec<f64>;
pub fn rolling_min(series: &[f64], window: usize, center: bool) -> Vec<f64>;
pub fn rolling_max(series: &[f64], window: usize, center: bool) -> Vec<f64>;
pub fn expanding_mean(series: &[f64]) -> Vec<f64>;
pub fn ewm_mean(series: &[f64], span: f64) -> Vec<f64>;
```

[Back to top](#api-reference)

---

## Validation

### Residual Tests

```rust
pub fn ljung_box(residuals: &[f64], nlags: Option<usize>, seasonal: usize) -> LjungBoxResult;
pub fn box_pierce(residuals: &[f64], nlags: Option<usize>, seasonal: usize) -> LjungBoxResult;
pub fn durbin_watson(residuals: &[f64]) -> DurbinWatsonResult;

pub struct LjungBoxResult {
    pub statistic: f64,
    pub p_value: f64,
    pub degrees_of_freedom: usize,
}

pub struct DurbinWatsonResult {
    pub statistic: f64,  // Values near 2 indicate no autocorrelation
}
```

### Stationarity Tests

```rust
pub fn adf_test(series: &[f64], nlags: Option<usize>) -> StationarityResult;
pub fn kpss_test(series: &[f64], nlags: Option<usize>) -> StationarityResult;

pub struct StationarityResult {
    pub test_statistic: f64,
    pub p_value: f64,
    pub is_stationary: bool,
}
```

[Back to top](#api-reference)

---

## Changepoint Detection

PELT (Pruned Exact Linear Time) algorithm for changepoint detection.

```rust
pub fn pelt_detect(series: &[f64], config: &PeltConfig) -> PeltResult;

pub struct PeltConfig {
    pub penalty: f64,
    pub min_segment_length: usize,
    pub cost_fn: CostFunction,
}

impl PeltConfig {
    pub fn default() -> Self;
    pub fn penalty(penalty: f64) -> Self;
    pub fn with_bic_penalty(n: usize) -> Self;
}

pub enum CostFunction {
    L2,           // Squared cost (default)
    L1,           // Absolute cost, robust to outliers
    Normal,       // Normal likelihood
    Poisson,      // Poisson likelihood for count data
    LinearTrend,  // Detects slope/trend changes
    MeanVariance, // Joint mean and variance changes
    Cusum,        // Sustained mean shifts
}

pub struct PeltResult {
    pub changepoints: Vec<usize>,
    pub n_changepoints: usize,
}
```

[Back to top](#api-reference)

---

## Utilities

### Accuracy Metrics

```rust
pub fn calculate_metrics(actual: &[f64], predicted: &[f64],
                         seasonal_period: Option<usize>) -> Result<AccuracyMetrics>;

pub struct AccuracyMetrics {
    pub mae: f64,      // Mean Absolute Error
    pub mse: f64,      // Mean Squared Error
    pub rmse: f64,     // Root Mean Squared Error
    pub mape: f64,     // Mean Absolute Percentage Error
    pub smape: f64,    // Symmetric MAPE
    pub mase: f64,     // Mean Absolute Scaled Error
    pub r_squared: f64,
}
```

### Cross-Validation

```rust
pub fn cross_validate<F>(config: &CVConfig, series: &TimeSeries,
                         model_factory: F) -> Result<CVResults>;

pub struct CVConfig {
    pub horizon: usize,
    pub initial_window: usize,
    pub step_size: usize,
    pub strategy: CVStrategy,
}

pub enum CVStrategy {
    Rolling,    // Fixed window slides forward
    Expanding,  // Window grows over time
}

pub struct CVResults {
    pub n_folds: usize,
    pub aggregated: AggregatedMetrics,
    pub fold_metrics: Vec<AccuracyMetrics>,
}
```

### Optimization

```rust
pub fn nelder_mead(objective: fn(&[f64]) -> f64, initial: Vec<f64>,
                   config: &NelderMeadConfig) -> Result<NelderMeadResult>;

pub struct NelderMeadConfig {
    pub max_iter: usize,
    pub tolerance: f64,
}

pub struct NelderMeadResult {
    pub parameters: Vec<f64>,
    pub value: f64,
    pub iterations: usize,
}
```

[Back to top](#api-reference)

---

### Bootstrap Intervals

Bootstrap methods for empirical confidence intervals.

```rust
pub struct BootstrapConfig {
    pub n_samples: usize,      // Number of bootstrap samples (default: 1000)
    pub block_size: Option<usize>,  // Block size for block bootstrap
    pub seed: Option<u64>,     // Random seed for reproducibility
}

impl BootstrapConfig {
    pub fn new(n_samples: usize) -> Self;
    pub fn with_block_size(self, block_size: usize) -> Self;
    pub fn with_seed(self, seed: u64) -> Self;
}

pub struct BootstrapResult {
    pub lower: Vec<f64>,       // Lower bounds per horizon step
    pub upper: Vec<f64>,       // Upper bounds per horizon step
    pub level: f64,            // Confidence level used
    pub n_samples: usize,      // Number of samples used
}

/// Generate bootstrap confidence intervals
pub fn bootstrap_intervals<M: Forecaster + Clone>(
    model: &M,
    series: &TimeSeries,
    horizon: usize,
    level: f64,
    config: &BootstrapConfig,
) -> Result<BootstrapResult>;

/// Generate forecast with bootstrap intervals
pub fn bootstrap_forecast<M: Forecaster + Clone>(
    model: &M,
    series: &TimeSeries,
    horizon: usize,
    level: f64,
    config: &BootstrapConfig,
) -> Result<Forecast>;
```

| Method | Description |
|--------|-------------|
| Residual Bootstrap | Resamples fitted residuals with replacement |
| Block Bootstrap | Preserves autocorrelation structure |

**Example:**
```rust
use anofox_forecast::utils::bootstrap::{bootstrap_forecast, BootstrapConfig};

let config = BootstrapConfig::new(500).with_seed(42);
let forecast = bootstrap_forecast(&model, &ts, 12, 0.95, &config)?;
```

[Back to top](#api-reference)

---

## Probabilistic Postprocessing

The postprocessing module provides methods to convert point forecasts into calibrated
predictive distributions with coverage guarantees. It follows the approach of
[PostForecasts.jl](https://github.com/lipiecki/PostForecasts.jl).

### Core Types

#### PointForecasts

Point forecasts with optional timestamps and metadata.

```rust
pub struct PointForecasts {
    timestamps: Vec<DateTime<Utc>>,
    values: Vec<f64>,
    model_name: Option<String>,
}

impl PointForecasts {
    pub fn new(timestamps: Vec<DateTime<Utc>>, values: Vec<f64>) -> Result<Self>;
    pub fn from_values(values: Vec<f64>) -> Self;
    pub fn empty() -> Self;
    pub fn with_model_name(self, name: impl Into<String>) -> Self;
    pub fn len(&self) -> usize;
    pub fn values(&self) -> &[f64];
    pub fn timestamps(&self) -> &[DateTime<Utc>];
}
```

#### QuantileForecasts

Multi-quantile forecasts representing a discrete predictive distribution.

```rust
pub struct QuantileForecasts {
    timestamps: Vec<DateTime<Utc>>,
    quantiles: Vec<f64>,
    values: Vec<Vec<f64>>,  // values[time][quantile]
}

impl QuantileForecasts {
    pub fn new(timestamps: Vec<DateTime<Utc>>, quantiles: Vec<f64>, values: Vec<Vec<f64>>) -> Result<Self>;
    pub fn from_values(quantiles: Vec<f64>, values: Vec<Vec<f64>>) -> Result<Self>;
    pub fn n_times(&self) -> usize;
    pub fn n_quantiles(&self) -> usize;
    pub fn quantiles(&self) -> &[f64];
    pub fn at_time(&self, idx: usize) -> Option<&[f64]>;
    pub fn at_quantile(&self, idx: usize) -> Option<Vec<f64>>;
    pub fn median(&self) -> Option<Vec<f64>>;
    pub fn to_prediction_intervals(&self, coverage: f64) -> Option<PredictionIntervals>;
}
```

#### PredictionIntervals

Lower and upper bounds with coverage level.

```rust
pub struct PredictionIntervals {
    timestamps: Vec<DateTime<Utc>>,
    lower: Vec<f64>,
    upper: Vec<f64>,
    coverage: f64,
}

impl PredictionIntervals {
    pub fn new(timestamps: Vec<DateTime<Utc>>, lower: Vec<f64>, upper: Vec<f64>, coverage: f64) -> Result<Self>;
    pub fn from_bounds(lower: Vec<f64>, upper: Vec<f64>, coverage: f64) -> Result<Self>;
    pub fn lower(&self) -> &[f64];
    pub fn upper(&self) -> &[f64];
    pub fn coverage(&self) -> f64;
    pub fn widths(&self) -> Vec<f64>;
    pub fn midpoints(&self) -> Vec<f64>;
    pub fn contains(&self, values: &[f64]) -> Vec<bool>;
    pub fn empirical_coverage(&self, actuals: &[f64]) -> Option<f64>;
}
```

[Back to top](#api-reference)

---

### ConformalPredictor

Distribution-free prediction intervals with coverage guarantees.

```rust
pub struct ConformalPredictor {
    coverage: f64,
    method: ConformalMethod,
}

pub enum ConformalMethod {
    Split { cal_fraction: f64 },
    CrossVal { n_folds: usize },
    JackknifePlus,
}

impl ConformalPredictor {
    pub fn new(coverage: f64, method: ConformalMethod) -> Self;
    pub fn split(coverage: f64) -> Self;
    pub fn cross_val(coverage: f64, n_folds: usize) -> Self;
    pub fn jackknife_plus(coverage: f64) -> Self;
    pub fn fit(&self, forecasts: &[f64], actuals: &[f64]) -> Result<ConformalResult>;
    pub fn predict(&self, result: &ConformalResult, forecasts: &PointForecasts) -> PredictionIntervals;
    pub fn predict_values(&self, result: &ConformalResult, values: &[f64]) -> PredictionIntervals;
}

pub struct ConformalResult {
    pub fn scores(&self) -> &[f64];
    pub fn quantile_value(&self) -> f64;
    pub fn coverage(&self) -> f64;
    pub fn method(&self) -> &ConformalMethod;
}
```

| Method | Description |
|--------|-------------|
| `Split` | Fast method using a holdout calibration set |
| `CrossVal` | Uses all data via k-fold cross-validation |
| `JackknifePlus` | Leave-one-out with finite sample validity |

**Example:**
```rust
use anofox_forecast::postprocess::{ConformalPredictor, ConformalMethod, PointForecasts};

let predictor = ConformalPredictor::split(0.90);
let result = predictor.fit(&historical_forecasts, &historical_actuals)?;

let new_forecasts = PointForecasts::from_values(vec![20.0, 21.0, 22.0]);
let intervals = predictor.predict(&result, &new_forecasts);
```

[Back to top](#api-reference)

---

### HistoricalSimulator

Non-parametric empirical error distribution for uncertainty quantification.

```rust
pub struct HistoricalSimulator {
    quantiles: Vec<f64>,
    window_size: Option<usize>,
}

impl HistoricalSimulator {
    pub fn new(quantiles: Vec<f64>) -> Self;
    pub fn with_window(quantiles: Vec<f64>, window_size: usize) -> Self;
    pub fn fit(&self, forecasts: &[f64], actuals: &[f64]) -> Result<HistoricalSimResult>;
    pub fn predict_values(&self, result: &HistoricalSimResult, values: &[f64]) -> Result<QuantileForecasts>;
}
```

[Back to top](#api-reference)

---

### NormalPredictor

Gaussian error assumption baseline for uncertainty quantification.

```rust
pub struct NormalPredictor {
    quantiles: Vec<f64>,
}

impl NormalPredictor {
    pub fn new(quantiles: Vec<f64>) -> Self;
    pub fn fit(&self, forecasts: &[f64], actuals: &[f64]) -> Result<NormalResult>;
    pub fn predict_values(&self, result: &NormalResult, values: &[f64]) -> Result<QuantileForecasts>;
}
```

[Back to top](#api-reference)

---

### IDRPredictor

Isotonic Distributional Regression for state-of-the-art calibration.

```rust
pub struct IDRPredictor {
    quantiles: Vec<f64>,
}

impl IDRPredictor {
    pub fn new(quantiles: Vec<f64>) -> Self;
    pub fn fit(&self, forecasts: &[f64], actuals: &[f64]) -> Result<IDRResult>;
    pub fn predict_values(&self, result: &IDRResult, values: &[f64]) -> Result<QuantileForecasts>;
}
```

[Back to top](#api-reference)

---

### QRAPredictor

Quantile Regression Averaging for ensemble combining.

```rust
pub struct QRAPredictor {
    quantiles: Vec<f64>,
    regularization: QRARegularization,
}

pub enum QRARegularization {
    None,
    L1(f64),
    L2(f64),
}

impl QRAPredictor {
    pub fn new(quantiles: Vec<f64>) -> Self;
    pub fn with_regularization(quantiles: Vec<f64>, reg: QRARegularization) -> Self;
}
```

[Back to top](#api-reference)

---

### PostProcessor

Unified interface for all postprocessing methods.

```rust
pub struct PostProcessor {
    model: PostModel,
}

pub enum PostModel {
    Conformal { coverage: f64, method: ConformalMethod },
    HistoricalSim { quantiles: Vec<f64>, window_size: Option<usize> },
    Normal { quantiles: Vec<f64> },
    IDR { quantiles: Vec<f64> },
}

impl PostProcessor {
    pub fn new(model: PostModel) -> Self;
    pub fn conformal(coverage: f64) -> Self;
    pub fn historical_sim(quantiles: Vec<f64>) -> Self;
    pub fn normal(quantiles: Vec<f64>) -> Self;
    pub fn idr(quantiles: Vec<f64>) -> Self;
    pub fn train(&self, forecasts: &PointForecasts, actuals: &[f64]) -> Result<TrainedModel>;
    pub fn predict_intervals(&self, trained: &TrainedModel, forecasts: &PointForecasts) -> Result<PredictionIntervals>;
    pub fn predict_quantiles(&self, trained: &TrainedModel, forecasts: &PointForecasts) -> Result<QuantileForecasts>;
    pub fn point_to_quantiles(&self, train_forecasts: &PointForecasts, train_actuals: &[f64], predict_forecasts: &PointForecasts) -> Result<QuantileForecasts>;
}

pub enum TrainedModel {
    Conformal(ConformalResult),
    HistoricalSim(HistoricalSimResult),
    Normal(NormalResult),
    IDR(IDRResult),
}
```

**Example:**
```rust
use anofox_forecast::postprocess::{PostProcessor, PointForecasts};

// Create a conformal processor with 90% coverage
let processor = PostProcessor::conformal(0.90);

// Train on historical data
let train_forecasts = PointForecasts::from_values(historical_f);
let trained = processor.train(&train_forecasts, &historical_actuals)?;

// Generate prediction intervals
let new_forecasts = PointForecasts::from_values(new_f);
let intervals = processor.predict_intervals(&trained, &new_forecasts)?;
```

[Back to top](#api-reference)

---

### Backtesting

Rolling/expanding window backtesting with horizon-aware calibration.

```rust
pub struct BacktestConfig {
    pub initial_window: usize,
    pub step: usize,
    pub horizon: usize,
    pub expanding: bool,
    pub horizon_aware: bool,
}

impl BacktestConfig {
    pub fn new() -> Self;
    pub fn initial_window(self, size: usize) -> Self;
    pub fn step(self, step: usize) -> Self;
    pub fn horizon(self, horizon: usize) -> Self;
    pub fn expanding(self, expanding: bool) -> Self;
    pub fn horizon_aware(self, aware: bool) -> Self;
}

pub struct BacktestResult {
    pub fn n_folds(&self) -> usize;
    pub fn config(&self) -> &BacktestConfig;
    pub fn folds(&self) -> impl Iterator<Item = &BacktestFold>;
    pub fn coverage(&self) -> f64;
    pub fn calibration_error(&self, target_coverage: f64) -> f64;
    pub fn interval_widths(&self) -> f64;
    pub fn coverage_by_horizon(&self) -> &HashMap<usize, f64>;
    pub fn calibrated_model(&self, processor: &PostProcessor) -> Result<TrainedModel>;
    pub fn calibrated_model_by_horizon(&self, processor: &PostProcessor) -> Result<CalibratedModelByHorizon>;
}

pub struct BacktestFold {
    pub fold_idx: usize,
    pub train_start: usize,
    pub train_end: usize,
    pub test_start: usize,
    pub test_end: usize,
    pub intervals: PredictionIntervals,
    pub actuals: Vec<f64>,
    pub coverage: f64,
    pub avg_width: f64,
}
```

**Example:**
```rust
use anofox_forecast::postprocess::{PostProcessor, BacktestConfig, PointForecasts};

let processor = PostProcessor::conformal(0.90);

let config = BacktestConfig::new()
    .initial_window(100)
    .step(10)
    .horizon(7)
    .horizon_aware(true);

let forecasts = PointForecasts::from_values(all_forecasts);
let results = processor.backtest(&forecasts, &all_actuals, config)?;

println!("Coverage: {:.1}%", results.coverage() * 100.0);
println!("Calibration error: {:.3}", results.calibration_error(0.90));
```

[Back to top](#api-reference)

---

### Conformalize

Recalibrate quantile forecasts using conformal prediction.

```rust
pub fn conformalize(
    forecasts: &QuantileForecasts,
    calib_forecasts: &QuantileForecasts,
    calib_actuals: &[f64],
) -> Result<ConformalizeResult>;

pub fn conformalize_with_config(
    forecasts: &QuantileForecasts,
    calib_forecasts: &QuantileForecasts,
    calib_actuals: &[f64],
    config: ConformalizeConfig,
) -> Result<ConformalizeResult>;

pub struct ConformalizeConfig {
    method: ConformalMethod,
    symmetric: bool,
}

impl ConformalizeConfig {
    pub fn new() -> Self;
    pub fn method(self, method: ConformalMethod) -> Self;
    pub fn symmetric(self, symmetric: bool) -> Self;
}

pub struct ConformalizeResult {
    pub fn forecasts(&self) -> &QuantileForecasts;
    pub fn into_forecasts(self) -> QuantileForecasts;
    pub fn adjustments(&self) -> &[f64];
    pub fn original_coverage(&self) -> &[f64];
}
```

**Example:**
```rust
use anofox_forecast::postprocess::{conformalize, QuantileForecasts};

// Calibrate quantile forecasts
let calibrated = conformalize(&test_forecasts, &calib_forecasts, &calib_actuals)?;

// Get the recalibrated forecasts
let improved = calibrated.into_forecasts();
```

[Back to top](#api-reference)

---

## Prelude

Convenience re-exports for common usage:

```rust
pub use crate::core::{Forecast, TimeSeries};
pub use crate::error::{ForecastError, Result};
pub use crate::models::Forecaster;
pub use crate::utils::{calculate_metrics, AccuracyMetrics};
```

**Usage:**
```rust
use anofox_forecast::prelude::*;
```

[Back to top](#api-reference)