optionstratlib-pricing 0.22.1

Option pricing models, Greeks and implied volatility of OptionStratLib, on Decimal and Positive boundaries. Re-exported by the optionstratlib facade under its `pricing` feature.
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
use crate::error::PricingError;
use crate::pricing::utils::*;
use optionstratlib_core::f2d;
use optionstratlib_core::model::Positive;
use optionstratlib_core::model::decimal::{d_div, d_mul, d_sub};
use optionstratlib_core::model::payoff::{Payoff, PayoffInfo};
use optionstratlib_core::model::types::{OptionStyle, OptionType, Side};
use rust_decimal::Decimal;
use std::num::NonZeroUsize;
use tracing::instrument;

#[cfg(test)]
use optionstratlib_core::pos_or_panic;

type BinomialTreeResult = Result<(Vec<Vec<Decimal>>, Vec<Vec<Decimal>>), PricingError>;

/// Parameters for pricing options using the Binomial Tree model.
///
/// This structure encapsulates all the necessary parameters required to calculate
/// the price of an option using the binomial pricing model. The binomial model is
/// a discrete-time, lattice-based approach to option pricing that can handle various
/// option types and styles.
///
/// The model builds a tree of possible future asset prices to determine the option's
/// value at each node, working backwards from expiration to the present value.
/// This approach is particularly valuable for American options or other early-exercise
/// scenarios.
#[derive(Debug, Clone)]
pub struct BinomialPricingParams<'a> {
    /// The current price of the underlying asset, represented as a positive value.
    pub asset: Positive,

    /// The volatility of the underlying asset, expressed as a positive value.
    /// This represents the standard deviation of the asset's returns.
    pub volatility: Positive,

    /// The risk-free interest rate used in the pricing model.
    pub int_rate: Decimal,

    /// The strike price of the option, represented as a positive value.
    pub strike: Positive,

    /// The time to expiration of the option in years, represented as a positive value.
    pub expiry: Positive,

    /// The number of steps to use in the binomial tree calculation,
    /// as a [`NonZeroUsize`] so zero is structurally invalid at the
    /// type level. Higher values increase accuracy but also
    /// computational cost. See
    /// [`crate::pricing::constants::DEFAULT_BINOMIAL_STEPS`] for a sensible
    /// default.
    pub no_steps: NonZeroUsize,

    /// The type of option (European, American, etc.) which determines
    /// when the option can be exercised.
    pub option_type: &'a OptionType,

    /// The style of the option (Call or Put) which determines whether the option
    /// gives the right to buy or sell the underlying asset.
    pub option_style: &'a OptionStyle,

    /// Indicates whether the option position is long (buying the option) or
    /// short (selling/writing the option).
    pub side: &'a Side,
}

/// Calculates the price of an option using the binomial model.
///
/// This function implements the binomial model for option pricing,
/// which is a numerical method for estimating the price of both European and American options.
/// The model constructs a binomial tree of possible future underlying asset prices
/// and then recursively calculates the option value from the leaves to the root of the tree.
///
/// # Arguments
///
/// * `params` - A `BinomialPricingParams` struct containing all necessary pricing parameters:
///     - `asset`: Current price of the underlying asset.
///     - `volatility`: Annualized volatility of the underlying asset.
///     - `int_rate`: Annualized risk-free interest rate.
///     - `strike`: Strike price of the option.
///     - `expiry`: Time to expiration in years.
///     - `no_steps`: Number of steps in the binomial tree.
///     - `option_type`: Type of option (e.g., European, American).
///     - `option_style`: Style of the option (Call or Put).
///     - `side`: Side of the trade (Long or Short).
///
/// # Returns
///
/// Returns the calculated price of the option as a `Decimal`, negated for a
/// short `side`.
///
/// # Special cases
///
/// - If `expiry` is 0, the function returns the intrinsic value of the option.
/// - If `volatility` is 0, the underlying is deterministic and the price is
///   computed in closed form, which still honours early exercise: an American
///   is worth the better of exercising now and holding to expiry, a Bermuda
///   the best of its schedule, a European its discounted payoff.
///
/// # Notes
///
/// - The model's accuracy increases with the number of steps, but so does the computation time.
/// - This model assumes that the underlying asset follows a multiplicative binomial process.
/// - For American options, this model accounts for the possibility of early exercise.
///
/// # Cost
///
/// `no_steps` has no upper limit: the step count is the caller's choice and
/// so is its cost (#807). With `N = no_steps`:
///
/// - **Time** grows as `N²`. The `N + 1` terminal payoffs each take two
///   `Decimal` powers; backward induction then values `N (N + 1) / 2` nodes
///   with a few checked `Decimal` operations each, and an American or a
///   Bermuda exercise date adds two powers and a payoff per node, which
///   makes those contracts several times slower than a European and grow
///   somewhat faster than `N²`, as the powers' exponents grow with `N`.
///   Measured with Criterion (`cargo bench -p optionstratlib-pricing
///   --bench pricing -- pricing/binomial`) on an Apple M-series laptop, a
///   European takes about 2.2 ms at 200 steps and 47 ms at 1 000, an
///   American put 15 ms and 0.7 s; extrapolated at `N²`, at least 5 s and
///   70 s at 10 000 steps.
/// - **Memory** is one vector of `N + 1` `Decimal`s, `16 (N + 1)` bytes,
///   reserved before the first payoff is evaluated. A size the allocator
///   refuses is [`PricingError::InvalidParameter`] at once; a size it grants
///   is priced however long that takes, and nothing interrupts it.
///
/// Accuracy improves as `1/N` with the oscillation of the CRR tree, so a few
/// hundred to a few thousand steps cover most uses;
/// [`crate::pricing::constants::DEFAULT_BINOMIAL_STEPS`] is the library's
/// default.
///
/// # Errors
///
/// Returns [`PricingError::SqrtFailure`] when the up-factor exponent
/// produces an invalid `Decimal`, [`PricingError::BinomialNodeMissing`]
/// when the induction step cannot read an intermediate node,
/// [`PricingError::InvalidParameter`] when the `no_steps + 1` terminal
/// nodes cannot be allocated, and [`PricingError::Positive`] when any
/// `Positive` construction downstream (e.g. strike × discount factor)
/// underflows below zero.
#[instrument(skip(params), fields(
    strike = %params.strike,
    asset = %params.asset,
    steps = params.no_steps.get(),
    style = ?*params.option_style,
    side = ?*params.side,
))]
pub fn price_binomial(params: BinomialPricingParams) -> Result<Decimal, PricingError> {
    let mut info = PayoffInfo {
        spot: params.asset,
        strike: params.strike,
        style: *params.option_style,
        side: *params.side,
        spot_prices: None,
        spot_min: None,
        spot_max: None,
        exotic_params: None,
    };

    if params.expiry == Decimal::ZERO {
        let intrinsic_value = params.option_type.payoff(&info)?;
        return Ok(intrinsic_value);
    }
    if params.volatility == Decimal::ZERO {
        return price_deterministic(&params);
    }

    let no_steps_raw = params.no_steps.get();
    let dt = params
        .expiry
        .checked_div(&Positive::new(no_steps_raw as f64)?)?
        .to_dec();
    let u = calculate_up_factor(params.volatility, dt)?;
    let d = calculate_down_factor(params.volatility, dt)?;
    if u == d {
        // `σ√dt` underflowed below the representable scale, so the lattice has
        // collapsed onto a single deterministic path: same answer as the
        // zero-volatility branch above.
        return price_deterministic(&params);
    }
    let p = calculate_probability(params.int_rate, dt, d, u)?;
    let discount_factor = calculate_discount_factor(params.int_rate, dt)?;

    // The lattice is valued from the holder's side and the requested side is
    // applied once, to the root (#648). The early-exercise decision belongs to
    // the holder: `max(continuation, intrinsic)` over short-signed values
    // picked the writer's smaller liability, so a short American priced at
    // zero instead of the negated long price.
    let long_params = BinomialPricingParams {
        side: &Side::Long,
        ..params.clone()
    };
    info.side = Side::Long;

    let mut prices = reserve_nodes(no_steps_raw)?;
    let powers = LatticePowers::new(u, d, no_steps_raw)?;
    for i in 0..=no_steps_raw {
        prices.push(calculate_option_price(
            long_params.clone(),
            u,
            d,
            i,
            &powers,
        )?);
    }

    let half_dt = d_div(dt, Decimal::TWO, "pricing::binomial::half_dt")?;
    for step in (0..no_steps_raw).rev() {
        for i in 0..=step {
            let price_up = *i
                .checked_add(1)
                .and_then(|up| prices.get(up))
                .ok_or(PricingError::BinomialNodeMissing { node: "price_up" })?;
            let price_down = *prices
                .get(i)
                .ok_or(PricingError::BinomialNodeMissing { node: "price_down" })?;
            let option_value = option_node_value(p, price_up, price_down, discount_factor)?;
            let slot = prices
                .get_mut(i)
                .ok_or(PricingError::BinomialNodeMissing { node: "price_slot" })?;
            match params.option_type {
                OptionType::American => {
                    info.spot = lattice_spot(params.asset, u, d, i, step, &powers)?;
                    let intrinsic_value = params.option_type.payoff(&info)?;
                    *slot = option_value.max(intrinsic_value);
                }
                OptionType::Bermuda { exercise_dates } => {
                    // Calculate time at this step
                    let time_at_step = d_mul(
                        dt,
                        Decimal::from(step as u64),
                        "pricing::binomial::time_at_step",
                    )?;
                    // Check if this step is an exercise date
                    let mut is_exercise_date = false;
                    for exercise in exercise_dates {
                        let gap = d_sub(
                            time_at_step,
                            exercise.to_dec(),
                            "pricing::binomial::exercise_gap",
                        )?;
                        if gap.abs() < half_dt {
                            is_exercise_date = true;
                            break;
                        }
                    }
                    if is_exercise_date {
                        let spot = lattice_spot(params.asset, u, d, i, step, &powers)?;
                        let slot_value = option_value;
                        info.spot = spot;
                        let intrinsic_value = params.option_type.payoff(&info)?;
                        let slot = prices
                            .get_mut(i)
                            .ok_or(PricingError::BinomialNodeMissing { node: "price_slot" })?;
                        *slot = slot_value.max(intrinsic_value);
                    } else {
                        *slot = option_value;
                    }
                }
                OptionType::European => {
                    *slot = option_value;
                }
                _ => {
                    return Err(PricingError::other(
                        "OptionType not supported for binomial pricing",
                    ));
                }
            }
        }
    }
    let root = prices
        .first()
        .copied()
        .ok_or(PricingError::BinomialNodeMissing { node: "root" })?;
    Ok(match params.side {
        Side::Long => root,
        Side::Short => -root,
    })
}

