libitofin 0.14.0

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
//! Credit-default swap.
//!
//! Port of `ql/instruments/creditdefaultswap.{hpp,cpp}`: the contract's terms,
//! the premium leg it pays, and the cash-settled upfront and accrual-rebate
//! flows that frame it (`creditdefaultswap.cpp:39-85` and `:87-176`).
//!
//! A contract quoted as a running spread alone carries no [`upfront`], and its
//! upfront payment is a zero-amount flow on the cash settlement date that exists
//! only because the engines read it unconditionally. The upfront-quoted
//! constructors add the quote, and with it a payment of `upfront * notional`
//! held unsigned as C++ holds it (`creditdefaultswap.cpp:127-131`): the sign the
//! protection side gives it is the engine's to apply.
//!
//! ## Divergences from QuantLib
//!
//! - The C++ constructors' defaulted arguments (`creditdefaultswap.hpp:105-112`
//!   and `:155-166`) become [`CdsTerms`], whose [`Default`] carries the C++
//!   defaults. [`CreditDefaultSwap::new`] and [`CreditDefaultSwap::with_upfront`]
//!   take the leading arguments and default the rest;
//!   [`CreditDefaultSwap::with_terms`] and
//!   [`CreditDefaultSwap::with_upfront_and_terms`] take them all. Only the
//!   upfront-quoted C++ constructor takes an `upfrontDate`, so there a
//!   running-spread contract cannot reach it; here it is one [`CdsTerms`] field
//!   among the rest that the running-spread constructors leave `None`.
//! - The empty-schedule check runs before the protection-start default, where
//!   C++ runs it after: `protectionStart == Date() ? schedule[0]` sits in the
//!   member-initialiser list (`creditdefaultswap.cpp:56`) and so reads
//!   `schedule[0]` before `init`'s `QL_REQUIRE(!schedule.empty())`
//!   (`creditdefaultswap.cpp:91`). Reordering keeps an empty schedule an `Err`
//!   rather than an out-of-range index (D4).
//! - The null-date sentinels for the protection start, the trade date and the
//!   last-period day counter become [`Option`]s, as does the empty
//!   `DayCounter()` the C++ leg builder reads as "use the coupon rate's"
//!   (`fixedratecoupon.cpp:255-257`).
//! - `registerWith(claim_)` (`creditdefaultswap.cpp:175`) has no counterpart:
//!   the ported [`Claim`] is not an `Observable` (see `claim.rs`), so there is
//!   nothing to subscribe to. The only other registration is the evaluation
//!   date the C++ [`Instrument`](crate::instrument::Instrument) base subscribes
//!   to (`instrument.cpp:26-32`); with no singleton to reach (D5) the caller
//!   passes the [`Settings`] instead. C++ does not register with the premium
//!   leg's flows, and neither does this port.
//! - The engine bundles' sentinels all become [`Option`] (D4): the
//!   `Null<Real>`/`Null<Rate>` "result not available" of [`CdsResults`], and the
//!   `Protection::Side(-1)`, `Null<Real>`, null `shared_ptr` and `Date()` "not
//!   set" of [`CdsArguments`] (`creditdefaultswap.cpp:451-453`). `upfront` is
//!   the exception that is no translation at all: C++ already declares it
//!   `ext::optional<Rate>` (`creditdefaultswap.hpp:314`) and does not validate
//!   it, because an absent upfront is a running-spread contract rather than a
//!   missing input.
//! - [`setup_expired`] zeroes seven results where the eight-field
//!   [`CdsResults`] might suggest eight: `accrualRebateNPV_` is absent from
//!   `setupExpired` (`creditdefaultswap.cpp:215-220`), is declared without an
//!   initialiser (`creditdefaultswap.hpp:302`), and is written only by
//!   `fetchResults` (`creditdefaultswap.cpp:256`), so C++ reads an
//!   uninitialised member from `accrualRebateNPV()` on a contract that expires
//!   before it is ever priced. The port leaves it `None`, whose accessor
//!   reports it as not available. A contract priced before it expired keeps the
//!   fetched value in both, since `setupExpired` does not touch the field.
//! - [`implied_hazard_rate`] validates the arguments it sets its solving engine
//!   up with, which `impliedHazardRate` (`creditdefaultswap.cpp:373`) does not:
//!   a bundle C++ inverts unvalidated is one whose pricing failure the port
//!   could only report as a failure to bracket (D4).
//!
//! ## Deferred
//!
//! Within EPIC Credit (#676), and omitted visibly rather than accepted and
//! ignored:
//!
//! - `protectionEndDate` (`creditdefaultswap.cpp:430-432`), which reads the
//!   accrual end of the last coupon through the `coupon_cast` that
//!   [`CashFlow::as_coupon`](crate::cashflow::CashFlow::as_coupon) ports.
//!
//! [`upfront`]: CreditDefaultSwap::upfront
//! [`setup_expired`]: CreditDefaultSwap::setup_expired
//! [`implied_hazard_rate`]: CreditDefaultSwap::implied_hazard_rate

use std::any::Any;

use crate::cashflow::Leg;
use crate::cashflows::{FixedRateLeg, SimpleCashFlow};
use crate::errors::QlResult;
use crate::handle::Handle;
use crate::instrument::{Instrument, InstrumentBase, InstrumentResults};
use crate::instruments::claim::{Claim, FaceValueClaim};
use crate::instruments::protection::ProtectionSide;
use crate::interestrate::Compounding;
use crate::math::solver1d::Solver1D;
use crate::math::solvers1d::brent::Brent;
use crate::pricingengine::{Arguments, GenericEngine, PricingEngine, Results};
use crate::pricingengines::credit::{
    AccrualBias, ForwardsInCouponPeriod, IsdaCdsEngine, MidPointCdsEngine, NumericalFix,
};
use crate::quotes::{Quote, SimpleQuote};
use crate::settings::Settings;
use crate::shared::{Shared, shared};
use crate::termstructures::credit::defaulttermstructure::DefaultProbabilityTermStructure;
use crate::termstructures::credit::flathazardrate::FlatHazardRate;
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::time::businessdayconvention::BusinessDayConvention;
use crate::time::calendars::weekendsonly::WeekendsOnly;
use crate::time::date::{Date, Month};
use crate::time::dategenerationrule::DateGeneration;
use crate::time::daycounter::DayCounter;
use crate::time::frequency::Frequency;
use crate::time::period::Period;
use crate::time::schedule::{Schedule, previous_twentieth};
use crate::time::timeunit::TimeUnit;
use crate::types::{Integer, Natural, Rate, Real};
use crate::{fail, require};

/// The terms a [`CreditDefaultSwap`] defaults when they are not quoted.
///
/// One field per defaulted argument of the C++ constructors
/// (`creditdefaultswap.hpp:105-112`); [`Default`] carries their C++ values.
pub struct CdsTerms {
    /// Whether the accrued coupon is due on a default.
    pub settles_accrual: bool,
    /// Whether a default pays at default time rather than at the end of the
    /// accrual period.
    pub pays_at_default_time: bool,
    /// The first date a default triggers the contract; the schedule's first
    /// date when absent.
    pub protection_start: Option<Date>,
    /// The date the upfront and the accrual rebate settle on; deduced from the
    /// trade date and [`cash_settlement_days`](CdsTerms::cash_settlement_days)
    /// when absent.
    pub upfront_date: Option<Date>,
    /// What a default pays out; a [`FaceValueClaim`] when absent.
    pub claim: Option<Shared<dyn Claim>>,
    /// The day counter the last coupon accrues with, overriding the spread's.
    pub last_period_day_counter: Option<DayCounter>,
    /// Whether the protection seller rebates the accrued current coupon.
    pub rebates_accrual: bool,
    /// The trade date; deduced from the protection start when absent.
    pub trade_date: Option<Date>,
    /// The business days from the trade date to cash settlement.
    pub cash_settlement_days: Natural,
}

impl Default for CdsTerms {
    fn default() -> CdsTerms {
        CdsTerms {
            settles_accrual: true,
            pays_at_default_time: true,
            protection_start: None,
            upfront_date: None,
            claim: None,
            last_period_day_counter: None,
            rebates_accrual: true,
            trade_date: None,
            cash_settlement_days: 3,
        }
    }
}

/// Arguments passed to a credit-default-swap pricing engine (the C++
/// `CreditDefaultSwap::arguments`, `creditdefaultswap.hpp:311-329`).
///
/// Every field the C++ default constructor sentinels
/// (`creditdefaultswap.cpp:451-453`) or leaves null is an [`Option`] here, and
/// [`validate`](Arguments::validate) reads them as C++ reads the sentinels.
#[derive(Default)]
pub struct CdsArguments {
    /// Which side of the protection the contract holds.
    pub side: Option<ProtectionSide>,
    /// The notional the protection covers.
    pub notional: Option<Real>,
    /// The upfront, in fractional units, when the contract quotes one.
    ///
    /// Already an `ext::optional` in C++ and, like it, not validated: a
    /// running-spread contract legitimately has none.
    pub upfront: Option<Rate>,
    /// The running spread the premium leg pays.
    pub spread: Option<Rate>,
    /// The premium leg.
    pub leg: Leg,
    /// The upfront payment, due on the cash settlement date.
    pub upfront_payment: Option<Shared<SimpleCashFlow>>,
    /// The accrual rebate, when the contract carries one.
    pub accrual_rebate: Option<Shared<SimpleCashFlow>>,
    /// Whether the accrued coupon is due on a default.
    pub settles_accrual: bool,
    /// Whether a default pays at default time.
    pub pays_at_default_time: bool,
    /// What a default pays out.
    pub claim: Option<Shared<dyn Claim>>,
    /// The first date a default triggers the contract.
    pub protection_start: Option<Date>,
    /// The date the contract matures.
    pub maturity: Option<Date>,
}