/// Price of a contract whose underlying is deterministic.
///
/// With no volatility the underlying follows its forward, `S(t) = S · e^{r·t}`,
/// so exercising at `t` is worth `e^{-r·t} · payoff(S · e^{r·t})` today. Each
/// candidate exercise time is valued by [`calculate_discounted_payoff`] on a
/// copy of the parameters whose expiry is that time, held to the long side,
/// and the requested side is applied once to the winner.
///
/// The exercise opportunities depend on the contract:
///
/// - **European** — expiry only.
/// - **American** — any `t ∈ [0, T]`. For a standard call or put the value
///   above is monotone in `t` (a call is worth `(S − K·e^{-r·t})⁺`, a put
///   `(K·e^{-r·t} − S)⁺`, and only the discount factor moves), so the maximum
///   always sits at one of the two endpoints and `max(immediate, expiry)` is
///   the exact optimum rather than an approximation of it.
/// - **Bermuda** — expiry plus every scheduled date that falls on or before
///   it. An empty schedule leaves expiry alone, which is a European.
///
/// Any other contract keeps the previous behaviour and is valued at expiry:
/// the lattice rejects those types, but this branch never did and widening
/// the error surface is a separate decision.
///
/// # Errors
///
/// Propagates whatever [`calculate_discounted_payoff`] reports for a single
/// exercise time: [`PricingError::NonFinite`] for a non-finite payoff and
/// [`PricingError::Decimal`] when the growth or discount factor leaves the
/// representable range.
fn price_deterministic(params: &BinomialPricingParams) -> Result<Decimal, PricingError> {
    // Every candidate is valued long and the side is applied once, to the
    // winner. Two reasons, and both arms need them. The exercise decision
    // belongs to the holder whichever side you are on, so the maximum has to
    // be taken over long values; taken over signed short ones it would pick
    // the smallest liability instead of mirroring the holder's choice. And
    // `calculate_discounted_payoff` already signs the payoff through
    // `PayoffInfo` before negating a short result a second time, so a short
    // arm evaluated directly came back positive: a zero-volatility short
    // American put on `S = 90`, `K = 100`, `r = 5%` returned `+10` for a
    // liability of `-10`. Signing here keeps this path on the `long == -short`
    // convention the lattice holds to.
    let exercise_value = |time: Positive| -> Result<Decimal, PricingError> {
        calculate_discounted_payoff(BinomialPricingParams {
            expiry: time,
            side: &Side::Long,
            ..params.clone()
        })
    };

    let expiry_value = exercise_value(params.expiry)?;
    let best = match params.option_type {
        OptionType::American => {
            let immediate = exercise_value(Positive::ZERO)?;
            expiry_value.max(immediate)
        }
        OptionType::Bermuda { exercise_dates } => {
            let mut best = expiry_value;
            for date in exercise_dates {
                if *date > params.expiry {
                    // Not an exercise opportunity: the contract is already gone.
                    continue;
                }
                best = best.max(exercise_value(*date)?);
            }
            best
        }
        _ => expiry_value,
    };

    Ok(match params.side {
        Side::Long => best,
        Side::Short => -best,
    })
}

/// Spot price at lattice node `(step, i)`: `S · u^i · d^(step - i)`, with the
/// powers read from the tree's [`LatticePowers`] table (#859).
///
/// # Errors
///
/// Returns [`PricingError::Decimal`] when either power or the product leaves
/// the representable `Decimal` range, [`PricingError::Positive`] when the
/// result is not a valid `Positive`, and [`PricingError::BinomialNodeMissing`]
/// when `i` walks past `step`.
fn lattice_spot(
    asset: Positive,
    u: Decimal,
    d: Decimal,
    i: usize,
    step: usize,
    powers: &LatticePowers,
) -> Result<Positive, PricingError> {
    let down_steps = step
        .checked_sub(i)
        .ok_or(PricingError::BinomialNodeMissing { node: "down_steps" })?;
    let up_power = powers.up(u, i, "pricing::binomial::lattice_spot::up")?;
    let down_power = powers.down(d, down_steps, "pricing::binomial::lattice_spot::down")?;
    let spot = d_mul(
        d_mul(
            asset.to_dec(),
            up_power,
            "pricing::binomial::lattice_spot::spot_up",
        )?,
        down_power,
        "pricing::binomial::lattice_spot::spot",
    )?;
    Ok(Positive::new_decimal(spot)?)
}

/// Generates a binomial tree for option pricing.
///
/// # Parameters
///
/// * `params`: A reference to `BinomialPricingParams` which contains the parameters required for
///   generating the binomial tree including expiration time, number of steps, volatility, interest rate,
///   asset price, strike price, option type, and option style.
///
/// # Returns
///
/// A tuple containing two vectors of vectors:
/// * `asset_tree`: The tree representing the possible future values of the asset at each step.
/// * `option_tree`: The tree representing the values of the option at each step, signed by
///   `params.side`: a short tree is the negated long tree, whose exercise decisions are the
///   holder's.
///
/// The `generate_binomial_tree` function calculates the possible asset prices and option prices
/// at each node in a binomial tree based on the input parameters.
///
/// 1. It calculates the time interval `dt` for each step.
/// 2. `u` and `d` are the factors by which the price increases or decreases.
/// 3. `p` is the risk-neutral probability.
/// 4. It initializes the `asset_tree` and `option_tree` with the appropriate dimensions.
/// 5. The asset prices are computed for all nodes.
/// 6. The option values are computed at maturity based on the payoff function.
/// 7. The option values are then back-propagated to compute the option value at the current time.
///
/// # Example
///
/// ```rust
/// use rust_decimal::Decimal;
/// use rust_decimal_macros::dec;
/// use optionstratlib_core::model::types::{OptionStyle, OptionType, Side};
/// use optionstratlib_core::nz;
/// use optionstratlib_core::pos_or_panic;
/// use optionstratlib_pricing::pricing::binomial_model::{BinomialPricingParams, generate_binomial_tree};
/// use optionstratlib_core::model::Positive;
/// # fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let params = BinomialPricingParams {
///             asset: Positive::HUNDRED,
///             volatility: pos_or_panic!(0.2),
///             int_rate: dec!(0.05),
///             strike: Positive::HUNDRED,
///             expiry: Positive::ONE,
///             no_steps: nz!(1000),
///             option_type: &OptionType::European,
///             option_style: &OptionStyle::Call,
///             side: &Side::Long,
///         };
/// let (asset_tree, option_tree) = generate_binomial_tree(&params)?;
/// # Ok(())
/// # }
/// ```
///
/// # Cost
///
/// `no_steps` has no upper limit (#807); with `N = no_steps`:
///
/// - **Time** grows as `N²`: every one of the `(N + 1)(N + 2) / 2` lattice
///   nodes gets its spot from two `Decimal` powers, and backward induction
///   values `N (N + 1) / 2` of them, with a payoff per node for an American
///   or a Bermuda exercise date. Measured with Criterion (`cargo bench -p
///   optionstratlib-pricing --bench pricing -- pricing/binomial`) on an
///   Apple M-series laptop, a European call takes about 0.66 ms at 50
///   steps and 15 ms at 200, roughly 0.4 s at 1 000.
/// - **Memory** is two square `(N + 1) × (N + 1)` lattices of `Decimal`,
///   `32 (N + 1)²` bytes (about 32 MB at 1 000 steps and 3.2 GB at 10 000),
///   plus one row of `N + 1` per induction step. Both lattices are reserved
///   and zeroed before any node is valued, so a size the allocator refuses
///   is [`PricingError::InvalidParameter`] at once. On a system that
///   overcommits memory the reservation itself can succeed and the process
///   be stopped by the operating system while the zeros are written; the
///   cost above is the guide for choosing `N`. The full tree exists for
///   inspection and charts; [`price_binomial`] prices the same lattice in
///   `O(N)` memory.
///
/// # Errors
///
/// Same failure surface as [`price_binomial`]:
/// [`PricingError::SqrtFailure`] when the up-factor exponent cannot
/// be represented, [`PricingError::BinomialNodeMissing`] when an
/// intermediate node of the lattice is unexpectedly absent, and
/// [`PricingError::Positive`] when a `Positive` construction
/// downstream underflows. Returns [`PricingError::InvalidParameter`] when
/// the `(no_steps + 1)²` lattice cannot be allocated.
pub fn generate_binomial_tree(params: &BinomialPricingParams) -> BinomialTreeResult {
    // Valued from the holder's side, then signed once at the end (#648): the
    // early-exercise maximum must be taken over the holder's values.
    let mut info = PayoffInfo {
        spot: params.asset,
        strike: params.strike,
        style: *params.option_style,
        side: Side::Long,
        spot_prices: None,
        spot_min: None,
        spot_max: None,
        exotic_params: None,
    };

    let no_steps_raw = params.no_steps.get();
    let dt = params
        .expiry
        .checked_div_dec(f2d!(no_steps_raw as f64))?
        .to_dec();
    let up_factor = calculate_up_factor(params.volatility, dt)?;
    let down_factor = calculate_down_factor(params.volatility, dt)?;
    let probability = calculate_probability(params.int_rate, dt, down_factor, up_factor)?;
    let discount_factor = calculate_discount_factor(params.int_rate, dt)?;

    let mut asset_tree = lattice(no_steps_raw)?;
    let mut option_tree = lattice(no_steps_raw)?;
    let powers = LatticePowers::new(up_factor, down_factor, no_steps_raw)?;

    for (step, step_vec) in asset_tree.iter_mut().enumerate() {
        let nodes = step_vec
            .get_mut(..=step)
            .ok_or(PricingError::BinomialNodeMissing { node: "asset_step" })?;
        for (node, node_val) in nodes.iter_mut().enumerate() {
            // `node` counts down moves. The spot is `lattice_spot`'s, so it
            // is the same `Decimal` `price_binomial` values at this node and
            // the root of the tree is `price_binomial` digit for digit (#716).
            let up_steps = step
                .checked_sub(node)
                .ok_or(PricingError::BinomialNodeMissing { node: "up_steps" })?;
            *node_val = lattice_spot(
                params.asset,
                up_factor,
                down_factor,
                up_steps,
                step,
                &powers,
            )?
            .to_dec();
        }
    }

    let terminal_assets = asset_tree
        .get(no_steps_raw)
        .ok_or(PricingError::BinomialNodeMissing {
            node: "terminal_step",
        })?
        .clone();
    let terminal_options =
        option_tree
            .get_mut(no_steps_raw)
            .ok_or(PricingError::BinomialNodeMissing {
                node: "terminal_step",
            })?;
    for (node, node_val) in terminal_assets.iter().enumerate() {
        info.spot = Positive::new_decimal(*node_val)?;
        let slot = terminal_options
            .get_mut(node)
            .ok_or(PricingError::BinomialNodeMissing {
                node: "terminal_node",
            })?;
        *slot = params.option_type.payoff(&info)?;
    }

    let half_dt = d_div(dt, Decimal::TWO, "pricing::binomial::tree::half_dt")?;
    for step in (0..no_steps_raw).rev() {
        let step_assets = asset_tree
            .get(step)
            .ok_or(PricingError::BinomialNodeMissing { node: "asset_step" })?
            .clone();
        let (current_step_arr, next_step_arr) = step
            .checked_add(1)
            .and_then(|mid| option_tree.split_at_mut_checked(mid))
            .ok_or(PricingError::BinomialNodeMissing {
                node: "option_step",
            })?;
        let current = current_step_arr
            .get_mut(step)
            .and_then(|row| row.get_mut(..=step))
            .ok_or(PricingError::BinomialNodeMissing {
                node: "option_step",
            })?;
        for (node_idx, node_val) in current.iter_mut().enumerate() {
            let node_value =
                option_node_value_wrapper(probability, next_step_arr, node_idx, discount_factor)?;
            let node_asset = || -> Result<Positive, PricingError> {
                let raw = step_assets
                    .get(node_idx)
                    .ok_or(PricingError::BinomialNodeMissing { node: "asset_node" })?;
                Ok(Positive::new_decimal(*raw)?)
            };
            match params.option_type {
                OptionType::European => {
                    *node_val = node_value;
                }
                OptionType::American => {
                    // The root is an exercise opportunity like every other
                    // node, as in `price_binomial`: a deep in-the-money put
                    // is worth its intrinsic value today (#708). Compared in
                    // `Decimal`, as `price_binomial` does (#716).
                    info.spot = node_asset()?;
                    let intrinsic_value = params.option_type.payoff(&info)?;
                    *node_val = node_value.max(intrinsic_value);
                }
                OptionType::Bermuda { exercise_dates } => {
                    // Calculate time at this step
                    let time_at_step = d_mul(
                        dt,
                        Decimal::from(step as u64),
                        "pricing::binomial::tree::time_at_step",
                    )?;
                    // Check if this step is an exercise date
                    let mut is_exercise_date = false;
                    for exercise in exercise_dates {
                        let gap = d_sub(
                            time_at_step,
                            exercise.to_dec(),
                            "pricing::binomial::tree::exercise_gap",
                        )?;
                        if gap.abs() < half_dt {
                            is_exercise_date = true;
                            break;
                        }
                    }
                    // The root is an exercise opportunity when a date lies
                    // within `dt / 2` of `t = 0`, as in `price_binomial`
                    // (#716); compared in `Decimal`, as it does.
                    if is_exercise_date {
                        info.spot = node_asset()?;
                        let intrinsic_value = params.option_type.payoff(&info)?;
                        *node_val = node_value.max(intrinsic_value);
                    } else {
                        *node_val = node_value;
                    }
                }
                _ => {
                    return Err(PricingError::other(
                        "OptionType not supported for binomial tree generation",
                    ));
                }
            }
        }
    }

    if matches!(params.side, Side::Short) {
        for node_val in option_tree.iter_mut().flatten() {
            *node_val = -*node_val;
        }
    }

    Ok((asset_tree, option_tree))
}