impl Arguments for CdsArguments {
    fn validate(&self) -> QlResult<()> {
        require!(self.side.is_some(), "side not set");
        let Some(notional) = self.notional else {
            fail!("notional not set");
        };
        require!(notional != 0.0, "null notional set");
        require!(self.spread.is_some(), "spread not set");
        require!(!self.leg.is_empty(), "coupons not set");
        require!(self.upfront_payment.is_some(), "upfront payment not set");
        require!(self.claim.is_some(), "claim not set");
        require!(
            self.protection_start.is_some(),
            "protection start date not set"
        );
        require!(self.maturity.is_some(), "maturity date not set");
        Ok(())
    }
}

/// Results returned by a credit-default-swap pricing engine (the C++
/// `CreditDefaultSwap::results`, `creditdefaultswap.hpp:331-342`).
///
/// A result the engine did not provide is `None`, the C++ `Null<Real>` /
/// `Null<Rate>` sentinel [`reset`](Results::reset) restores; the matching
/// accessor on the instrument then reports it as not available.
#[derive(Default)]
pub struct CdsResults {
    /// The instrument-level results (NPV and the rest).
    pub instrument: InstrumentResults,
    /// The spread that prices the contract at zero.
    pub fair_spread: Option<Rate>,
    /// The upfront that prices the contract at zero.
    pub fair_upfront: Option<Rate>,
    /// The premium leg's sensitivity to a one-basis-point spread move.
    pub coupon_leg_bps: Option<Real>,
    /// The premium leg's NPV.
    pub coupon_leg_npv: Option<Real>,
    /// The protection leg's NPV.
    pub default_leg_npv: Option<Real>,
    /// The upfront payment's sensitivity to a one-basis-point upfront move.
    pub upfront_bps: Option<Real>,
    /// The upfront payment's NPV.
    pub upfront_npv: Option<Real>,
    /// The accrual rebate's NPV.
    pub accrual_rebate_npv: Option<Real>,
}

impl Results for CdsResults {
    fn reset(&mut self) {
        self.instrument.reset();
        self.fair_spread = None;
        self.fair_upfront = None;
        self.coupon_leg_bps = None;
        self.coupon_leg_npv = None;
        self.default_leg_npv = None;
        self.upfront_bps = None;
        self.upfront_npv = None;
        self.accrual_rebate_npv = None;
    }

    fn as_instrument_results(&self) -> Option<&InstrumentResults> {
        Some(&self.instrument)
    }
}

/// Engine base for credit-default swaps (the C++ `CreditDefaultSwap::engine`,
/// `creditdefaultswap.hpp:344-346`).
pub type CdsEngine = GenericEngine<CdsArguments, CdsResults>;

/// The model a quoted contract is inverted under
/// (`CreditDefaultSwap::PricingModel`, `creditdefaultswap.hpp:61-64`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PricingModel {
    /// The mid-point engine, which is not ISDA conform
    /// (`creditdefaultswap.hpp:51-52`).
    Midpoint,
    /// The ISDA engine.
    Isda,
}

/// A credit-default swap quoted as a running spread.
///
/// One side pays the premium leg and receives the protection payment, the other
/// the reverse; which way round is [`side`](CreditDefaultSwap::side).
pub struct CreditDefaultSwap {
    base: InstrumentBase,
    settings: Shared<Settings<Date>>,
    side: ProtectionSide,
    notional: Real,
    upfront: Option<Rate>,
    running_spread: Rate,
    settles_accrual: bool,
    pays_at_default_time: bool,
    claim: Shared<dyn Claim>,
    protection_start: Date,
    trade_date: Date,
    cash_settlement_days: Natural,
    leg: Leg,
    upfront_payment: Shared<SimpleCashFlow>,
    accrual_rebate: Option<Shared<SimpleCashFlow>>,
    maturity: Date,
    fair_spread: Option<Rate>,
    fair_upfront: Option<Rate>,
    coupon_leg_bps: Option<Real>,
    coupon_leg_npv: Option<Real>,
    default_leg_npv: Option<Real>,
    upfront_bps: Option<Real>,
    upfront_npv: Option<Real>,
    accrual_rebate_npv: Option<Real>,
}

impl CreditDefaultSwap {
    /// A contract on the C++ default terms, settling its accrual and paying at
    /// default time as `settles_accrual` and `pays_at_default_time` say
    /// (`creditdefaultswap.cpp:39-60`).
    ///
    /// The remaining terms take their C++ defaults; [`with_terms`] gives them.
    ///
    /// # Errors
    ///
    /// As [`with_terms`].
    ///
    /// [`with_terms`]: CreditDefaultSwap::with_terms
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        side: ProtectionSide,
        notional: Real,
        spread: Rate,
        schedule: Schedule,
        payment_convention: BusinessDayConvention,
        day_counter: DayCounter,
        settles_accrual: bool,
        pays_at_default_time: bool,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CreditDefaultSwap> {
        CreditDefaultSwap::with_terms(
            side,
            notional,
            spread,
            schedule,
            payment_convention,
            day_counter,
            CdsTerms {
                settles_accrual,
                pays_at_default_time,
                ..CdsTerms::default()
            },
            settings,
        )
    }