/// An empty vector with room for the `no_steps + 1` terminal nodes of
/// [`price_binomial`], reserved before the first payoff is evaluated so a
/// size the system refuses is reported at once, as [`lattice`] reports it,
/// instead of after the leaves have been priced one by one (#807).
fn reserve_nodes(no_steps: usize) -> Result<Vec<Decimal>, PricingError> {
    let too_large = || {
        PricingError::invalid_parameter(
            "no_steps",
            Decimal::from(no_steps),
            "a binomial lattice of this many steps cannot be allocated",
        )
    };
    let width = no_steps.checked_add(1).ok_or_else(too_large)?;
    let mut nodes = Vec::new();
    nodes.try_reserve_exact(width).map_err(|_| too_large())?;
    Ok(nodes)
}

/// A square lattice of `no_steps + 1` rows of `no_steps + 1` zeros. The
/// rows are reserved fallibly: `vec![vec![..; n + 1]; n + 1]` overflowed
/// `n + 1` at `usize::MAX` and aborted with `capacity overflow` on a row
/// wider than the address space (#788); an allocation the system refuses
/// is reported the same way rather than aborting the process.
fn lattice(no_steps: usize) -> Result<Vec<Vec<Decimal>>, PricingError> {
    let too_large = || {
        PricingError::invalid_parameter(
            "no_steps",
            Decimal::from(no_steps),
            "a binomial tree of this many steps cannot be allocated",
        )
    };
    let width = no_steps.checked_add(1).ok_or_else(too_large)?;
    let mut rows: Vec<Vec<Decimal>> = Vec::new();
    rows.try_reserve_exact(width).map_err(|_| too_large())?;
    for _ in 0..width {
        let mut row = Vec::new();
        row.try_reserve_exact(width).map_err(|_| too_large())?;
        row.resize(width, Decimal::ZERO);
        rows.push(row);
    }
    Ok(rows)
}

#[cfg(test)]
mod tests_price_binomial {
    use super::*;
    use optionstratlib_core::assert_decimal_eq;
    use optionstratlib_core::model::types::OptionType;
    use rust_decimal::MathematicalOps;
    use rust_decimal_macros::dec;

    const EPSILON: Decimal = dec!(1e-6);

    /// A step count whose `no_steps + 1` nodes cannot be reserved is
    /// rejected before any node is priced (#807): `usize::MAX` overflows the
    /// node count and `2^60` nodes exceed what any allocation can hold. The
    /// pricer used to start pricing the leaves and grow its vector one node
    /// at a time.
    #[test]
    fn test_price_binomial_unallocatable_steps_is_invalid_parameter() {
        for steps in [usize::MAX, 1usize << 60] {
            let no_steps = NonZeroUsize::new(steps).unwrap_or(NonZeroUsize::MIN);
            let params = BinomialPricingParams {
                asset: Positive::HUNDRED,
                strike: Positive::HUNDRED,
                int_rate: dec!(0.05),
                volatility: pos_or_panic!(0.2),
                expiry: Positive::ONE,
                no_steps,
                option_type: &OptionType::European,
                option_style: &OptionStyle::Call,
                side: &Side::Long,
            };
            assert!(
                matches!(
                    price_binomial(params),
                    Err(PricingError::InvalidParameter {
                        parameter: "no_steps",
                        ..
                    })
                ),
                "steps {steps}"
            );
        }
    }

    #[test]
    fn test_european_call_option() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            strike: Positive::HUNDRED,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.2),
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(3),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert_decimal_eq!(price, dec!(11.0438708), EPSILON);
    }

    #[test]
    fn test_european_put_option() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert_decimal_eq!(price, dec!(5.571526), EPSILON);
    }

    #[test]
    fn test_european_put_option_extended() {
        let params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(1),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert_decimal_eq!(price, dec!(4.446415), EPSILON);
    }

    #[test]
    fn test_short_option() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let long_price = price_binomial(params.clone()).unwrap();
        let short_price = price_binomial(BinomialPricingParams {
            side: &Side::Short,
            ..params
        })
        .unwrap();
        assert_decimal_eq!(long_price, -short_price, EPSILON);
    }

    #[test]
    fn test_zero_volatility() {
        let asset = Positive::HUNDRED;
        let strike = Positive::HUNDRED;
        let int_rate = dec!(0.05);
        let expiry = Positive::ONE;

        let params = BinomialPricingParams {
            asset,
            volatility: Positive::ZERO,
            int_rate,
            strike,
            expiry,
            no_steps: optionstratlib_core::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();

        let exact_price = (asset * (int_rate * expiry).exp() - strike).max(Positive::ZERO)
            * (-int_rate * expiry).exp();

        assert_decimal_eq!(price, exact_price, EPSILON);
    }

    #[test]
    fn test_deep_in_the_money() {
        let params = BinomialPricingParams {
            asset: pos_or_panic!(150.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert!(price > dec!(50.0));
    }

    #[test]
    fn test_deep_out_of_the_money() {
        let params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert!(price < Decimal::ONE);
    }

    #[test]
    fn test_zero_time_to_expiry() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ZERO,
            no_steps: optionstratlib_core::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert_decimal_eq!(price, Decimal::ZERO, EPSILON);
    }
}

#[cfg(test)]
mod tests_generate_binomial_tree {
    use super::*;
    use optionstratlib_core::assert_decimal_eq;
    use optionstratlib_core::model::types::OptionType;
    use rust_decimal_macros::dec;

    const EPSILON: Decimal = dec!(1e-5);

    #[test]
    fn test_binomial_tree_basic() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            strike: Positive::HUNDRED,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.2),
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(3),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        // Check if the asset tree is generated correctly
        assert_eq!(asset_tree[0][0], dec!(100.0));
        assert_decimal_eq!(asset_tree[1][0], dec!(112.2400899), EPSILON);
        assert_decimal_eq!(asset_tree[3][1], dec!(112.2400899), EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(11.0438708), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(17.713887), EPSILON);
        assert_decimal_eq!(option_tree[1][1], dec!(3.500653), EPSILON);
        assert_decimal_eq!(option_tree[2][0], dec!(27.631232), EPSILON);
        assert_decimal_eq!(option_tree[2][1], dec!(6.5458625), EPSILON);
        assert_decimal_eq!(option_tree[2][2], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][0], dec!(41.398244), EPSILON);
        assert_decimal_eq!(option_tree[3][1], dec!(12.240089), EPSILON);
        assert_decimal_eq!(option_tree[3][2], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][3], Decimal::ZERO, EPSILON);
    }

    #[test]
    fn test_binomial_tree_put_option() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            strike: Positive::HUNDRED,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.2),
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(3),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let (_, option_tree) = generate_binomial_tree(&params).unwrap();

        assert_decimal_eq!(option_tree[3][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][1], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][2], dec!(10.905274), EPSILON);
        assert_decimal_eq!(option_tree[3][3], dec!(29.277764), EPSILON);
    }

    #[test]
    fn test_binomial_tree_call_option_check() {
        let params = BinomialPricingParams {
            asset: pos_or_panic!(30.0),
            strike: pos_or_panic!(30.0),
            expiry: Positive::ONE,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.17),
            no_steps: optionstratlib_core::nz!(1),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        // Test asset tree
        assert_eq!(asset_tree.len(), 2);
        assert_decimal_eq!(asset_tree[0][0], dec!(30.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(35.559145), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(25.309944), EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(3.213401), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(5.559145), EPSILON);
        assert_decimal_eq!(option_tree[1][1], Decimal::ZERO, EPSILON);

        let params = BinomialPricingParams {
            asset: pos_or_panic!(30.0),
            strike: pos_or_panic!(30.0),
            expiry: Positive::ONE,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.17),
            no_steps: optionstratlib_core::nz!(2),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        // Test asset tree
        assert_eq!(asset_tree.len(), 3);
        assert_decimal_eq!(asset_tree[0][0], dec!(30.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(33.831947), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(26.602075), EPSILON);
        assert_decimal_eq!(asset_tree[2][0], dec!(38.153354), EPSILON);
        assert_decimal_eq!(asset_tree[2][1], dec!(30.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][2], dec!(23.589013), EPSILON);

        assert_decimal_eq!(option_tree[0][0], dec!(2.564481), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(4.572649), EPSILON);
        assert_decimal_eq!(option_tree[1][1], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][0], dec!(8.153354), EPSILON);
        assert_decimal_eq!(option_tree[2][1], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][2], Decimal::ZERO, EPSILON);
    }

    #[test]
    fn test_binomial_tree_put_option_check() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            strike: pos_or_panic!(110.0),
            expiry: pos_or_panic!(3.0), // Assuming each time step is 1 unit of time
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.09531018), // Calculated to match the 10% up/down movement
            no_steps: optionstratlib_core::nz!(3),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        // Test asset tree
        assert_eq!(asset_tree.len(), 4);
        assert_decimal_eq!(asset_tree[0][0], dec!(100.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(110.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(90.909090), EPSILON);
        assert_decimal_eq!(asset_tree[2][0], dec!(121.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][1], dec!(100.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][2], dec!(82.644628), EPSILON);
        assert_decimal_eq!(asset_tree[3][0], dec!(133.1), EPSILON);
        assert_decimal_eq!(asset_tree[3][1], dec!(110.0), EPSILON);
        assert_decimal_eq!(asset_tree[3][2], dec!(90.909090), EPSILON);
        assert_decimal_eq!(asset_tree[3][3], dec!(75.131480), EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(2.890941), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(1.125426), EPSILON);
        assert_decimal_eq!(option_tree[1][1], dec!(8.623025), EPSILON);
        assert_decimal_eq!(option_tree[2][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][1], dec!(4.635236), EPSILON);
        assert_decimal_eq!(option_tree[2][2], dec!(21.990608), EPSILON);
        assert_decimal_eq!(option_tree[3][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][1], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][2], dec!(19.090909), EPSILON);
        assert_decimal_eq!(option_tree[3][3], dec!(34.868519), EPSILON);
    }

    #[test]
    fn test_binomial_tree_european_put_option() {
        // Define parameters for an American option test case
        let params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::TWO,
            no_steps: optionstratlib_core::nz!(2),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        assert_decimal_eq!(asset_tree[0][0], dec!(50.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(61.070137), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(40.936537), EPSILON);
        assert_decimal_eq!(asset_tree[2][0], dec!(74.591234), EPSILON);
        assert_decimal_eq!(asset_tree[2][1], dec!(50.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][2], dec!(33.516002), EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(3.8687179), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(0.8038018), EPSILON);
        assert_decimal_eq!(option_tree[1][1], dec!(8.5273923), EPSILON);
        assert_decimal_eq!(option_tree[2][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][1], dec!(2.0), EPSILON);
        assert_decimal_eq!(option_tree[2][2], dec!(18.483997), EPSILON);
    }

    #[test]
    fn test_binomial_tree_american_put_option() {
        // Define parameters for an American option test case
        let params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::TWO,
            no_steps: optionstratlib_core::nz!(2),
            option_type: &OptionType::American,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };
        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        assert_decimal_eq!(asset_tree[0][0], dec!(50.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(61.070137), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(40.936537), EPSILON);
        assert_decimal_eq!(asset_tree[2][0], dec!(74.591234), EPSILON);
        assert_decimal_eq!(asset_tree[2][1], dec!(50.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][2], dec!(33.516002), EPSILON);
        assert_decimal_eq!(option_tree[2][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][1], dec!(2.0), EPSILON);
        assert_decimal_eq!(option_tree[2][2], dec!(18.483997), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(0.803801), EPSILON);

        assert_decimal_eq!(option_tree[1][1], params.strike - asset_tree[1][1], EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(4.887966), EPSILON);
    }
}

/// The root of an American tree is an exercise opportunity (#708):
/// `generate_binomial_tree` used to take the continuation value there, so a
/// deep in-the-money put rooted below its intrinsic value and away from
/// `price_binomial` on the same lattice.
#[cfg(test)]
mod tests_american_root_exercise {
    use super::*;
    use rust_decimal_macros::dec;

    fn params<'a>(
        asset: f64,
        strike: f64,
        steps: usize,
        style: &'a OptionStyle,
        side: &'a Side,
    ) -> BinomialPricingParams<'a> {
        BinomialPricingParams {
            asset: pos_or_panic!(asset),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(strike),
            expiry: Positive::ONE,
            no_steps: match NonZeroUsize::new(steps) {
                Some(n) => n,
                None => panic!("step count {steps} is non-zero"),
            },
            option_type: &OptionType::American,
            option_style: style,
            side,
        }
    }

    fn tree_root(params: &BinomialPricingParams) -> Decimal {
        match generate_binomial_tree(params) {
            Ok((_, option_tree)) => match option_tree.first().and_then(|step| step.first()) {
                Some(root) => *root,
                None => panic!("a tree has a root"),
            },
            Err(e) => panic!("tree builds: {e}"),
        }
    }

    fn lattice_price(params: &BinomialPricingParams) -> Decimal {
        match price_binomial(params.clone()) {
            Ok(price) => price,
            Err(e) => panic!("lattice prices: {e}"),
        }
    }

    /// `S = 50`, `K = 100`: exercising today is worth 50, more than holding
    /// (the put cannot pay more than `K = 100` minus a positive spot, and
    /// holding forgoes the interest on `K`). The root is the intrinsic
    /// value, and the short root its negation.
    #[test]
    fn test_generate_binomial_tree_deep_itm_american_put_root_is_intrinsic() {
        for steps in [1, 2, 10, 50] {
            let long = params(50.0, 100.0, steps, &OptionStyle::Put, &Side::Long);
            assert_eq!(tree_root(&long), dec!(50), "steps {steps}");
            assert_eq!(lattice_price(&long), dec!(50), "steps {steps}");

            let short = params(50.0, 100.0, steps, &OptionStyle::Put, &Side::Short);
            assert_eq!(tree_root(&short), dec!(-50), "steps {steps}");
        }
    }

    /// The continuation value at the root is below intrinsic for the deep
    /// in-the-money put: the European on the same lattice is worth less than
    /// 50, so the root equals intrinsic only through early exercise.
    #[test]
    fn test_generate_binomial_tree_deep_itm_put_continuation_is_below_intrinsic() {
        let european = BinomialPricingParams {
            option_type: &OptionType::European,
            ..params(50.0, 100.0, 50, &OptionStyle::Put, &Side::Long)
        };
        assert!(tree_root(&european) < dec!(50));
    }

    /// The tree root and `price_binomial` agree for American calls and puts,
    /// long and short, out of, at and in the money, at several step counts.
    /// They agree exactly: since #716 the tree builds each spot as
    /// `lattice_spot` does and compares nodes in `Decimal`, so both walk the
    /// same numbers. Before, an `f64` round trip and a different factor order
    /// left gaps up to `5.4e-14`.
    #[test]
    fn test_generate_binomial_tree_american_root_matches_price_binomial() {
        for style in [OptionStyle::Call, OptionStyle::Put] {
            for side in [Side::Long, Side::Short] {
                for (asset, strike) in
                    [(50.0, 100.0), (90.0, 100.0), (100.0, 100.0), (130.0, 100.0)]
                {
                    for steps in [1, 2, 3, 10, 50] {
                        let p = params(asset, strike, steps, &style, &side);
                        assert_eq!(
                            tree_root(&p),
                            lattice_price(&p),
                            "{style:?} {side:?} S={asset} K={strike} steps={steps}"
                        );
                    }
                }
            }
        }
    }
}