    /// A contract on the given `terms` (`creditdefaultswap.cpp:39-60` and its
    /// `init`, `:87-176`).
    ///
    /// # Errors
    ///
    /// Errors on an empty schedule, on a protection start after the first
    /// accrual date under a pre-Big-Bang date-generation rule, on a cash
    /// settlement date before the protection start, and on a premium leg
    /// carrying a flow that is not a coupon to rebate. Propagates the premium
    /// leg's own preconditions.
    #[allow(clippy::too_many_arguments)]
    pub fn with_terms(
        side: ProtectionSide,
        notional: Real,
        spread: Rate,
        schedule: Schedule,
        payment_convention: BusinessDayConvention,
        day_counter: DayCounter,
        terms: CdsTerms,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CreditDefaultSwap> {
        CreditDefaultSwap::build(
            side,
            notional,
            None,
            spread,
            schedule,
            payment_convention,
            day_counter,
            terms,
            settings,
        )
    }

    /// A contract quoted as an upfront plus a running spread, on the C++
    /// default terms (`creditdefaultswap.cpp:62-85`). The remaining terms take
    /// their C++ defaults; [`with_upfront_and_terms`] gives them.
    ///
    /// # Errors
    ///
    /// As [`with_terms`](CreditDefaultSwap::with_terms).
    ///
    /// [`with_upfront_and_terms`]: CreditDefaultSwap::with_upfront_and_terms
    #[allow(clippy::too_many_arguments)]
    pub fn with_upfront(
        side: ProtectionSide,
        notional: Real,
        upfront: Rate,
        spread: Rate,
        schedule: Schedule,
        payment_convention: BusinessDayConvention,
        day_counter: DayCounter,
        settles_accrual: bool,
        pays_at_default_time: bool,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CreditDefaultSwap> {
        CreditDefaultSwap::with_upfront_and_terms(
            side,
            notional,
            upfront,
            spread,
            schedule,
            payment_convention,
            day_counter,
            CdsTerms {
                settles_accrual,
                pays_at_default_time,
                ..CdsTerms::default()
            },
            settings,
        )
    }

    /// A contract quoted as an upfront plus a running spread, on the given
    /// `terms` (`creditdefaultswap.cpp:62-85`).
    ///
    /// # Errors
    ///
    /// As [`with_terms`](CreditDefaultSwap::with_terms).
    #[allow(clippy::too_many_arguments)]
    pub fn with_upfront_and_terms(
        side: ProtectionSide,
        notional: Real,
        upfront: Rate,
        spread: Rate,
        schedule: Schedule,
        payment_convention: BusinessDayConvention,
        day_counter: DayCounter,
        terms: CdsTerms,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CreditDefaultSwap> {
        CreditDefaultSwap::build(
            side,
            notional,
            Some(upfront),
            spread,
            schedule,
            payment_convention,
            day_counter,
            terms,
            settings,
        )
    }

    /// The shared C++ `init` (`creditdefaultswap.cpp:87-176`), which both
    /// quotations reach through their own constructor.
    #[allow(clippy::too_many_arguments)]
    fn build(
        side: ProtectionSide,
        notional: Real,
        upfront: Option<Rate>,
        spread: Rate,
        schedule: Schedule,
        payment_convention: BusinessDayConvention,
        day_counter: DayCounter,
        terms: CdsTerms,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CreditDefaultSwap> {
        require!(
            !schedule.is_empty(),
            "CreditDefaultSwap needs a non-empty schedule."
        );
        let protection_start = terms.protection_start.unwrap_or_else(|| schedule.date(0));

        let post_big_bang = schedule.has_rule()
            && matches!(
                schedule.rule(),
                DateGeneration::CDS | DateGeneration::CDS2015
            );
        if !post_big_bang {
            require!(
                protection_start <= schedule.date(0),
                "protection can not start after accrual"
            );
        }

        let mut builder = FixedRateLeg::new(schedule.clone())
            .with_notional(notional)
            .with_coupon_rate(spread, day_counter, Compounding::Simple, Frequency::Annual)?
            .with_payment_adjustment(payment_convention);
        if let Some(day_counter) = terms.last_period_day_counter {
            builder = builder.with_last_period_day_counter(day_counter);
        }
        let leg = builder.build()?;

        let trade_date = terms.trade_date.unwrap_or_else(|| {
            if post_big_bang {
                protection_start
            } else {
                protection_start - 1
            }
        });

        let effective_upfront_date = terms.upfront_date.unwrap_or_else(|| {
            schedule.calendar().advance(
                trade_date,
                terms.cash_settlement_days as Integer,
                TimeUnit::Days,
                payment_convention,
                false,
            )
        });
        require!(
            effective_upfront_date >= protection_start,
            "The cash settlement date must not be before the protection start date."
        );

        let upfront_amount = upfront.map_or(0.0, |upfront| upfront * notional);
        let upfront_payment = shared(SimpleCashFlow::new(upfront_amount, effective_upfront_date)?);

        let accrual_rebate = if terms.rebates_accrual {
            let mut rebate_amount = 0.0;
            let reference_date = trade_date + 1;
            if trade_date >= schedule.date(0) {
                let last = leg.len() - 1;
                for (i, flow) in leg.iter().enumerate() {
                    let payment_date = flow.date();
                    if reference_date > payment_date {
                        continue;
                    }
                    let Some(coupon) = flow.as_coupon() else {
                        fail!("premium leg flow #{} is not a coupon", i + 1);
                    };
                    if reference_date == payment_date {
                        if i == last {
                            rebate_amount = coupon.amount()?;
                        }
                    } else {
                        rebate_amount = coupon.accrued_amount(reference_date)?;
                    }
                    break;
                }
            }
            Some(shared(SimpleCashFlow::new(
                rebate_amount,
                effective_upfront_date,
            )?))
        } else {
            None
        };

        let base = InstrumentBase::new();
        settings.register_eval_date_observer(&base.observer());

        Ok(CreditDefaultSwap {
            base,
            settings,
            side,
            notional,
            upfront,
            running_spread: spread,
            settles_accrual: terms.settles_accrual,
            pays_at_default_time: terms.pays_at_default_time,
            claim: terms.claim.unwrap_or_else(|| shared(FaceValueClaim)),
            protection_start,
            trade_date,
            cash_settlement_days: terms.cash_settlement_days,
            leg,
            upfront_payment,
            accrual_rebate,
            maturity: schedule.date(schedule.len() - 1),
            fair_spread: None,
            fair_upfront: None,
            coupon_leg_bps: None,
            coupon_leg_npv: None,
            default_leg_npv: None,
            upfront_bps: None,
            upfront_npv: None,
            accrual_rebate_npv: None,
        })
    }

    /// Which side of the protection this contract holds.
    pub fn side(&self) -> ProtectionSide {
        self.side
    }

    /// The notional the protection covers.
    pub fn notional(&self) -> Real {
        self.notional
    }

    /// The running spread the premium leg pays.
    pub fn running_spread(&self) -> Rate {
        self.running_spread
    }

    /// The upfront, in fractional units, when the contract quotes one
    /// (`creditdefaultswap.cpp:78`); `None` on a running-spread contract.
    pub fn upfront(&self) -> Option<Rate> {
        self.upfront
    }

    /// Whether the accrued coupon is due on a default.
    pub fn settles_accrual(&self) -> bool {
        self.settles_accrual
    }

    /// Whether a default pays at default time.
    pub fn pays_at_default_time(&self) -> bool {
        self.pays_at_default_time
    }

    /// What a default pays out.
    pub fn claim(&self) -> &Shared<dyn Claim> {
        &self.claim
    }

    /// The premium leg.
    pub fn coupons(&self) -> &Leg {
        &self.leg
    }

    /// The first date a default triggers the contract.
    pub fn protection_start_date(&self) -> Date {
        self.protection_start
    }

    /// The schedule's last date.
    pub fn maturity(&self) -> Date {
        self.maturity
    }

    /// The upfront payment, due on the cash settlement date.
    pub fn upfront_payment(&self) -> &Shared<SimpleCashFlow> {
        &self.upfront_payment
    }

    /// The accrual rebate, when the contract carries one.
    pub fn accrual_rebate(&self) -> Option<&Shared<SimpleCashFlow>> {
        self.accrual_rebate.as_ref()
    }

    /// Whether the protection seller rebates the accrued current coupon
    /// (`creditdefaultswap.hpp:186`).
    pub fn rebates_accrual(&self) -> bool {
        self.accrual_rebate.is_some()
    }

    /// The contract's trade date.
    pub fn trade_date(&self) -> Date {
        self.trade_date
    }

    /// The business days from the trade date to cash settlement.
    pub fn cash_settlement_days(&self) -> Natural {
        self.cash_settlement_days
    }

    /// The spread that prices the contract at zero
    /// (`creditdefaultswap.cpp:266-271`).
    ///
    /// # Errors
    ///
    /// The calculation must succeed and the engine must have provided the
    /// value; an engine pricing a worthless premium leg does not
    /// (`midpointcdsengine.cpp:156-157`).
    pub fn fair_spread(&mut self) -> QlResult<Rate> {
        self.calculate()?;
        let Some(value) = self.fair_spread else {
            fail!("fair spread not available");
        };
        Ok(value)
    }

    /// The upfront that prices the contract at zero
    /// (`creditdefaultswap.cpp:259-264`).
    ///
    /// # Errors
    ///
    /// As [`fair_spread`](CreditDefaultSwap::fair_spread).
    pub fn fair_upfront(&mut self) -> QlResult<Rate> {
        self.calculate()?;
        let Some(value) = self.fair_upfront else {
            fail!("fair upfront not available");
        };
        Ok(value)
    }

    /// The premium leg's sensitivity to a one-basis-point spread move
    /// (`creditdefaultswap.cpp:273-278`).
    ///
    /// # Errors
    ///
    /// As [`fair_spread`](CreditDefaultSwap::fair_spread).
    pub fn coupon_leg_bps(&mut self) -> QlResult<Real> {
        self.calculate()?;
        let Some(value) = self.coupon_leg_bps else {
            fail!("coupon-leg BPS not available");
        };
        Ok(value)
    }

    /// The premium leg's NPV (`creditdefaultswap.cpp:280-285`).
    ///
    /// # Errors
    ///
    /// As [`fair_spread`](CreditDefaultSwap::fair_spread).
    pub fn coupon_leg_npv(&mut self) -> QlResult<Real> {
        self.calculate()?;
        let Some(value) = self.coupon_leg_npv else {
            fail!("coupon-leg NPV not available");
        };
        Ok(value)
    }

    /// The protection leg's NPV (`creditdefaultswap.cpp:287-292`).
    ///
    /// # Errors
    ///
    /// As [`fair_spread`](CreditDefaultSwap::fair_spread).
    pub fn default_leg_npv(&mut self) -> QlResult<Real> {
        self.calculate()?;
        let Some(value) = self.default_leg_npv else {
            fail!("default-leg NPV not available");
        };
        Ok(value)
    }

    /// The upfront payment's NPV (`creditdefaultswap.cpp:294-299`).
    ///
    /// # Errors
    ///
    /// As [`fair_spread`](CreditDefaultSwap::fair_spread).
    pub fn upfront_npv(&mut self) -> QlResult<Real> {
        self.calculate()?;
        let Some(value) = self.upfront_npv else {
            fail!("upfront NPV not available");
        };
        Ok(value)
    }

    /// The upfront payment's sensitivity to a one-basis-point upfront move
    /// (`creditdefaultswap.cpp:301-306`).
    ///
    /// # Errors
    ///
    /// As [`fair_spread`](CreditDefaultSwap::fair_spread).
    pub fn upfront_bps(&mut self) -> QlResult<Real> {
        self.calculate()?;
        let Some(value) = self.upfront_bps else {
            fail!("upfront BPS not available");
        };
        Ok(value)
    }

    /// The accrual rebate's NPV (`creditdefaultswap.cpp:308-313`).
    ///
    /// # Errors
    ///
    /// As [`fair_spread`](CreditDefaultSwap::fair_spread), and additionally on
    /// an expired contract, which C++ leaves reading an uninitialised member.
    pub fn accrual_rebate_npv(&mut self) -> QlResult<Real> {
        self.calculate()?;
        let Some(value) = self.accrual_rebate_npv else {
            fail!("accrual Rebate NPV not available");
        };
        Ok(value)
    }

    /// The flat hazard rate that prices this contract at `target_npv`
    /// (`creditdefaultswap.cpp:339-381`).
    ///
    /// A Brent solve over the one quote of a [`FlatHazardRate`] curve, started
    /// from the running spread grossed up by the loss given default - already a
    /// very close guess when `target_npv` is zero
    /// (`creditdefaultswap.cpp:377-380`).
    ///
    /// The contract is set up on the solving engine once and only the quote
    /// moves between iterations, as in C++. Unlike C++, which inverts an
    /// unvalidated bundle, the port validates it first, so that a malformed
    /// contract reports itself rather than reaching the solver as a pricing
    /// failure it can only report as a failure to bracket (D4).
    ///
    /// [`PricingModel::Midpoint`] solves on a [`MidPointCdsEngine`] and
    /// [`PricingModel::Isda`] on an [`IsdaCdsEngine`] carrying the three
    /// fidelity flags C++ spells out at the call site
    /// (`creditdefaultswap.cpp:361-368`).
    ///
    /// # Errors
    ///
    /// Errors on a malformed contract, and if the solve does not converge -
    /// which includes a pricing failure at some hazard rate, since that reaches
    /// the solver as the non-finite value it rejects.
    pub fn implied_hazard_rate(
        &self,
        target_npv: Real,
        discount_curve: &Handle<dyn YieldTermStructure>,
        day_counter: DayCounter,
        recovery_rate: Real,
        accuracy: Real,
        model: PricingModel,
    ) -> QlResult<Rate> {
        let flat_rate = shared(SimpleQuote::new(0.0));
        let probability = Handle::new(shared(FlatHazardRate::moving(
            0,
            WeekendsOnly::new(),
            Handle::new(Shared::clone(&flat_rate) as Shared<dyn Quote>),
            day_counter,
            Shared::clone(&self.settings),
        )) as Shared<dyn DefaultProbabilityTermStructure>);
        let mut engine: Box<dyn PricingEngine> = match model {
            PricingModel::Midpoint => Box::new(MidPointCdsEngine::new(
                probability,
                recovery_rate,
                discount_curve.clone(),
                None,
                Shared::clone(&self.settings),
            )),
            PricingModel::Isda => Box::new(
                IsdaCdsEngine::new(
                    probability,
                    recovery_rate,
                    discount_curve.clone(),
                    None,
                    Shared::clone(&self.settings),
                )
                .with_fidelity(
                    NumericalFix::Taylor,
                    AccrualBias::HalfDayBias,
                    ForwardsInCouponPeriod::Piecewise,
                ),
            ),
        };
        self.setup_arguments(engine.arguments_mut())?;
        engine.arguments_mut().validate()?;

        let objective = |hazard_rate: Rate| -> Real {
            flat_rate.set_value(hazard_rate);
            if engine.calculate().is_err() {
                return Real::NAN;
            }
            match (engine.results() as &dyn Any).downcast_ref::<CdsResults>() {
                Some(results) => results.instrument.value.unwrap_or(Real::NAN) - target_npv,
                None => Real::NAN,
            }
        };
        let guess = self.running_spread / (1.0 - recovery_rate) * 365.0 / 360.0;
        Brent::new().solve(objective, accuracy, guess, 0.1 * guess)
    }

    /// The spread that quotes the contract on conventional terms
    /// (`conventionalSpread`, `creditdefaultswap.cpp:383-423`).
    ///
    /// Solves the flat hazard rate that prices the contract - upfront and all -
    /// to nothing at `conventional_recovery`, then reports the engine's fair
    /// spread on that curve. Where [`implied_hazard_rate`] returns the rate it
    /// solved for, this returns the spread read off the results at it: the two
    /// differ by the upfront, which enters the priced value but not the fair
    /// spread (`midpointcdsengine.rs:246-247`), so a contract quoted with an
    /// upfront converts to a running spread away from its own.
    ///
    /// The target NPV (`0.0`), the recovery (`conventional_recovery`) and the
    /// accuracy (`1e-9`) are all fixed by C++ at the call site, so none is a
    /// parameter.
    ///
    /// # Errors
    ///
    /// As [`implied_hazard_rate`], and additionally if the engine reports no
    /// fair spread - which it does for a contract whose premium leg has no
    /// value left to spread over.
    ///
    /// [`implied_hazard_rate`]: CreditDefaultSwap::implied_hazard_rate
    pub fn conventional_spread(
        &self,
        conventional_recovery: Real,
        discount_curve: &Handle<dyn YieldTermStructure>,
        day_counter: DayCounter,
        model: PricingModel,
    ) -> QlResult<Rate> {
        let flat_rate = shared(SimpleQuote::new(0.0));
        let probability = Handle::new(shared(FlatHazardRate::moving(
            0,
            WeekendsOnly::new(),
            Handle::new(Shared::clone(&flat_rate) as Shared<dyn Quote>),
            day_counter,
            Shared::clone(&self.settings),
        )) as Shared<dyn DefaultProbabilityTermStructure>);
        let mut engine: Box<dyn PricingEngine> = match model {
            PricingModel::Midpoint => Box::new(MidPointCdsEngine::new(
                probability,
                conventional_recovery,
                discount_curve.clone(),
                None,
                Shared::clone(&self.settings),
            )),
            PricingModel::Isda => Box::new(
                IsdaCdsEngine::new(
                    probability,
                    conventional_recovery,
                    discount_curve.clone(),
                    None,
                    Shared::clone(&self.settings),
                )
                .with_fidelity(
                    NumericalFix::Taylor,
                    AccrualBias::HalfDayBias,
                    ForwardsInCouponPeriod::Piecewise,
                ),
            ),
        };
        self.setup_arguments(engine.arguments_mut())?;
        engine.arguments_mut().validate()?;

        let objective = |hazard_rate: Rate| -> Real {
            flat_rate.set_value(hazard_rate);
            if engine.calculate().is_err() {
                return Real::NAN;
            }
            match (engine.results() as &dyn Any).downcast_ref::<CdsResults>() {
                Some(results) => results.instrument.value.unwrap_or(Real::NAN),
                None => Real::NAN,
            }
        };
        let guess = self.running_spread / (1.0 - conventional_recovery) * 365.0 / 360.0;
        Brent::new().solve(objective, 1.0e-9, guess, 0.1 * guess)?;

        match (engine.results() as &dyn Any).downcast_ref::<CdsResults>() {
            Some(results) => match results.fair_spread {
                Some(fair_spread) => Ok(fair_spread),
                None => fail!("the engine reported no fair spread at the conventional hazard rate"),
            },
            None => fail!("the engine did not report credit-default-swap results"),
        }
    }
}

impl Instrument for CreditDefaultSwap {
    fn base(&self) -> &InstrumentBase {
        &self.base
    }

    fn base_mut(&mut self) -> &mut InstrumentBase {
        &mut self.base
    }

    /// `creditdefaultswap.cpp:207-213`: expired once every premium flow has
    /// occurred.
    fn is_expired(&self) -> QlResult<bool> {
        for flow in self.leg.iter().rev() {
            if !flow.has_occurred(&self.settings, None, None)? {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// `creditdefaultswap.cpp:222-239`.
    fn setup_arguments(&self, arguments: &mut dyn Arguments) -> QlResult<()> {
        let Some(arguments) = (arguments as &mut dyn Any).downcast_mut::<CdsArguments>() else {
            fail!("wrong argument type");
        };
        arguments.side = Some(self.side);
        arguments.notional = Some(self.notional);
        arguments.leg = self.leg.clone();
        arguments.upfront_payment = Some(Shared::clone(&self.upfront_payment));
        arguments.accrual_rebate = self.accrual_rebate.as_ref().map(Shared::clone);
        arguments.settles_accrual = self.settles_accrual;
        arguments.pays_at_default_time = self.pays_at_default_time;
        arguments.claim = Some(Shared::clone(&self.claim));
        arguments.upfront = self.upfront;
        arguments.spread = Some(self.running_spread);
        arguments.protection_start = Some(self.protection_start);
        arguments.maturity = Some(self.maturity);
        Ok(())
    }

    /// `creditdefaultswap.cpp:215-220`, which zeroes seven of the eight
    /// results and leaves `accrualRebateNPV_` as it found it.
    fn setup_expired(&mut self) {
        let expired = InstrumentResults {
            value: Some(0.0),
            error_estimate: Some(0.0),
            ..InstrumentResults::default()
        };
        self.base_mut().store_results(&expired);
        self.fair_spread = Some(0.0);
        self.fair_upfront = Some(0.0);
        self.coupon_leg_bps = Some(0.0);
        self.upfront_bps = Some(0.0);
        self.coupon_leg_npv = Some(0.0);
        self.default_leg_npv = Some(0.0);
        self.upfront_npv = Some(0.0);
    }

    /// `creditdefaultswap.cpp:242-257`.
    fn fetch_results(&mut self, results: &dyn Results) -> QlResult<()> {
        let Some(results) = (results as &dyn Any).downcast_ref::<CdsResults>() else {
            fail!("wrong result type");
        };
        self.base_mut().store_results(&results.instrument);
        self.fair_spread = results.fair_spread;
        self.fair_upfront = results.fair_upfront;
        self.coupon_leg_bps = results.coupon_leg_bps;
        self.coupon_leg_npv = results.coupon_leg_npv;
        self.default_leg_npv = results.default_leg_npv;
        self.upfront_npv = results.upfront_npv;
        self.upfront_bps = results.upfront_bps;
        self.accrual_rebate_npv = results.accrual_rebate_npv;
        Ok(())
    }
}

/// The date a standard CDS traded on `trade_date` at a quoted `tenor` matures,
/// under one of the CDS date-generation rules.
///
/// Port of `cdsMaturity` (`creditdefaultswap.cpp:479-506`). The tenor must be
/// quoted in years or in a whole number of quarters, and `OldCDS` does not
/// admit a zero tenor.
///
/// `Ok(None)` stands for the null `Date` C++ returns in its one such case
/// (`creditdefaultswap.cpp:494`): a `CDS2015` contract quoted at a zero tenor
/// whose anchor date is 20 December or 20 June, which has already matured. All
/// other rejections are `Err` (D4).
pub fn cds_maturity(
    trade_date: Date,
    tenor: Period,
    rule: DateGeneration,
) -> QlResult<Option<Date>> {
    require!(
        matches!(
            rule,
            DateGeneration::CDS2015 | DateGeneration::CDS | DateGeneration::OldCDS
        ),
        "cds_maturity should only be used with date generation rule CDS2015, CDS or OldCDS"
    );
    require!(
        tenor.units() == TimeUnit::Years
            || (tenor.units() == TimeUnit::Months && tenor.length() % 3 == 0),
        "cds_maturity expects a tenor that is a multiple of 3 months."
    );
    if rule == DateGeneration::OldCDS {
        require!(
            tenor != Period::new(0, TimeUnit::Months),
            "A tenor of 0M is not supported for OldCDS."
        );
    }

    let mut anchor_date = previous_twentieth(trade_date, rule);
    if rule == DateGeneration::CDS2015
        && (anchor_date == Date::new(20, Month::December, anchor_date.year())
            || anchor_date == Date::new(20, Month::June, anchor_date.year()))
    {
        if tenor.length() == 0 {
            return Ok(None);
        }
        anchor_date = anchor_date - Period::new(3, TimeUnit::Months);
    }

    let maturity = anchor_date + tenor + Period::new(3, TimeUnit::Months);
    require!(
        maturity > trade_date,
        "error calculating CDS maturity. Tenor is {tenor}, trade date is {trade_date} \
         generating a maturity of {maturity} <= trade date."
    );

    Ok(Some(maturity))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cashflow::CashFlow;
    use crate::event::Event;
    use crate::math::interpolations::flat::BackwardFlat;
    use crate::patterns::observable::{AsObservable, Observable};
    use crate::shared::{SharedMut, shared_mut};
    use crate::termstructures::credit::interpolatedhazardratecurve::InterpolatedHazardRateCurve;
    use crate::termstructures::yields::FlatForward;
    use crate::time::calendars::target::Target;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::daycounters::actual365fixed::Actual365Fixed;
    use crate::time::schedule::MakeSchedule;

    const NOTIONAL: Real = 10_000_000.0;
    const SPREAD: Rate = 0.01;

    /// The day before the schedule's first accrual date, so that no premium
    /// flow has occurred and the contract is live.
    fn today() -> Date {
        Date::new(19, Month::June, 2026)
    }

    fn settings_today() -> Shared<Settings<Date>> {
        let settings = shared(Settings::new());
        settings.set_evaluation_date(today());
        settings
    }

    /// A ten-year semiannual contract on the conventions a standard CDS quotes
    /// with. The `Backward` rule keeps it pre-Big-Bang, which is the arm the
    /// trade-date deduction and the protection-start check both branch on.
    fn ten_year_schedule() -> Schedule {
        MakeSchedule::new()
            .from(Date::new(20, Month::June, 2026))
            .to(Date::new(20, Month::June, 2036))
            .with_frequency(Frequency::Semiannual)
            .with_calendar(WeekendsOnly::new())
            .with_convention(BusinessDayConvention::Following)
            .with_termination_date_convention(BusinessDayConvention::Unadjusted)
            .backwards()
            .build()
    }

    fn contract(terms: CdsTerms) -> QlResult<CreditDefaultSwap> {
        contract_priced_on(terms, settings_today())
    }

    fn contract_priced_on(
        terms: CdsTerms,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CreditDefaultSwap> {
        CreditDefaultSwap::with_terms(
            ProtectionSide::Buyer,
            NOTIONAL,
            SPREAD,
            ten_year_schedule(),
            BusinessDayConvention::Following,
            Actual360::new(),
            terms,
            settings,
        )
    }

    #[test]
    fn the_premium_leg_spans_the_schedule_and_the_contract_matures_with_it() {
        let schedule = ten_year_schedule();
        let cds = CreditDefaultSwap::new(
            ProtectionSide::Buyer,
            NOTIONAL,
            SPREAD,
            schedule.clone(),
            BusinessDayConvention::Following,
            Actual360::new(),
            true,
            true,
            settings_today(),
        )
        .unwrap();

        assert_eq!(cds.coupons().len(), schedule.len() - 1);
        assert_eq!(cds.coupons().len(), 20);
        assert_eq!(
            Event::date(cds.coupons()[0].as_ref()),
            WeekendsOnly::new().adjust(schedule.date(1), BusinessDayConvention::Following)
        );
        assert_eq!(cds.maturity(), *schedule.dates().last().unwrap());
        assert_eq!(cds.side(), ProtectionSide::Buyer);
        assert_eq!(cds.notional(), NOTIONAL);
        assert_eq!(cds.running_spread(), SPREAD);
        assert!(cds.settles_accrual());
        assert!(cds.pays_at_default_time());
        assert_eq!(cds.cash_settlement_days(), 3);
    }

    /// `creditdefaultswap.cpp:110-116`, the pre-Big-Bang arm.
    #[test]
    fn the_trade_date_defaults_to_the_day_before_the_protection_start() {
        let cds = contract(CdsTerms::default()).unwrap();

        assert_eq!(cds.trade_date(), cds.protection_start_date() - 1);
    }

    /// `creditdefaultswap.cpp:56`.
    #[test]
    fn the_protection_starts_on_the_first_accrual_date_unless_given() {
        let schedule = ten_year_schedule();
        assert_eq!(
            contract(CdsTerms::default())
                .unwrap()
                .protection_start_date(),
            schedule.date(0)
        );

        let earlier = schedule.date(0) - 10;
        let cds = contract(CdsTerms {
            protection_start: Some(earlier),
            ..CdsTerms::default()
        })
        .unwrap();
        assert_eq!(cds.protection_start_date(), earlier);
        assert_eq!(cds.trade_date(), earlier - 1);
    }

    /// A running-spread contract quotes no upfront, so the payment is a zero
    /// flow that exists only for the engines to read
    /// (`creditdefaultswap.cpp:127-131`).
    #[test]
    fn the_upfront_payment_is_a_zero_flow_on_the_cash_settlement_date() {
        let cds = contract(CdsTerms::default()).unwrap();
        let expected = WeekendsOnly::new().advance(
            cds.trade_date(),
            3,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );

        assert_eq!(cds.upfront(), None);
        assert_eq!(cds.upfront_payment().amount().unwrap(), 0.0);
        assert_eq!(Event::date(cds.upfront_payment().as_ref()), expected);
        assert!(expected >= cds.protection_start_date());
    }

    /// `creditdefaultswap.cpp:62-85` and `:127-131`: the upfront-quoted
    /// constructor is the one path that sets `upfront_`, and the payment it
    /// makes is `upfront * notional` held unsigned, which is what leaves the
    /// protection side's sign to the engine.
    #[test]
    fn the_upfront_constructor_quotes_the_upfront_and_pays_it_unsigned() {
        for side in [ProtectionSide::Buyer, ProtectionSide::Seller] {
            let cds = CreditDefaultSwap::with_upfront(
                side,
                NOTIONAL,
                0.001,
                SPREAD,
                ten_year_schedule(),
                BusinessDayConvention::Following,
                Actual360::new(),
                true,
                true,
                settings_today(),
            )
            .unwrap();

            assert_eq!(cds.upfront(), Some(0.001));
            assert_eq!(cds.upfront_payment().amount().unwrap(), NOTIONAL * 0.001);
            assert_eq!(arguments(&cds).upfront, Some(0.001));
        }
    }

    /// `creditdefaultswap.cpp:118-123`: an upfront date given outright settles
    /// both cash flows, in place of the trade date advanced by the cash
    /// settlement days.
    #[test]
    fn an_upfront_date_given_outright_settles_both_cash_flows() {
        let deduced = contract(CdsTerms::default()).unwrap();
        let given = Event::date(deduced.upfront_payment().as_ref()) + 7;
        let cds = contract(CdsTerms {
            upfront_date: Some(given),
            ..CdsTerms::default()
        })
        .unwrap();

        assert_eq!(Event::date(cds.upfront_payment().as_ref()), given);
        assert_eq!(Event::date(cds.accrual_rebate().unwrap().as_ref()), given);
    }

    /// `creditdefaultswap.cpp:724-757` (`testAccrualRebateAmounts`), whose ten
    /// expected amounts come from the ISDA CDS model website.
    ///
    /// C++ builds each contract through `MakeCreditDefaultSwap`, which is not
    /// ported. The direct constructor reproduces it exactly rather than
    /// approximately: `MakeCreditDefaultSwap(termDate, spread)` takes the term
    /// date as the schedule's end and never consults `cdsMaturity`
    /// (`makecds.cpp:70-88`), and every term below is either one of its defaults
    /// (`makecds.hpp:118-138`) or the trade date it derives the rest from. Its
    /// `Actual360(true)` last-period day counter leaves the two 2014 rows
    /// untouched, whose two-date schedule takes no last-period override
    /// (`fixedratecoupon.cpp:235`).
    #[test]
    fn the_accrual_rebate_matches_the_isda_amounts() {
        let maturity = Date::new(20, Month::June, 2014);
        let expected = [
            (Date::new(18, Month::March, 2009), 24_166.67),
            (Date::new(19, Month::March, 2009), 0.00),
            (Date::new(20, Month::March, 2009), 277.78),
            (Date::new(23, Month::March, 2009), 1_111.11),
            (Date::new(19, Month::June, 2009), 25_555.56),
            (Date::new(20, Month::June, 2009), 25_833.33),
            (Date::new(21, Month::June, 2009), 0.00),
            (Date::new(22, Month::June, 2009), 277.78),
            (Date::new(18, Month::June, 2014), 25_277.78),
            (Date::new(19, Month::June, 2014), 25_555.56),
        ];

        for (trade_date, amount) in expected {
            let settings = shared(Settings::new());
            settings.set_evaluation_date(trade_date);
            let calendar = WeekendsOnly::new();
            let schedule = Schedule::new(
                trade_date,
                maturity,
                Period::new(3, TimeUnit::Months),
                calendar.clone(),
                BusinessDayConvention::Following,
                BusinessDayConvention::Unadjusted,
                DateGeneration::CDS,
                false,
                Date::null(),
                Date::null(),
            );
            let cds = CreditDefaultSwap::with_upfront_and_terms(
                ProtectionSide::Buyer,
                NOTIONAL,
                0.0,
                SPREAD,
                schedule,
                BusinessDayConvention::Following,
                Actual360::new(),
                CdsTerms {
                    protection_start: Some(trade_date),
                    upfront_date: Some(calendar.advance(
                        trade_date,
                        3,
                        TimeUnit::Days,
                        BusinessDayConvention::Following,
                        false,
                    )),
                    last_period_day_counter: Some(Actual360::with_last_day(true)),
                    trade_date: Some(trade_date),
                    ..CdsTerms::default()
                },
                settings,
            )
            .unwrap();

            let rebate = cds.accrual_rebate().unwrap().amount().unwrap();
            assert!(
                (rebate - amount).abs() < 0.01,
                "a contract traded on {trade_date} rebated {rebate} rather than {amount}"
            );
        }
    }

    /// `creditdefaultswap.cpp:138-171`: the rebate is a flow the contract either
    /// carries or does not, which is what `rebatesAccrual()` reads
    /// (`creditdefaultswap.hpp:186`).
    #[test]
    fn the_accrual_rebate_is_a_zero_flow_when_rebated_and_absent_otherwise() {
        let rebated = contract(CdsTerms::default()).unwrap();
        let rebate = rebated.accrual_rebate().unwrap();
        assert!(rebated.rebates_accrual());
        assert_eq!(rebate.amount().unwrap(), 0.0);
        assert_eq!(
            Event::date(rebate.as_ref()),
            Event::date(rebated.upfront_payment().as_ref())
        );

        let bare = contract(CdsTerms {
            rebates_accrual: false,
            ..CdsTerms::default()
        })
        .unwrap();
        assert!(bare.accrual_rebate().is_none());
        assert!(!bare.rebates_accrual());
    }

    /// `creditdefaultswap.cpp:91`. C++ reads `schedule[0]` for the protection
    /// start before this check runs; the port checks first, so an empty schedule
    /// is an error rather than an out-of-range index.
    #[test]
    fn an_empty_schedule_is_an_error_not_a_panic() {
        let empty = CreditDefaultSwap::with_terms(
            ProtectionSide::Buyer,
            NOTIONAL,
            SPREAD,
            Schedule::from_dates(Vec::new()),
            BusinessDayConvention::Following,
            Actual360::new(),
            CdsTerms::default(),
            settings_today(),
        );

        assert!(empty.is_err());
    }

    /// `creditdefaultswap.cpp:99-101`, which only guards the pre-Big-Bang arm.
    #[test]
    fn protection_can_not_start_after_the_first_accrual_date() {
        let late = ten_year_schedule().date(0) + 1;

        assert!(
            contract(CdsTerms {
                protection_start: Some(late),
                ..CdsTerms::default()
            })
            .is_err()
        );
    }

    /// `creditdefaultswap.cpp:143`: a trade date before the first accrual date
    /// skips the loop and rebates nothing, where one on or after it rebates the
    /// coupon accrued to the day after the trade (`:163-164`). The accrued
    /// amount is read off the coupon the loop must land on, not off a number
    /// this port produced.
    #[test]
    fn only_a_trade_date_on_or_after_the_first_accrual_date_rebates_anything() {
        let first_accrual = ten_year_schedule().date(0);

        let before = contract(CdsTerms::default()).unwrap();
        assert!(before.trade_date() < first_accrual);
        assert_eq!(before.accrual_rebate().unwrap().amount().unwrap(), 0.0);

        let on = contract(CdsTerms {
            trade_date: Some(first_accrual),
            ..CdsTerms::default()
        })
        .unwrap();
        let accrued = on.coupons()[0]
            .as_coupon()
            .unwrap()
            .accrued_amount(first_accrual + 1)
            .unwrap();
        assert!(accrued > 0.0);
        assert_eq!(on.accrual_rebate().unwrap().amount().unwrap(), accrued);
    }

    /// The post-Big-Bang arm of the trade-date deduction
    /// (`creditdefaultswap.cpp:111-112`): protection is effective on the trade
    /// date itself, and the protection-start check is skipped
    /// (`creditdefaultswap.cpp:94-101`).
    #[test]
    fn a_post_big_bang_contract_trades_on_the_protection_start() {
        let schedule = MakeSchedule::new()
            .from(Date::new(20, Month::June, 2026))
            .to(Date::new(20, Month::June, 2036))
            .with_frequency(Frequency::Quarterly)
            .with_calendar(WeekendsOnly::new())
            .with_convention(BusinessDayConvention::Following)
            .with_rule(DateGeneration::CDS)
            .build();
        let build = |terms| {
            CreditDefaultSwap::with_terms(
                ProtectionSide::Buyer,
                NOTIONAL,
                SPREAD,
                schedule.clone(),
                BusinessDayConvention::Following,
                Actual360::new(),
                terms,
                settings_today(),
            )
        };

        let cds = build(CdsTerms::default()).unwrap();
        assert_eq!(cds.trade_date(), cds.protection_start_date());
        assert_eq!(cds.protection_start_date(), schedule.date(0));
    }

    /// `creditdefaultswap.cpp:173-174`.
    #[test]
    fn the_claim_defaults_to_the_face_value() {
        let cds = contract(CdsTerms::default()).unwrap();

        assert_eq!(
            cds.claim().amount(&cds.maturity(), NOTIONAL, 0.4).unwrap(),
            NOTIONAL * 0.6
        );
    }

    /// The last-period day counter overrides the spread's on the last coupon
    /// alone, where an absent one leaves the spread's in place
    /// (`fixedratecoupon.cpp:255-257`).
    #[test]
    fn the_last_period_day_counter_reaches_the_last_coupon_only() {
        let plain = contract(CdsTerms::default()).unwrap();
        let overridden = contract(CdsTerms {
            last_period_day_counter: Some(Actual365Fixed::new()),
            ..CdsTerms::default()
        })
        .unwrap();

        let amount = |cds: &CreditDefaultSwap, i: usize| cds.coupons()[i].amount().unwrap();
        let last = plain.coupons().len() - 1;
        assert_ne!(amount(&plain, last), amount(&overridden, last));
        assert_eq!(amount(&plain, 0), amount(&overridden, 0));
    }

    /// The bundle the contract fills in, as an engine receives it.
    fn arguments(cds: &CreditDefaultSwap) -> CdsArguments {
        let mut arguments = CdsArguments::default();
        cds.setup_arguments(&mut arguments).unwrap();
        arguments
    }

    /// An engine that either fills every result or leaves them all as
    /// [`Results::reset`] left them, to tell "the engine did not provide it"
    /// from a provided value.
    struct StubEngine {
        base: CdsEngine,
        fills_results: bool,
    }

    impl AsObservable for StubEngine {
        fn observable(&self) -> &Observable {
            self.base.observable()
        }
    }

    impl PricingEngine for StubEngine {
        fn arguments_mut(&mut self) -> &mut dyn Arguments {
            self.base.arguments_mut()
        }

        fn results(&self) -> &dyn Results {
            self.base.results()
        }

        fn reset(&mut self) {
            self.base.reset();
        }

        fn calculate(&mut self) -> QlResult<()> {
            if !self.fills_results {
                return Ok(());
            }
            let results = self.base.results_mut();
            results.instrument.value = Some(1.0);
            results.fair_spread = Some(0.02);
            results.fair_upfront = Some(0.03);
            results.coupon_leg_bps = Some(4.0);
            results.coupon_leg_npv = Some(5.0);
            results.default_leg_npv = Some(6.0);
            results.upfront_bps = Some(7.0);
            results.upfront_npv = Some(8.0);
            results.accrual_rebate_npv = Some(9.0);
            Ok(())
        }
    }

    fn engine(fills_results: bool) -> SharedMut<StubEngine> {
        shared_mut(StubEngine {
            base: CdsEngine::new(CdsArguments::default(), CdsResults::default()),
            fills_results,
        })
    }

    /// `creditdefaultswap.cpp:222-239`: every field the engine reads reaches it,
    /// carrying the contract's own values rather than the bundle's defaults.
    #[test]
    fn setup_arguments_round_trips_the_contract_into_the_bundle() {
        let cds = contract(CdsTerms::default()).unwrap();
        let arguments = arguments(&cds);

        assert_eq!(arguments.side, Some(ProtectionSide::Buyer));
        assert_eq!(arguments.notional, Some(NOTIONAL));
        assert_eq!(arguments.spread, Some(SPREAD));
        assert_eq!(arguments.upfront, None);
        assert_eq!(arguments.leg.len(), cds.coupons().len());
        assert!(Shared::ptr_eq(&arguments.leg[0], &cds.coupons()[0]));
        assert!(Shared::ptr_eq(
            arguments.upfront_payment.as_ref().unwrap(),
            cds.upfront_payment()
        ));
        assert!(Shared::ptr_eq(
            arguments.accrual_rebate.as_ref().unwrap(),
            cds.accrual_rebate().unwrap()
        ));
        assert!(arguments.settles_accrual);
        assert!(arguments.pays_at_default_time);
        assert_eq!(
            arguments
                .claim
                .as_ref()
                .unwrap()
                .amount(&cds.maturity(), NOTIONAL, 0.4)
                .unwrap(),
            NOTIONAL * 0.6
        );
        assert_eq!(
            arguments.protection_start,
            Some(cds.protection_start_date())
        );
        assert_eq!(arguments.maturity, Some(cds.maturity()));
    }

    /// A contract without a rebate leaves the bundle's rebate empty, which is
    /// the one null `shared_ptr` `validate` does not reject.
    #[test]
    fn an_unrebated_contract_leaves_the_bundle_rebate_empty() {
        let cds = contract(CdsTerms {
            rebates_accrual: false,
            ..CdsTerms::default()
        })
        .unwrap();
        let arguments = arguments(&cds);

        assert!(arguments.accrual_rebate.is_none());
        assert!(arguments.validate().is_ok());
    }

    /// `creditdefaultswap.cpp:455-465`, message for message. A zero notional is
    /// rejected separately from an unset one, as C++ rejects `Null<Real>` and
    /// `0.0` with different messages.
    #[test]
    fn validate_rejects_each_unset_field_with_the_cpp_message() {
        let cds = contract(CdsTerms::default()).unwrap();
        assert!(arguments(&cds).validate().is_ok());

        let rejects = |breaks: fn(&mut CdsArguments), message: &str| {
            let mut arguments = arguments(&cds);
            breaks(&mut arguments);
            assert_eq!(arguments.validate().unwrap_err().message(), message);
        };

        rejects(|a| a.side = None, "side not set");
        rejects(|a| a.notional = None, "notional not set");
        rejects(|a| a.notional = Some(0.0), "null notional set");
        rejects(|a| a.spread = None, "spread not set");
        rejects(|a| a.leg.clear(), "coupons not set");
        rejects(|a| a.upfront_payment = None, "upfront payment not set");
        rejects(|a| a.claim = None, "claim not set");
        rejects(
            |a| a.protection_start = None,
            "protection start date not set",
        );
        rejects(|a| a.maturity = None, "maturity date not set");
    }

    /// `creditdefaultswap.cpp:467-477`: reset restores the `Null` sentinels,
    /// which are `None` here, across all eight results and the instrument's own.
    #[test]
    fn reset_clears_every_result() {
        let mut results = CdsResults {
            instrument: InstrumentResults {
                value: Some(1.0),
                ..InstrumentResults::default()
            },
            fair_spread: Some(0.02),
            fair_upfront: Some(0.03),
            coupon_leg_bps: Some(4.0),
            coupon_leg_npv: Some(5.0),
            default_leg_npv: Some(6.0),
            upfront_bps: Some(7.0),
            upfront_npv: Some(8.0),
            accrual_rebate_npv: Some(9.0),
        };

        results.reset();

        assert_eq!(results.instrument.value, None);
        assert_eq!(results.fair_spread, None);
        assert_eq!(results.fair_upfront, None);
        assert_eq!(results.coupon_leg_bps, None);
        assert_eq!(results.coupon_leg_npv, None);
        assert_eq!(results.default_leg_npv, None);
        assert_eq!(results.upfront_bps, None);
        assert_eq!(results.upfront_npv, None);
        assert_eq!(results.accrual_rebate_npv, None);
    }

    /// `creditdefaultswap.cpp:242-257`: the engine's results reach the
    /// accessors, which price the contract first.
    #[test]
    fn the_accessors_read_the_engine_results() {
        let mut cds = contract(CdsTerms::default()).unwrap();
        cds.base_mut().set_pricing_engine(engine(true));

        assert_eq!(cds.npv().unwrap(), 1.0);
        assert_eq!(cds.fair_spread().unwrap(), 0.02);
        assert_eq!(cds.fair_upfront().unwrap(), 0.03);
        assert_eq!(cds.coupon_leg_bps().unwrap(), 4.0);
        assert_eq!(cds.coupon_leg_npv().unwrap(), 5.0);
        assert_eq!(cds.default_leg_npv().unwrap(), 6.0);
        assert_eq!(cds.upfront_bps().unwrap(), 7.0);
        assert_eq!(cds.upfront_npv().unwrap(), 8.0);
        assert_eq!(cds.accrual_rebate_npv().unwrap(), 9.0);
    }

    /// A result the engine left alone is the C++ `Null` the accessor rejects
    /// (`creditdefaultswap.cpp:259-313`), message for message.
    #[test]
    fn unprovided_results_are_not_available() {
        let mut cds = contract(CdsTerms::default()).unwrap();
        cds.base_mut().set_pricing_engine(engine(false));

        let message = |result: QlResult<Real>| result.unwrap_err().message().to_string();
        assert_eq!(message(cds.fair_spread()), "fair spread not available");
        assert_eq!(message(cds.fair_upfront()), "fair upfront not available");
        assert_eq!(
            message(cds.coupon_leg_bps()),
            "coupon-leg BPS not available"
        );
        assert_eq!(
            message(cds.coupon_leg_npv()),
            "coupon-leg NPV not available"
        );
        assert_eq!(
            message(cds.default_leg_npv()),
            "default-leg NPV not available"
        );
        assert_eq!(message(cds.upfront_bps()), "upfront BPS not available");
        assert_eq!(message(cds.upfront_npv()), "upfront NPV not available");
        assert_eq!(
            message(cds.accrual_rebate_npv()),
            "accrual Rebate NPV not available"
        );
    }

    /// An accessor prices the contract before reading, so with no engine
    /// installed it surfaces the failure to price rather than a stale value.
    #[test]
    fn an_accessor_on_an_unpriced_contract_reports_the_missing_engine() {
        let mut cds = contract(CdsTerms::default()).unwrap();

        assert_eq!(
            cds.fair_spread().unwrap_err().message(),
            "null pricing engine"
        );
    }

    /// `creditdefaultswap.cpp:215-220` zeroes seven results, not eight:
    /// `accrualRebateNPV_` is absent there and uninitialised in the header
    /// (`creditdefaultswap.hpp:302`), so C++ reads a garbage value from it on an
    /// expired contract where this port reports it as unavailable. An expired
    /// contract needs no engine to answer, which is what distinguishes these
    /// zeros from an engine's results.
    #[test]
    fn an_expired_contract_zeroes_seven_results_and_leaves_the_rebate_unavailable() {
        let settings = shared(Settings::new());
        settings.set_evaluation_date(Date::new(21, Month::June, 2036));
        let mut cds = contract_priced_on(CdsTerms::default(), settings).unwrap();
        assert!(cds.is_expired().unwrap());

        assert_eq!(cds.npv().unwrap(), 0.0);
        assert_eq!(cds.fair_spread().unwrap(), 0.0);
        assert_eq!(cds.fair_upfront().unwrap(), 0.0);
        assert_eq!(cds.coupon_leg_bps().unwrap(), 0.0);
        assert_eq!(cds.coupon_leg_npv().unwrap(), 0.0);
        assert_eq!(cds.default_leg_npv().unwrap(), 0.0);
        assert_eq!(cds.upfront_bps().unwrap(), 0.0);
        assert_eq!(cds.upfront_npv().unwrap(), 0.0);
        assert_eq!(
            cds.accrual_rebate_npv().unwrap_err().message(),
            "accrual Rebate NPV not available"
        );
    }

    /// `creditdefaultswap.cpp:207-213`: live while any premium flow is still to
    /// pay, expired once the last one has paid.
    #[test]
    fn is_expired_tracks_the_premium_legs_flows() {
        assert!(!contract(CdsTerms::default()).unwrap().is_expired().unwrap());

        let settings = shared(Settings::new());
        settings.set_evaluation_date(Date::new(19, Month::June, 2036));
        let last_coupon_due = contract_priced_on(CdsTerms::default(), settings).unwrap();
        assert!(
            !last_coupon_due.is_expired().unwrap(),
            "the final premium flow has not paid yet"
        );

        let settings = shared(Settings::new());
        settings.set_evaluation_date(Date::new(21, Month::June, 2036));
        let matured = contract_priced_on(CdsTerms::default(), settings).unwrap();
        assert!(
            matured.is_expired().unwrap(),
            "the final premium flow has paid"
        );
    }

    /// The contract observes the evaluation date the C++ `Instrument` base
    /// registers with through the settings singleton (`instrument.cpp:26-32`),
    /// which D5 replaces with the [`Settings`] the constructor is handed: moving
    /// the date invalidates the cached results.
    #[test]
    fn an_evaluation_date_change_invalidates_the_contract() {
        let settings = settings_today();
        let mut cds = contract_priced_on(CdsTerms::default(), Shared::clone(&settings)).unwrap();
        cds.base_mut().set_pricing_engine(engine(true));

        cds.npv().unwrap();
        assert!(cds.base().is_calculated());

        settings.set_evaluation_date(today() + 1);
        assert!(
            !cds.base().is_calculated(),
            "an evaluation-date change invalidates the contract"
        );
    }

    /// The maturity a tenor implies is graded against the CDS date-generation
    /// grids in `schedule.rs`, which the C++ test suite also keeps in
    /// `test-suite/schedule.cpp:415` rather than beside the function. What is
    /// left to pin here is the four rejections those grids never reach.
    fn rejection(tenor: Period, rule: DateGeneration) -> String {
        cds_maturity(Date::new(1, Month::March, 2017), tenor, rule)
            .unwrap_err()
            .message()
            .to_string()
    }

    #[test]
    fn only_the_three_cds_rules_imply_a_maturity() {
        let message = rejection(
            Period::new(5, TimeUnit::Years),
            DateGeneration::TwentiethIMM,
        );
        assert!(message.contains("CDS2015, CDS or OldCDS"), "{message}");
    }

    #[test]
    fn a_tenor_that_is_not_a_whole_number_of_quarters_is_rejected() {
        let message = rejection(Period::new(4, TimeUnit::Months), DateGeneration::CDS2015);
        assert!(message.contains("multiple of 3 months"), "{message}");
    }

    /// C++ compares the tenor against `0*Months` through the unit-converting
    /// `Period::operator==`, so a zero tenor quoted in years is the same zero and
    /// is rejected too. [`PartialEq`] ports that comparison rather than deriving
    /// on the unit, which is what keeps the two agreeing.
    #[test]
    fn a_zero_tenor_is_rejected_under_the_old_rule_alone() {
        let zero = Period::new(0, TimeUnit::Months);
        let message = rejection(zero, DateGeneration::OldCDS);
        assert!(
            message.contains("0M is not supported for OldCDS"),
            "{message}"
        );

        let message = rejection(Period::new(0, TimeUnit::Years), DateGeneration::OldCDS);
        assert!(
            message.contains("0M is not supported for OldCDS"),
            "a zero tenor quoted in years is the same zero: {message}"
        );

        let live = cds_maturity(
            Date::new(1, Month::December, 2016),
            zero,
            DateGeneration::CDS2015,
        );
        assert_eq!(live.unwrap(), Some(Date::new(20, Month::December, 2016)));
    }

    /// The guard is out of reach of a forward tenor: the anchor is the latest
    /// twentieth of an IMM month on or before the trade date, so it sits under
    /// three months back and the three months the maturity adds carry it past
    /// the trade date again. A tenor quoted backwards reaches it.
    #[test]
    fn a_maturity_on_or_before_the_trade_date_is_rejected() {
        let message = rejection(Period::new(-1, TimeUnit::Years), DateGeneration::CDS);
        assert!(message.contains("<= trade date"), "{message}");
    }

    /// `testImpliedHazardRate` (`creditdefaultswap.cpp:313-415`): a credit
    /// curve flat at 30% out to five years and 40% beyond, inverted through
    /// contracts maturing between the two.
    ///
    /// A contract straddling the step implies a flat rate strictly between the
    /// two, rising with maturity as more of the contract sits past the step.
    ///
    /// The evaluation date is a Monday and no TARGET holiday, which is what
    /// lets the moving curve the solve builds off `WeekendsOnly` and the fixed
    /// curve the round trip reprices on share a reference date - as they do in
    /// C++, which adjusts `todaysDate` onto a business day.
    #[test]
    fn the_implied_hazard_rate_brackets_the_curve_and_reprices_the_contract() {
        const H1: Rate = 0.30;
        const H2: Rate = 0.40;
        const RECOVERY: Real = 0.4;

        let calendar = Target::new();
        let today = Date::new(15, Month::June, 2026);
        let settings = shared(Settings::new());
        settings.set_evaluation_date(today);

        let probability_curve = Handle::new(shared(
            InterpolatedHazardRateCurve::new(
                vec![
                    today,
                    today + Period::new(5, TimeUnit::Years),
                    today + Period::new(10, TimeUnit::Years),
                ],
                vec![H1, H1, H2],
                Actual365Fixed::new(),
                BackwardFlat,
            )
            .unwrap(),
        )
            as Shared<dyn DefaultProbabilityTermStructure>);
        let discount_curve = Handle::new(shared(FlatForward::with_rate(
            today,
            0.03,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>);

        let issue_date = calendar.advance(
            today,
            -6,
            TimeUnit::Months,
            BusinessDayConvention::Following,
            false,
        );
        let mut previous: Option<Rate> = None;

        for n in 6..=10 {
            let maturity = calendar.advance(
                issue_date,
                n,
                TimeUnit::Years,
                BusinessDayConvention::Following,
                false,
            );
            let schedule = Schedule::new(
                issue_date,
                maturity,
                Period::new(6, TimeUnit::Months),
                calendar.clone(),
                BusinessDayConvention::ModifiedFollowing,
                BusinessDayConvention::ModifiedFollowing,
                DateGeneration::Forward,
                false,
                Date::null(),
                Date::null(),
            );
            let priced_on = |probability: Handle<dyn DefaultProbabilityTermStructure>| {
                let mut cds = CreditDefaultSwap::new(
                    ProtectionSide::Seller,
                    10_000.0,
                    0.0120,
                    schedule.clone(),
                    BusinessDayConvention::ModifiedFollowing,
                    Actual360::new(),
                    true,
                    true,
                    Shared::clone(&settings),
                )
                .unwrap();
                cds.base_mut()
                    .set_pricing_engine(shared_mut(MidPointCdsEngine::new(
                        probability,
                        RECOVERY,
                        discount_curve.clone(),
                        None,
                        Shared::clone(&settings),
                    )) as SharedMut<dyn PricingEngine>);
                cds
            };

            let mut cds = priced_on(probability_curve.clone());
            let npv = cds.npv().unwrap();
            let rate = cds
                .implied_hazard_rate(
                    npv,
                    &discount_curve,
                    Actual365Fixed::new(),
                    RECOVERY,
                    1.0e-8,
                    PricingModel::Midpoint,
                )
                .unwrap();

            assert!(
                (H1..=H2).contains(&rate),
                "the {n}Y implied rate {rate} is outside [{H1}, {H2}]"
            );
            if let Some(previous) = previous {
                assert!(
                    rate >= previous,
                    "the {n}Y implied rate {rate} falls below the previous {previous}"
                );
            }
            previous = Some(rate);

            let flat = Handle::new(shared(FlatHazardRate::new(
                today,
                Handle::new(shared(SimpleQuote::new(rate)) as Shared<dyn Quote>),
                Actual365Fixed::new(),
            ))
                as Shared<dyn DefaultProbabilityTermStructure>);
            let reproduced = priced_on(flat).npv().unwrap();
            assert!(
                (npv - reproduced).abs() < 1.0,
                "the {n}Y implied rate reprices to {reproduced}, not {npv}"
            );
        }
    }

    /// The fixture the two conventional-spread cases share: an eight-year
    /// contract whose schedule starts at the evaluation date, so its upfront is
    /// still unsettled there.
    ///
    /// That last part is load-bearing. `midpointcdsengine.rs:155-161` leaves
    /// `upfront_npv` at zero once the upfront has occurred, and the fair spread
    /// the engine reports omits `upfront_npv` from its numerator
    /// (`midpointcdsengine.rs:246-247`); a contract whose upfront already
    /// settled therefore converts back to its own running spread, and the cases
    /// below would pass against a `Ok(self.running_spread)` stub.
    fn conventional_spread_fixture(
        day_counter: DayCounter,
    ) -> (
        Shared<Settings<Date>>,
        Date,
        Schedule,
        Handle<dyn YieldTermStructure>,
    ) {
        let calendar = Target::new();
        let today = Date::new(15, Month::June, 2026);
        let settings = shared(Settings::new());
        settings.set_evaluation_date(today);

        let discount_curve = Handle::new(shared(FlatForward::with_rate(
            today,
            0.03,
            day_counter,
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>);
        let maturity = calendar.advance(
            today,
            8,
            TimeUnit::Years,
            BusinessDayConvention::Following,
            false,
        );
        let schedule = Schedule::new(
            today,
            maturity,
            Period::new(6, TimeUnit::Months),
            calendar,
            BusinessDayConvention::ModifiedFollowing,
            BusinessDayConvention::ModifiedFollowing,
            DateGeneration::Forward,
            false,
            Date::null(),
            Date::null(),
        );
        (settings, today, schedule, discount_curve)
    }

    const CONVENTIONAL_RECOVERY: Real = 0.4;
    const CONVENTIONAL_RUNNING: Rate = 0.0120;
    const CONVENTIONAL_UPFRONT: Rate = 0.05;
    const CONVENTIONAL_NOTIONAL: Real = 10_000.0;

    /// The contract the conventional spread converts, quoted with an upfront.
    fn upfront_quoted(schedule: Schedule, settings: &Shared<Settings<Date>>) -> CreditDefaultSwap {
        CreditDefaultSwap::with_upfront(
            ProtectionSide::Seller,
            CONVENTIONAL_NOTIONAL,
            CONVENTIONAL_UPFRONT,
            CONVENTIONAL_RUNNING,
            schedule,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            true,
            true,
            Shared::clone(settings),
        )
        .unwrap()
    }

    /// A flat hazard-rate curve at `hazard_rate`, the curve the conventional
    /// spread is quoted off.
    fn flat_credit(
        reference: Date,
        hazard_rate: Rate,
    ) -> Handle<dyn DefaultProbabilityTermStructure> {
        Handle::new(shared(FlatHazardRate::new(
            reference,
            Handle::new(shared(SimpleQuote::new(hazard_rate)) as Shared<dyn Quote>),
            Actual365Fixed::new(),
        )) as Shared<dyn DefaultProbabilityTermStructure>)
    }

    /// `creditdefaultswap.cpp:383-423` on the mid-point model: the spread that
    /// quotes a contract carrying an upfront as a running spread alone.
    ///
    /// Invented self-consistency, since C++ has no caller and the test suite no
    /// case. The upfront moves the conventional spread off the running one, and
    /// the same contract rebuilt at that spread with no upfront prices to
    /// nothing on the hazard rate the conversion solved for.
    #[test]
    fn the_conventional_spread_converts_an_upfront_into_a_running_spread() {
        let (settings, today, schedule, discount_curve) =
            conventional_spread_fixture(Actual360::new());
        let quoted = upfront_quoted(schedule.clone(), &settings);

        let hazard_rate = quoted
            .implied_hazard_rate(
                0.0,
                &discount_curve,
                Actual365Fixed::new(),
                CONVENTIONAL_RECOVERY,
                1.0e-9,
                PricingModel::Midpoint,
            )
            .unwrap();
        let conventional = quoted
            .conventional_spread(
                CONVENTIONAL_RECOVERY,
                &discount_curve,
                Actual365Fixed::new(),
                PricingModel::Midpoint,
            )
            .unwrap();

        assert!(
            (conventional - CONVENTIONAL_RUNNING).abs() > 1.0e-4,
            "the upfront left the conventional spread {conventional} at the running \
             {CONVENTIONAL_RUNNING}"
        );

        let mut converted = CreditDefaultSwap::new(
            ProtectionSide::Seller,
            CONVENTIONAL_NOTIONAL,
            conventional,
            schedule,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            true,
            true,
            Shared::clone(&settings),
        )
        .unwrap();
        converted
            .base_mut()
            .set_pricing_engine(shared_mut(MidPointCdsEngine::new(
                flat_credit(today, hazard_rate),
                CONVENTIONAL_RECOVERY,
                discount_curve,
                None,
                Shared::clone(&settings),
            )) as SharedMut<dyn PricingEngine>);

        let npv = converted.npv().unwrap();
        assert!(
            npv.abs() < 1.0,
            "the contract converted to {conventional} prices at {npv}, not nothing"
        );
    }

    /// The same conversion on the ISDA model, which the port supports wherever
    /// [`implied_hazard_rate`](CreditDefaultSwap::implied_hazard_rate) does.
    /// Its discount curve is Act/365(Fixed), the only one the engine accepts
    /// (`isdacdsengine.rs:452`).
    #[test]
    fn the_conventional_spread_converts_an_upfront_on_the_isda_model() {
        let (settings, today, schedule, discount_curve) =
            conventional_spread_fixture(Actual365Fixed::new());
        let quoted = upfront_quoted(schedule.clone(), &settings);

        let hazard_rate = quoted
            .implied_hazard_rate(
                0.0,
                &discount_curve,
                Actual365Fixed::new(),
                CONVENTIONAL_RECOVERY,
                1.0e-9,
                PricingModel::Isda,
            )
            .unwrap();
        let conventional = quoted
            .conventional_spread(
                CONVENTIONAL_RECOVERY,
                &discount_curve,
                Actual365Fixed::new(),
                PricingModel::Isda,
            )
            .unwrap();

        assert!(
            (conventional - CONVENTIONAL_RUNNING).abs() > 1.0e-4,
            "the upfront left the conventional spread {conventional} at the running \
             {CONVENTIONAL_RUNNING}"
        );

        let mut converted = CreditDefaultSwap::new(
            ProtectionSide::Seller,
            CONVENTIONAL_NOTIONAL,
            conventional,
            schedule,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            true,
            true,
            Shared::clone(&settings),
        )
        .unwrap();
        converted.base_mut().set_pricing_engine(shared_mut(
            IsdaCdsEngine::new(
                flat_credit(today, hazard_rate),
                CONVENTIONAL_RECOVERY,
                discount_curve,
                None,
                Shared::clone(&settings),
            )
            .with_fidelity(
                NumericalFix::Taylor,
                AccrualBias::HalfDayBias,
                ForwardsInCouponPeriod::Piecewise,
            ),
        ) as SharedMut<dyn PricingEngine>);

        let npv = converted.npv().unwrap();
        assert!(
            npv.abs() < 1.0,
            "the contract converted to {conventional} prices at {npv}, not nothing"
        );
    }
}