/// The root of a Bermuda tree is an exercise opportunity when a date lies
/// within `dt / 2` of `t = 0` (#716), as it is in `price_binomial`: the tree
/// used to exempt its root, so a deep in-the-money put with an exercise date
/// today rooted at its continuation value instead of its intrinsic value.
#[cfg(test)]
mod tests_bermuda_root_exercise {
    use super::*;
    use rust_decimal_macros::dec;

    fn bermuda(dates: &[f64]) -> OptionType {
        OptionType::Bermuda {
            exercise_dates: dates.iter().map(|d| pos_or_panic!(*d)).collect(),
        }
    }

    fn params<'a>(
        asset: f64,
        steps: usize,
        option_type: &'a OptionType,
        style: &'a OptionStyle,
        side: &'a Side,
    ) -> BinomialPricingParams<'a> {
        BinomialPricingParams {
            asset: pos_or_panic!(asset),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: match NonZeroUsize::new(steps) {
                Some(n) => n,
                None => panic!("step count {steps} is non-zero"),
            },
            option_type,
            option_style: style,
            side,
        }
    }

    fn tree_root(params: &BinomialPricingParams) -> Decimal {
        match generate_binomial_tree(params) {
            Ok((_, option_tree)) => match option_tree.first().and_then(|step| step.first()) {
                Some(root) => *root,
                None => panic!("a tree has a root"),
            },
            Err(e) => panic!("tree builds: {e}"),
        }
    }

    fn lattice_price(params: &BinomialPricingParams) -> Decimal {
        match price_binomial(params.clone()) {
            Ok(price) => price,
            Err(e) => panic!("lattice prices: {e}"),
        }
    }

    /// `S = 50`, `K = 100` with an exercise date today: exercising is worth
    /// 50, more than holding, so the root is the intrinsic value and the
    /// short root its negation. The tree rooted at the continuation value,
    /// `45.1229424500713990` on one step.
    #[test]
    fn test_generate_binomial_tree_bermuda_put_exercisable_today_root_is_intrinsic() {
        let option_type = bermuda(&[0.0, 0.5]);
        for steps in [1, 2, 3, 10, 50] {
            let long = params(50.0, steps, &option_type, &OptionStyle::Put, &Side::Long);
            assert_eq!(tree_root(&long), dec!(50), "steps {steps}");
            assert_eq!(lattice_price(&long), dec!(50), "steps {steps}");

            let short = params(50.0, steps, &option_type, &OptionStyle::Put, &Side::Short);
            assert_eq!(tree_root(&short), dec!(-50), "steps {steps}");
        }
    }

    /// A date only near `t = 0` counts at the root while it lies within
    /// `dt / 2`: `0.001` does on 50 steps (`dt / 2 = 0.01`), and `0.3` does
    /// on one step (`dt / 2 = 0.5`) but not on ten (`dt / 2 = 0.05`).
    #[test]
    fn test_generate_binomial_tree_bermuda_root_exercise_follows_half_step_rule() {
        let near = bermuda(&[0.001]);
        let p = params(50.0, 50, &near, &OptionStyle::Put, &Side::Long);
        assert_eq!(tree_root(&p), dec!(50));

        let coarse = bermuda(&[0.3]);
        let one_step = params(50.0, 1, &coarse, &OptionStyle::Put, &Side::Long);
        assert_eq!(tree_root(&one_step), dec!(50));
        let ten_steps = params(50.0, 10, &coarse, &OptionStyle::Put, &Side::Long);
        assert!(tree_root(&ten_steps) < dec!(50));
        assert_eq!(tree_root(&ten_steps), lattice_price(&ten_steps));
    }

    /// The tree root and `price_binomial` agree exactly for Bermuda calls and
    /// puts, long and short, across moneyness, step counts and schedules
    /// with and without a date at `t = 0`.
    #[test]
    fn test_generate_binomial_tree_bermuda_root_matches_price_binomial() {
        let schedules = [
            bermuda(&[0.0, 0.5]),
            bermuda(&[0.25, 0.5, 0.75]),
            bermuda(&[0.001]),
            bermuda(&[0.5, 2.0]),
        ];
        for option_type in &schedules {
            for style in [OptionStyle::Call, OptionStyle::Put] {
                for side in [Side::Long, Side::Short] {
                    for asset in [50.0, 90.0, 100.0, 130.0] {
                        for steps in [1, 2, 3, 10, 50] {
                            let p = params(asset, steps, option_type, &style, &side);
                            assert_eq!(
                                tree_root(&p),
                                lattice_price(&p),
                                "{option_type:?} {style:?} {side:?} S={asset} steps={steps}"
                            );
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests_bermuda_option {
    use super::*;
    use optionstratlib_core::assert_decimal_eq;
    use optionstratlib_core::model::types::OptionType;
    use rust_decimal_macros::dec;

    const EPSILON: Decimal = dec!(1e-4);

    #[test]
    fn test_bermuda_price_between_european_and_american() {
        // Bermuda price should be: European <= Bermuda <= American
        let european_params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(100),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let american_params = BinomialPricingParams {
            option_type: &OptionType::American,
            ..european_params.clone()
        };

        // Exercise at 3 months, 6 months, 9 months
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![pos_or_panic!(0.25), pos_or_panic!(0.5), pos_or_panic!(0.75)],
        };
        let bermuda_params = BinomialPricingParams {
            option_type: &bermuda_type,
            ..european_params.clone()
        };

        let european_price = price_binomial(european_params).unwrap();
        let american_price = price_binomial(american_params).unwrap();
        let bermuda_price = price_binomial(bermuda_params).unwrap();

        assert!(
            european_price <= bermuda_price,
            "European {} should be <= Bermuda {}",
            european_price,
            bermuda_price
        );
        assert!(
            bermuda_price <= american_price,
            "Bermuda {} should be <= American {}",
            bermuda_price,
            american_price
        );
    }

    #[test]
    fn test_bermuda_single_exercise_date() {
        // Single exercise date should give price between European and American
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![pos_or_panic!(0.5)],
        };
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.3),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(105.0),
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(50),
            option_type: &bermuda_type,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert!(
            price > Decimal::ZERO,
            "Bermuda put price should be positive"
        );
    }

    #[test]
    fn test_bermuda_many_exercise_dates_approaches_american() {
        // With many exercise dates, Bermuda should approach American price
        let european_params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(52),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let american_params = BinomialPricingParams {
            option_type: &OptionType::American,
            ..european_params.clone()
        };

        // Weekly exercise dates (52 dates for 1 year)
        let exercise_dates: Vec<Positive> = (1..=52)
            .map(|i| pos_or_panic!(f64::from(i) / 52.0))
            .collect();
        let bermuda_type = OptionType::Bermuda { exercise_dates };
        let bermuda_params = BinomialPricingParams {
            option_type: &bermuda_type,
            ..european_params.clone()
        };

        let american_price = price_binomial(american_params).unwrap();
        let bermuda_price = price_binomial(bermuda_params).unwrap();

        // Bermuda with weekly exercise should be close to American
        let diff = (american_price - bermuda_price).abs();
        assert!(
            diff < dec!(0.5),
            "Bermuda with 52 exercise dates should be close to American: diff = {}",
            diff
        );
    }

    #[test]
    fn test_bermuda_no_exercise_dates_equals_european() {
        // Empty exercise dates results in European-like behavior
        let european_params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(50),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![],
        };
        let bermuda_params = BinomialPricingParams {
            option_type: &bermuda_type,
            ..european_params.clone()
        };

        let european_price = price_binomial(european_params).unwrap();
        let bermuda_price = price_binomial(bermuda_params).unwrap();

        assert_decimal_eq!(european_price, bermuda_price, EPSILON);
    }

    #[test]
    fn test_bermuda_call_option() {
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![pos_or_panic!(0.25), pos_or_panic!(0.5), pos_or_panic!(0.75)],
        };
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.25),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(95.0),
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(100),
            option_type: &bermuda_type,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert!(
            price > dec!(5.0),
            "ITM Bermuda call should have value > intrinsic"
        );
    }
}

#[cfg(test)]
mod tests_zero_volatility_early_exercise {
    use super::*;
    use optionstratlib_core::assert_decimal_eq;
    use optionstratlib_core::model::types::OptionType;
    use rust_decimal_macros::dec;

    /// With no volatility the underlying is its own forward, so every price
    /// below has a closed form. The only error between the two is
    /// `Decimal::checked_exp`'s series truncation; the largest gap observed
    /// across these cases is `7.1e-14`, so `1e-12` pins roughly thirteen
    /// significant digits with room to spare.
    const ANALYTIC_EPSILON: Decimal = dec!(1e-12);

    /// One year, one hundred steps, no volatility. The step count is
    /// irrelevant on this path — it never builds a lattice — and is only
    /// here so the parameters stay comparable with the small-volatility
    /// runs further down.
    fn zero_vol_params<'a>(
        asset: Positive,
        strike: Positive,
        int_rate: Decimal,
        option_type: &'a OptionType,
        option_style: &'a OptionStyle,
    ) -> BinomialPricingParams<'a> {
        BinomialPricingParams {
            asset,
            volatility: Positive::ZERO,
            int_rate,
            strike,
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(100),
            option_type,
            option_style,
            side: &Side::Long,
        }
    }

    #[test]
    fn test_price_binomial_zero_volatility_american_put_itm_exercises_immediately() {
        // S = 90, K = 100, r = 5%, T = 1, σ = 0. The forward is 94.61, so
        // holding to expiry is worth e^{-0.05}(100 − 90·e^{0.05}) = 5.1229.
        // Exercising now is worth K − S = 10, and that is the price.
        let params = zero_vol_params(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &OptionType::American,
            &OptionStyle::Put,
        );
        let european = price_binomial(BinomialPricingParams {
            option_type: &OptionType::European,
            ..params.clone()
        })
        .unwrap();
        let american = price_binomial(params).unwrap();

        // Immediate exercise is exact: no discount factor is involved.
        assert_eq!(american, dec!(10));
        assert_decimal_eq!(european, dec!(5.122942450071406), ANALYTIC_EPSILON);
        assert!(
            american > european,
            "American {american} must carry an early-exercise premium over European {european}"
        );
    }

    /// A short position is the negative of the long one, on the deterministic
    /// path as much as on the lattice. The exercise decision belongs to the
    /// holder either way, so the maximum is taken over long values and the
    /// side is applied once to the winner; evaluating a short candidate
    /// directly signed the payoff twice and reported this liability as `+10`.
    #[test]
    fn test_price_binomial_zero_volatility_short_is_the_negative_of_long() {
        let long_params = zero_vol_params(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &OptionType::American,
            &OptionStyle::Put,
        );
        let short = price_binomial(BinomialPricingParams {
            side: &Side::Short,
            ..long_params.clone()
        })
        .unwrap();
        let long = price_binomial(long_params).unwrap();

        assert_eq!(long, dec!(10));
        assert_eq!(short, dec!(-10));
    }

    /// The same symmetry over every arm of the deterministic branch, so an
    /// American, a Bermuda and a European are all held to `long == -short`.
    #[test]
    fn test_price_binomial_zero_volatility_short_symmetry_across_exercise_styles() {
        let dates = vec![pos_or_panic!(0.5)];
        let bermuda = OptionType::Bermuda {
            exercise_dates: dates,
        };
        for option_type in [&OptionType::American, &bermuda, &OptionType::European] {
            for option_style in [&OptionStyle::Put, &OptionStyle::Call] {
                let long_params = zero_vol_params(
                    pos_or_panic!(90.0),
                    Positive::HUNDRED,
                    dec!(0.05),
                    option_type,
                    option_style,
                );
                let short = price_binomial(BinomialPricingParams {
                    side: &Side::Short,
                    ..long_params.clone()
                })
                .unwrap();
                let long = price_binomial(long_params).unwrap();

                assert_eq!(
                    long, -short,
                    "{option_type:?} {option_style:?} broke long == -short: {long} against {short}"
                );
                assert!(
                    long >= Decimal::ZERO,
                    "{option_type:?} {option_style:?} priced a long holding at {long}"
                );
            }
        }
    }

    #[test]
    fn test_price_binomial_zero_volatility_american_call_itm_holds_to_expiry() {
        // S = 110, K = 100, r = 5%. A call on a non-dividend-paying forward
        // is never exercised early while r > 0: holding is worth
        // S − K·e^{-rT} = 14.877, above the intrinsic 10.
        let params = zero_vol_params(
            Positive::HUNDRED + pos_or_panic!(10.0),
            Positive::HUNDRED,
            dec!(0.05),
            &OptionType::American,
            &OptionStyle::Call,
        );
        let european = price_binomial(BinomialPricingParams {
            option_type: &OptionType::European,
            ..params.clone()
        })
        .unwrap();
        let american = price_binomial(params).unwrap();

        assert_eq!(american, european);
        assert_decimal_eq!(american, dec!(14.877057549928594), ANALYTIC_EPSILON);
        assert!(american > dec!(10), "holding must beat the intrinsic 10");
    }

    #[test]
    fn test_price_binomial_zero_volatility_american_call_negative_rate_exercises_immediately() {
        // Flip the sign of the rate and the call is the one with an
        // early-exercise premium: holding is worth
        // e^{0.05}(110·e^{-0.05} − 100) = 4.873, exercising now is worth 10.
        let params = zero_vol_params(
            Positive::HUNDRED + pos_or_panic!(10.0),
            Positive::HUNDRED,
            dec!(-0.05),
            &OptionType::American,
            &OptionStyle::Call,
        );
        let european = price_binomial(BinomialPricingParams {
            option_type: &OptionType::European,
            ..params.clone()
        })
        .unwrap();
        let american = price_binomial(params).unwrap();

        assert_eq!(american, dec!(10));
        assert_decimal_eq!(european, dec!(4.872890362397602), ANALYTIC_EPSILON);
    }

    #[test]
    fn test_price_binomial_zero_volatility_american_put_negative_rate_holds_to_expiry() {
        // The mirror image: with r < 0 the put is never exercised early,
        // and holding is worth 100·e^{0.02} − 90 = 12.020 against an
        // intrinsic of 10.
        let params = zero_vol_params(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(-0.02),
            &OptionType::American,
            &OptionStyle::Put,
        );
        let european = price_binomial(BinomialPricingParams {
            option_type: &OptionType::European,
            ..params.clone()
        })
        .unwrap();
        let american = price_binomial(params).unwrap();

        assert_eq!(american, european);
        assert_decimal_eq!(american, dec!(12.020134002675576), ANALYTIC_EPSILON);
        assert!(american > dec!(10), "holding must beat the intrinsic 10");
    }

    #[test]
    fn test_price_binomial_zero_volatility_european_put_keeps_the_discounted_forward_payoff() {
        // The regression bar: early exercise must not leak into a European.
        let params = zero_vol_params(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &OptionType::European,
            &OptionStyle::Put,
        );

        let price = price_binomial(params).unwrap();
        assert_decimal_eq!(price, dec!(5.122942450071406), ANALYTIC_EPSILON);
    }

    #[test]
    fn test_price_binomial_zero_volatility_bermuda_takes_the_best_scheduled_date() {
        // Exercising at t is worth K·e^{-rt} − S, which decays in t, so the
        // earliest scheduled date wins: 100·e^{-0.0125} − 90 = 8.7578. The
        // price sits strictly between the European (no early exercise) and
        // the American (exercise at t = 0), which is what proves the
        // schedule is being read rather than ignored in either direction.
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![pos_or_panic!(0.25), pos_or_panic!(0.5), pos_or_panic!(0.75)],
        };
        let params = zero_vol_params(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &bermuda_type,
            &OptionStyle::Put,
        );
        let european = price_binomial(BinomialPricingParams {
            option_type: &OptionType::European,
            ..params.clone()
        })
        .unwrap();
        let american = price_binomial(BinomialPricingParams {
            option_type: &OptionType::American,
            ..params.clone()
        })
        .unwrap();
        let bermuda = price_binomial(params).unwrap();

        assert_decimal_eq!(bermuda, dec!(8.757780049388145), ANALYTIC_EPSILON);
        assert!(
            european < bermuda,
            "European {european} < Bermuda {bermuda}"
        );
        assert!(
            bermuda < american,
            "Bermuda {bermuda} < American {american}"
        );
    }

    #[test]
    fn test_price_binomial_zero_volatility_bermuda_later_only_schedule_is_worth_less() {
        // Same contract, the 0.25 date removed: the best remaining date is
        // 0.5 and the price drops to 100·e^{-0.025} − 90 = 7.5310. A branch
        // that exercised continuously would return the same number for both
        // schedules.
        let early_type = OptionType::Bermuda {
            exercise_dates: vec![pos_or_panic!(0.25), pos_or_panic!(0.5)],
        };
        let late_type = OptionType::Bermuda {
            exercise_dates: vec![pos_or_panic!(0.5)],
        };
        let params = zero_vol_params(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &late_type,
            &OptionStyle::Put,
        );
        let early = price_binomial(BinomialPricingParams {
            option_type: &early_type,
            ..params.clone()
        })
        .unwrap();
        let late = price_binomial(params).unwrap();

        assert_decimal_eq!(late, dec!(7.530991202833263), ANALYTIC_EPSILON);
        assert_decimal_eq!(early, dec!(8.757780049388145), ANALYTIC_EPSILON);
        assert!(late < early, "later-only schedule {late} < {early}");
    }

    #[test]
    fn test_price_binomial_zero_volatility_bermuda_empty_schedule_equals_european() {
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![],
        };
        let params = zero_vol_params(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &bermuda_type,
            &OptionStyle::Put,
        );
        let european = price_binomial(BinomialPricingParams {
            option_type: &OptionType::European,
            ..params.clone()
        })
        .unwrap();
        let bermuda = price_binomial(params).unwrap();

        assert_eq!(bermuda, european);
    }

    #[test]
    fn test_price_binomial_zero_volatility_bermuda_schedule_after_expiry_equals_european() {
        // A date the contract never reaches is not an exercise opportunity.
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![Positive::TWO],
        };
        let params = zero_vol_params(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &bermuda_type,
            &OptionStyle::Put,
        );
        let european = price_binomial(BinomialPricingParams {
            option_type: &OptionType::European,
            ..params.clone()
        })
        .unwrap();
        let bermuda = price_binomial(params).unwrap();

        assert_eq!(bermuda, european);
    }

    #[test]
    fn test_price_binomial_zero_volatility_bermuda_exercisable_now_equals_american() {
        // A schedule containing t = 0 gives the holder the only date the
        // American would have used here, so the two must agree.
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![Positive::ZERO],
        };
        let params = zero_vol_params(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &bermuda_type,
            &OptionStyle::Put,
        );
        let american = price_binomial(BinomialPricingParams {
            option_type: &OptionType::American,
            ..params.clone()
        })
        .unwrap();
        let bermuda = price_binomial(params).unwrap();

        assert_eq!(bermuda, american);
        assert_eq!(bermuda, dec!(10));
    }

    #[test]
    fn test_price_binomial_collapsed_lattice_american_put_exercises_immediately() {
        // `1e-28` is the smallest non-zero `Decimal`, so `σ√dt` underflows
        // and `u == d`: the lattice collapses and the deterministic branch
        // takes over. It must honour early exercise like the σ = 0 branch
        // it stands in for. (`1e-29` and below round to zero and go through
        // the σ = 0 branch instead.)
        let params = BinomialPricingParams {
            asset: pos_or_panic!(90.0),
            volatility: Positive::new_decimal(dec!(1e-28)).unwrap(),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(10),
            option_type: &OptionType::American,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert_eq!(price, dec!(10));
    }
}

#[cfg(test)]
mod tests_zero_volatility_continuity {
    use super::*;
    use optionstratlib_core::assert_decimal_eq;
    use optionstratlib_core::model::types::OptionType;
    use rust_decimal_macros::dec;

    /// Largest gap measured across the five cases below is `4.9e-15`, which
    /// is `Decimal` round-off accumulated through two hundred induction
    /// steps rather than model error. `1e-12` leaves two orders of
    /// magnitude of headroom without hiding a real discrepancy: the defect
    /// this guards against moved the American put by `4.88`.
    const CONTINUITY_EPSILON: Decimal = dec!(1e-12);

    /// The volatility used to approach the limit, and the step count that
    /// goes with it.
    ///
    /// The two cannot be chosen independently. A CRR lattice is only
    /// arbitrage-free while `d < e^{r·dt} < u`, i.e. while `σ > |r|·√dt`;
    /// below that the risk-neutral probability leaves `[0, 1]`, is clamped,
    /// and the lattice stops approximating anything. With `|r| = 0.05` and
    /// `dt = 1/200`, the bound is `0.0035`, so `σ = 0.005` clears it by a
    /// factor of 1.4. Pushing σ lower without raising the step count moves
    /// *away* from the limit — measured at `σ = 0.002, n = 400` the
    /// American call is off by `−1.09`.
    const LIMIT_VOLATILITY: Decimal = dec!(0.005);

    /// Prices the same contract twice, at σ = 0 and at `LIMIT_VOLATILITY`,
    /// and asserts the two agree.
    fn assert_zero_volatility_is_the_limit(
        asset: Positive,
        strike: Positive,
        int_rate: Decimal,
        option_type: &OptionType,
        option_style: &OptionStyle,
    ) {
        let base = BinomialPricingParams {
            asset,
            volatility: Positive::ZERO,
            int_rate,
            strike,
            expiry: Positive::ONE,
            no_steps: optionstratlib_core::nz!(200),
            option_type,
            option_style,
            side: &Side::Long,
        };

        let at_zero = price_binomial(base.clone()).unwrap();
        let near_zero = price_binomial(BinomialPricingParams {
            volatility: Positive::new_decimal(LIMIT_VOLATILITY).unwrap(),
            ..base
        })
        .unwrap();

        assert_decimal_eq!(at_zero, near_zero, CONTINUITY_EPSILON);
    }

    #[test]
    fn test_price_binomial_zero_volatility_american_put_matches_the_lattice_limit() {
        assert_zero_volatility_is_the_limit(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &OptionType::American,
            &OptionStyle::Put,
        );
    }

    #[test]
    fn test_price_binomial_zero_volatility_american_call_matches_the_lattice_limit() {
        // r > 0: the limit is the European value, so this catches a branch
        // that exercised early when it should not.
        assert_zero_volatility_is_the_limit(
            Positive::HUNDRED + pos_or_panic!(10.0),
            Positive::HUNDRED,
            dec!(0.05),
            &OptionType::American,
            &OptionStyle::Call,
        );
    }

    #[test]
    fn test_price_binomial_zero_volatility_american_call_negative_rate_matches_the_lattice_limit() {
        // r < 0: the limit is the intrinsic, so this catches the opposite
        // mistake on the same contract.
        assert_zero_volatility_is_the_limit(
            Positive::HUNDRED + pos_or_panic!(10.0),
            Positive::HUNDRED,
            dec!(-0.05),
            &OptionType::American,
            &OptionStyle::Call,
        );
    }

    #[test]
    fn test_price_binomial_zero_volatility_bermuda_matches_the_lattice_limit() {
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![pos_or_panic!(0.25), pos_or_panic!(0.5), pos_or_panic!(0.75)],
        };
        assert_zero_volatility_is_the_limit(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &bermuda_type,
            &OptionStyle::Put,
        );
    }

    #[test]
    fn test_price_binomial_zero_volatility_european_matches_the_lattice_limit() {
        assert_zero_volatility_is_the_limit(
            pos_or_panic!(90.0),
            Positive::HUNDRED,
            dec!(0.05),
            &OptionType::European,
            &OptionStyle::Put,
        );
    }
}