libitofin 0.52.1

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
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
//! Rate helpers for the yield-curve bootstrap.
//!
//! Port of `ql/termstructures/yield/ratehelpers.{hpp,cpp}` plus the overnight
//! helper of `ql/termstructures/yield/oisratehelper.{hpp,cpp}`. This module holds
//! [`DepositRateHelper`], the short end of the curve, [`SwapRateHelper`], the
//! long end over vanilla swaps, [`OISRateHelper`], the long end over
//! overnight-indexed swaps, [`FuturesRateHelper`], the short-to-mid end over
//! exchange-traded IMM/ASX futures, and [`FraRateHelper`], the mid end over
//! forward-rate agreements. [`super::BMASwapRateHelper`] implements municipal swaps
//! in its own module. The `SwapIndex`-based and explicit-start/end-date `SwapRateHelper`
//! constructors are deferred with the swap-index port. The `OISRateHelper`
//! explicit-start/end-date constructor is deferred likewise.
//!
//! [`FraRateHelper`] defers the from-scratch constructors that build a synthetic `"no-fix"` [`IborIndex`]
//! (`ratehelpers.cpp:263,293`), and the IMM-offset constructors
//! (`ratehelpers.cpp:322`, with the `nthImmDate` helper). None sit on the
//! bootstrap oracle path. Unlike C++, which registers the helper with its cloned
//! index (`registerWith(iborIndex_)`) and so must unregister that index from the
//! forwarding handle to keep relink notifications out of the bootstrap, the Rust
//! helper never observes the cloned index (matching [`DepositRateHelper`]), so
//! the relink-notification loop is already broken and no unregister is needed.
//! [`SwapRateHelper`], [`OISRateHelper`] and [`FraRateHelper`] instead subscribe
//! to the cloned index's fixing history on [`Settings`] directly (D11), which
//! keeps the fixing notifications the C++ index relays without observing the
//! clone's forecasting handle.

use std::cell::Cell;
use std::cell::RefCell;
use std::rc::Weak;

use crate::cashflows::RateAveraging;
use crate::errors::{QlError, QlResult};
use crate::handle::{Handle, RelinkableHandle};
use crate::indexes::OvernightIndex;
use crate::indexes::iborindex::IborIndex;
use crate::indexes::index::Index;
use crate::indexes::interestrateindex::InterestRateIndex;
use crate::instrument::Instrument;
use crate::instruments::{
    FuturesType, MakeOis, MakeVanillaSwap, OvernightIndexedSwap, VanillaSwap,
};
use crate::patterns::observable::{AsObservable, Observable};
use crate::quotes::{Quote, SimpleQuote};
use crate::settings::Settings;
use crate::shared::{Shared, shared};
use crate::termstructures::bootstraphelper::{
    BootstrapHelperBase, RateHelper, RelativeDateRateHelper,
};
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::time::businessdayconvention::BusinessDayConvention;
use crate::time::calendar::Calendar;
use crate::time::date::Date;
use crate::time::dategenerationrule::DateGeneration;
use crate::time::daycounter::DayCounter;
use crate::time::frequency::Frequency;
use crate::time::period::Period;
use crate::time::timeunit::TimeUnit;
use crate::time::{asx, imm};
use crate::types::{Integer, Natural, Real};
use std::panic::{AssertUnwindSafe, catch_unwind};

/// Bootstrap helper over a deposit rate (`DepositRateHelper`).
///
/// A deposit borrows at the quoted rate from spot to spot-plus-tenor;
/// [`implied_quote`](RateHelper::implied_quote) re-derives that rate from the
/// bootstrapping curve's discount factors between the value and maturity dates.
///
/// The load-bearing mechanism is the cloned index: the constructor re-curves
/// the supplied index onto the helper's *own* [`RelinkableHandle`] with
/// [`IborIndex::clone_with`] (`ratehelpers.cpp:206`), so the helper forecasts
/// off the curve it is being bootstrapped against rather than whatever curve
/// the index was handed. [`set_term_structure`](RateHelper::set_term_structure)
/// weak-links that handle to the bootstrapping curve, non-owning and unobserved
/// (the `null_deleter`/`observer = false` of `ratehelpers.cpp:217`).
pub struct DepositRateHelper {
    base: BootstrapHelperBase,
    date_error: RefCell<Option<QlError>>,
    index: IborIndex,
    term_structure_handle: RelinkableHandle<dyn YieldTermStructure>,
    fixing_date: Cell<Date>,
}

impl DepositRateHelper {
    /// A deposit helper fitting `quote`, an explicit market-rate handle, with
    /// its schedule taken from `index` (the C++ `DepositRateHelper(rate, i)`
    /// with `rate` a `Handle<Quote>`, `ratehelpers.cpp:195`).
    pub fn new(quote: Handle<dyn Quote>, index: &IborIndex) -> Shared<DepositRateHelper> {
        Self::build(quote, index)
    }

    /// A deposit helper fitting a fixed `rate`, wrapped in a [`SimpleQuote`]
    /// (the `rate`-as-`Rate` arm of the same C++ variant constructor).
    pub fn from_rate(rate: Real, index: &IborIndex) -> Shared<DepositRateHelper> {
        let quote = Handle::new(shared(SimpleQuote::new(rate)) as Shared<dyn Quote>);
        Self::build(quote, index)
    }

    fn build(quote: Handle<dyn Quote>, source_index: &IborIndex) -> Shared<DepositRateHelper> {
        let settings = source_index.base().settings().clone();
        Shared::new_cyclic(|weak: &Weak<DepositRateHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    helper.initialize_dates();
                }
            });
            let term_structure_handle = RelinkableHandle::<dyn YieldTermStructure>::empty();
            let index = source_index.clone_with(term_structure_handle.handle());
            let base = BootstrapHelperBase::new_relative(quote, settings, true, on_eval_change);
            let helper = DepositRateHelper {
                base,
                date_error: RefCell::new(None),
                index,
                term_structure_handle,
                fixing_date: Cell::new(Date::null()),
            };
            helper.initialize_dates();
            helper
        })
    }
}

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

impl RateHelper for DepositRateHelper {
    fn base(&self) -> &BootstrapHelperBase {
        &self.base
    }

    /// The deposit rate implied by the current curve.
    ///
    /// The forecast flag is forced true (`iborIndex_->fixing(fixingDate_, true)`,
    /// `ratehelpers.cpp:213`): the helper prices off the curve, never off a
    /// stored fixing.
    fn implied_quote(&self) -> QlResult<Real> {
        if let Some(error) = self.date_error.borrow().as_ref() {
            return Err(error.clone());
        }
        self.base.term_structure()?;
        self.index.fixing(self.fixing_date.get(), true)
    }

    /// Weak-links the helper's own pricing handle to the bootstrapping curve,
    /// then records the curve on the base - both non-owning and unobserved
    /// (`ratehelpers.cpp:216`).
    fn set_term_structure(&self, term_structure: &Shared<dyn YieldTermStructure>) {
        self.term_structure_handle
            .link_to_weak(Shared::downgrade(term_structure));
        self.base.set_term_structure(term_structure);
    }
}

impl RelativeDateRateHelper for DepositRateHelper {
    /// Rebuilds the schedule off the current evaluation date
    /// (`initializeDates`, v1.44 `ratehelpers.cpp:228-237`): the earliest date
    /// is the index fixing days advanced on the fixing calendar from the
    /// unadjusted evaluation date (a Saturday plus two days is a Tuesday), the
    /// fixing date that date rolled back, and the maturity the earliest date
    /// advanced by the tenor. Pillar, latest and latest-relevant dates all
    /// equal the maturity.
    ///
    /// The earliest date no longer goes through the index value date, so for
    /// Libor-family indexes the joint-calendar adjust of `Libor::valueDate`
    /// (`libor.cpp:86-99`) no longer applies: the result changes on business
    /// days too when the spot lands on a value-calendar holiday.
    ///
    /// An unset evaluation date is stored as the error and returned by the
    /// next [`implied_quote`](RateHelper::implied_quote) (D10).
    fn initialize_dates(&self) {
        *self.date_error.borrow_mut() = self.try_initialize_dates().err();
    }
}

impl DepositRateHelper {
    fn try_initialize_dates(&self) -> QlResult<()> {
        let evaluation_date = self
            .base
            .evaluation_date()
            .ok_or_else(|| QlError::new("evaluation date is not set", file!(), line!()))?;
        let earliest = self.index.fixing_calendar().advance(
            evaluation_date,
            self.index.fixing_days() as Integer,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );
        self.fixing_date.set(self.index.fixing_date(earliest));
        let maturity = self.index.maturity_date(earliest)?;

        self.base.set_earliest_date(earliest);
        self.base.set_maturity_date(maturity);
        self.base.set_pillar_date(maturity);
        self.base.set_latest_date(maturity);
        self.base.set_latest_relevant_date(maturity);
        Ok(())
    }
}

/// Validates that `date` is a legal settlement date for the futures convention
/// (`CheckDate`, `ratehelpers.cpp:46`): IMM and ASX require a valid cycle date,
/// while [`FuturesType::Custom`] imposes no constraint.
fn check_futures_date(date: Date, futures_type: FuturesType) -> QlResult<()> {
    match futures_type {
        FuturesType::Imm => {
            crate::require!(
                imm::is_imm_date(date, false),
                "{date} is not a valid IMM date"
            )
        }
        FuturesType::Asx => {
            crate::require!(
                asx::is_asx_date(date, false),
                "{date} is not a valid ASX date"
            )
        }
        FuturesType::Custom => {}
    }
    Ok(())
}

/// Resolves the maturity of an explicit-date futures helper (the C++
/// `determineMaturityDate` lambda, `ratehelpers.cpp:100`): with no end date,
/// advance three futures periods off `next_date`; with one, take it after
/// checking it is past the start.
fn determine_maturity(
    start: Date,
    end: Option<Date>,
    next_date: impl Fn(Date) -> Date,
) -> QlResult<Date> {
    match end {
        None => Ok(next_date(next_date(next_date(start)))),
        Some(end) => {
            crate::require!(
                end > start,
                "end date ({end}) must be greater than start date ({start})"
            );
            Ok(end)
        }
    }
}

/// Bootstrap helper over an exchange-traded interest-rate future
/// (`FuturesRateHelper`).
///
/// The helper fits the quoted futures price `P` (e.g. `96.0` for a 4% implied
/// rate) at a fixed IMM/ASX window. Unlike the deposit, swap and OIS helpers it
/// derives from the **plain** [`RateHelper`], not [`RelativeDateRateHelper`]:
/// the earliest and maturity dates are absolute, computed once at construction
/// from the supplied dates, and never rebuilt on an evaluation-date change
/// (there is no `initialize_dates`). It therefore holds the bootstrapping curve
/// directly through [`base`](RateHelper::base) rather than forecasting off a
/// cloned index on its own relinkable handle.
///
/// [`implied_quote`](RateHelper::implied_quote) re-derives the price from the
/// curve (`ratehelpers.cpp:157`): the simple forward over the window is
/// `(discount(earliest)/discount(maturity) - 1)/year_fraction`, and the price is
/// `100 * (1 - (forward + convexity_adjustment))`. The convexity adjustment is a
/// plain [`Handle<Quote>`](Handle) value, whatever quote the caller supplies -
/// a [`FuturesConvAdjustmentQuote`](crate::quotes::FuturesConvAdjustmentQuote)
/// prices one off a Hull-White model; it may be negative, as futures margining
/// can push the futures rate either side of the forward.
pub struct FuturesRateHelper {
    base: BootstrapHelperBase,
    year_fraction: Real,
    conv_adj: Handle<dyn Quote>,
}

impl FuturesRateHelper {
    /// A futures helper over a length-in-months window off `ibor_start_date`
    /// (`ratehelpers.cpp:70`): the maturity is the start advanced
    /// `length_in_months` months on `calendar` under `convention`/`end_of_month`.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        price: Handle<dyn Quote>,
        ibor_start_date: Date,
        length_in_months: Natural,
        calendar: Calendar,
        convention: BusinessDayConvention,
        end_of_month: bool,
        day_counter: DayCounter,
        conv_adj: Handle<dyn Quote>,
        futures_type: FuturesType,
    ) -> QlResult<Shared<FuturesRateHelper>> {
        check_futures_date(ibor_start_date, futures_type)?;
        let earliest = ibor_start_date;
        let maturity = calendar.advance(
            ibor_start_date,
            length_in_months as Integer,
            TimeUnit::Months,
            convention,
            end_of_month,
        );
        let year_fraction = day_counter.year_fraction_ref(earliest, maturity, earliest, maturity);
        Ok(Self::assemble(
            price,
            conv_adj,
            earliest,
            maturity,
            year_fraction,
        ))
    }

    /// A futures helper over an explicit window (`ratehelpers.cpp:91`). With
    /// `ibor_end_date` `None` the maturity is three [`imm`]/[`asx`] periods past
    /// the start; with `Some`, that date (which must be past the start for the
    /// IMM/ASX conventions). [`FuturesType::Custom`] requires an explicit end
    /// date - the C++ null-maturity path is an error here.
    pub fn from_end_date(
        price: Handle<dyn Quote>,
        ibor_start_date: Date,
        ibor_end_date: Option<Date>,
        day_counter: DayCounter,
        conv_adj: Handle<dyn Quote>,
        futures_type: FuturesType,
    ) -> QlResult<Shared<FuturesRateHelper>> {
        check_futures_date(ibor_start_date, futures_type)?;
        let maturity = match futures_type {
            FuturesType::Imm => {
                determine_maturity(ibor_start_date, ibor_end_date, |d| imm::next_date(d, false))?
            }
            FuturesType::Asx => {
                determine_maturity(ibor_start_date, ibor_end_date, |d| asx::next_date(d, false))?
            }
            FuturesType::Custom => match ibor_end_date {
                Some(end) => end,
                None => crate::fail!("a Custom futures helper requires an explicit end date"),
            },
        };
        let earliest = ibor_start_date;
        let year_fraction = day_counter.year_fraction_ref(earliest, maturity, earliest, maturity);
        Ok(Self::assemble(
            price,
            conv_adj,
            earliest,
            maturity,
            year_fraction,
        ))
    }

    /// A futures helper whose window follows `index`'s conventions
    /// (`ratehelpers.cpp:139`): the maturity is the start advanced by the index
    /// tenor on the index's fixing calendar under its business-day convention (no
    /// end-of-month), and the year fraction uses the index day counter.
    pub fn from_index(
        price: Handle<dyn Quote>,
        ibor_start_date: Date,
        index: &IborIndex,
        conv_adj: Handle<dyn Quote>,
        futures_type: FuturesType,
    ) -> QlResult<Shared<FuturesRateHelper>> {
        check_futures_date(ibor_start_date, futures_type)?;
        let earliest = ibor_start_date;
        let maturity = index.fixing_calendar().advance_by_period(
            ibor_start_date,
            index.tenor(),
            index.business_day_convention(),
            false,
        );
        let year_fraction = index
            .day_counter()
            .year_fraction_ref(earliest, maturity, earliest, maturity);
        Ok(Self::assemble(
            price,
            conv_adj,
            earliest,
            maturity,
            year_fraction,
        ))
    }

    /// Builds the plain-date base shared by the three constructors: observes the
    /// price (via the base) and the convexity quote (the C++
    /// `registerWith(convAdj_)`), then pins every schedule date to the fixed
    /// window - `pillar = latest = latest_relevant = maturity`.
    fn assemble(
        price: Handle<dyn Quote>,
        conv_adj: Handle<dyn Quote>,
        earliest: Date,
        maturity: Date,
        year_fraction: Real,
    ) -> Shared<FuturesRateHelper> {
        let base = BootstrapHelperBase::new(price);
        conv_adj.register_observer(&base.observer());
        base.set_earliest_date(earliest);
        base.set_maturity_date(maturity);
        base.set_pillar_date(maturity);
        base.set_latest_date(maturity);
        base.set_latest_relevant_date(maturity);
        shared(FuturesRateHelper {
            base,
            year_fraction,
            conv_adj,
        })
    }

    /// The convexity adjustment applied to the forward (`ratehelpers.cpp:168`):
    /// the convexity quote's value, or zero when no quote was supplied.
    pub fn convexity_adjustment(&self) -> QlResult<Real> {
        if self.conv_adj.is_empty() {
            Ok(0.0)
        } else {
            self.conv_adj.current_link()?.value()
        }
    }
}

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

impl RateHelper for FuturesRateHelper {
    fn base(&self) -> &BootstrapHelperBase {
        &self.base
    }

    /// The futures price implied by the current curve (`ratehelpers.cpp:157`).
    ///
    /// The simple forward over the fixed window comes straight off the curve's
    /// discount factors; the price adds the convexity adjustment to that forward
    /// and quotes `100 * (1 - future_rate)`.
    fn implied_quote(&self) -> QlResult<Real> {
        let term_structure = self.base.term_structure()?;
        let forward = (term_structure.discount_date(self.base.earliest_date(), false)?
            / term_structure.discount_date(self.base.maturity_date(), false)?
            - 1.0)
            / self.year_fraction;
        let future_rate = forward + self.convexity_adjustment()?;
        Ok(100.0 * (1.0 - future_rate))
    }
}

/// Selects the date at which a helper places its curve node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pillar {
    /// The instrument's maturity date.
    MaturityDate,
    /// The latest date the instrument needs data at.
    LastRelevantDate,
    /// A fixed date within the helper's earliest and latest relevant dates.
    CustomDate(Date),
}

impl Pillar {
    pub(crate) fn resolve(self, earliest: Date, maturity: Date, latest: Date) -> QlResult<Date> {
        match self {
            Self::MaturityDate => Ok(maturity),
            Self::LastRelevantDate => Ok(latest),
            Self::CustomDate(date) => {
                crate::require!(date != Date::null(), "custom pillar date must be provided");
                crate::require!(
                    date >= earliest,
                    "pillar date must be later than or equal to the instrument's earliest date"
                );
                crate::require!(
                    date <= latest,
                    "pillar date must be before or equal to the instrument's latest relevant date"
                );
                Ok(date)
            }
        }
    }
}

fn rebuild_dates<T>(rebuild: impl FnOnce() -> QlResult<T>) -> QlResult<T> {
    catch_unwind(AssertUnwindSafe(rebuild)).unwrap_or_else(|_| {
        Err(QlError::new(
            "helper dates exceed supported range",
            file!(),
            line!(),
        ))
    })
}

/// Bootstrap helper over a forward-rate-agreement rate (`FraRateHelper`).
///
/// The helper fits the rate of a FRA that starts `period_to_start` after spot
/// and spans the index tenor. Like [`DepositRateHelper`] it clones the supplied
/// index onto its own [`RelinkableHandle`] with [`IborIndex::clone_with`]
/// (`ratehelpers.cpp:315`) so it forecasts off the curve being bootstrapped, and
/// [`set_term_structure`](RateHelper::set_term_structure) weak-links that handle
/// to the bootstrapping curve, non-owning and unobserved.
///
/// It runs in one of two modes (`use_indexed_coupon`, C++ default `true`):
/// **indexed**, where [`implied_quote`](RateHelper::implied_quote) is the index
/// fixing forecast off the curve (`ibor_index.fixing(fixing_date, true)`), the
/// node pinned at `index.maturity_date(earliest)`; and **par**, where the quote
/// is the simple forward `(discount(earliest)/discount(maturity) - 1)/tau` over
/// the raw schedule window with `tau` the index day-count fraction, the node
/// pinned at the maturity (`ratehelpers.cpp:361`).
pub struct FraRateHelper {
    base: BootstrapHelperBase,
    date_error: RefCell<Option<QlError>>,
    index: IborIndex,
    term_structure_handle: RelinkableHandle<dyn YieldTermStructure>,
    period_to_start: Option<Period>,
    use_indexed_coupon: bool,
    pillar: Pillar,
    fixing_date: Cell<Date>,
    spanning_time: Cell<Real>,
}

impl FraRateHelper {
    /// Builds the helper and returns schedule or custom-pillar errors.
    #[allow(clippy::too_many_arguments)]
    pub fn try_new(
        quote: Handle<dyn Quote>,
        period_to_start: Period,
        index: &IborIndex,
        use_indexed_coupon: bool,
        pillar: Pillar,
    ) -> QlResult<Shared<FraRateHelper>> {
        let helper = Self::new(quote, period_to_start, index, use_indexed_coupon, pillar);
        helper.validate_dates()?;
        Ok(helper)
    }

    /// Builds the helper and returns schedule or custom-pillar errors.
    #[allow(clippy::too_many_arguments)]
    pub fn try_from_rate(
        rate: Real,
        period_to_start: Period,
        index: &IborIndex,
        use_indexed_coupon: bool,
        pillar: Pillar,
    ) -> QlResult<Shared<FraRateHelper>> {
        let helper = Self::from_rate(rate, period_to_start, index, use_indexed_coupon, pillar);
        helper.validate_dates()?;
        Ok(helper)
    }

    /// Builds the helper and returns schedule or custom-pillar errors.
    #[allow(clippy::too_many_arguments)]
    pub fn try_from_months(
        quote: Handle<dyn Quote>,
        months_to_start: Natural,
        index: &IborIndex,
        use_indexed_coupon: bool,
        pillar: Pillar,
    ) -> QlResult<Shared<FraRateHelper>> {
        crate::require!(
            months_to_start <= i32::MAX as u32,
            "months to start exceed supported range"
        );
        let helper = Self::from_months(quote, months_to_start, index, use_indexed_coupon, pillar);
        helper.validate_dates()?;
        Ok(helper)
    }

    /// Builds the helper and returns schedule or custom-pillar errors.
    #[allow(clippy::too_many_arguments)]
    pub fn try_from_dates(
        quote: Handle<dyn Quote>,
        start_date: Date,
        end_date: Date,
        index: &IborIndex,
        use_indexed_coupon: bool,
        pillar: Pillar,
    ) -> QlResult<Shared<FraRateHelper>> {
        let helper = Self::from_dates(
            quote,
            start_date,
            end_date,
            index,
            use_indexed_coupon,
            pillar,
        );
        helper.validate_dates()?;
        Ok(helper)
    }

    /// Returns the last schedule error, if a date change invalidated the helper.
    pub fn validate_dates(&self) -> QlResult<()> {
        match self.date_error.borrow().as_ref() {
            Some(error) => Err(error.clone()),
            None => Ok(()),
        }
    }

    /// A FRA helper fitting `quote` over the window starting `period_to_start`
    /// after spot and spanning `index`'s tenor (the index-based `Period`
    /// constructor, `ratehelpers.cpp:305`).
    pub fn new(
        quote: Handle<dyn Quote>,
        period_to_start: Period,
        index: &IborIndex,
        use_indexed_coupon: bool,
        pillar: Pillar,
    ) -> Shared<FraRateHelper> {
        Self::build(
            quote,
            Some(period_to_start),
            index,
            use_indexed_coupon,
            pillar,
            None,
        )
    }

    /// A FRA helper fitting a fixed `rate`, wrapped in a [`SimpleQuote`] (the
    /// `Rate` arm of the C++ `variant<Rate, Handle<Quote>>` constructor).
    pub fn from_rate(
        rate: Real,
        period_to_start: Period,
        index: &IborIndex,
        use_indexed_coupon: bool,
        pillar: Pillar,
    ) -> Shared<FraRateHelper> {
        let quote = Handle::new(shared(SimpleQuote::new(rate)) as Shared<dyn Quote>);
        Self::new(quote, period_to_start, index, use_indexed_coupon, pillar)
    }

    /// A FRA helper whose start is `months_to_start` months after spot (the
    /// index-based `Natural monthsToStart` constructor, `ratehelpers.cpp:271`,
    /// which delegates to the `Period` form via `months_to_start * Months`).
    pub fn from_months(
        quote: Handle<dyn Quote>,
        months_to_start: Natural,
        index: &IborIndex,
        use_indexed_coupon: bool,
        pillar: Pillar,
    ) -> Shared<FraRateHelper> {
        Self::new(
            quote,
            Period::new(months_to_start as Integer, TimeUnit::Months),
            index,
            use_indexed_coupon,
            pillar,
        )
    }

    /// A FRA helper over an explicit `[start_date, end_date]` window (the
    /// non-relative date constructor, `ratehelpers.cpp:341`). Its schedule is
    /// fixed at construction and, mirroring the C++ `RelativeDateRateHelper(rate,
    /// false)`, does not shift when the evaluation date moves.
    pub fn from_dates(
        quote: Handle<dyn Quote>,
        start_date: Date,
        end_date: Date,
        index: &IborIndex,
        use_indexed_coupon: bool,
        pillar: Pillar,
    ) -> Shared<FraRateHelper> {
        Self::build(
            quote,
            None,
            index,
            use_indexed_coupon,
            pillar,
            Some((start_date, end_date)),
        )
    }

    fn build(
        quote: Handle<dyn Quote>,
        period_to_start: Option<Period>,
        source_index: &IborIndex,
        use_indexed_coupon: bool,
        pillar: Pillar,
        explicit_dates: Option<(Date, Date)>,
    ) -> Shared<FraRateHelper> {
        let settings = source_index.base().settings().clone();
        let update_dates = explicit_dates.is_none();
        Shared::new_cyclic(|weak: &Weak<FraRateHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    helper.initialize_dates();
                }
            });
            let term_structure_handle = RelinkableHandle::<dyn YieldTermStructure>::empty();
            let index = source_index.clone_with(term_structure_handle.handle());
            let base =
                BootstrapHelperBase::new_relative(quote, settings, update_dates, on_eval_change);
            index
                .settings()
                .register_fixing_observer(&index.name(), &base.observer());
            let helper = FraRateHelper {
                base,
                date_error: RefCell::new(None),
                index,
                term_structure_handle,
                period_to_start,
                use_indexed_coupon,
                pillar,
                fixing_date: Cell::new(Date::null()),
                spanning_time: Cell::new(0.0),
            };
            if let Some((start, end)) = explicit_dates {
                helper.base.set_earliest_date(start);
                helper.base.set_maturity_date(end);
            }
            helper.initialize_dates();
            helper
        })
    }
}

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

impl RateHelper for FraRateHelper {
    fn base(&self) -> &BootstrapHelperBase {
        &self.base
    }

    /// The FRA rate implied by the current curve (`ratehelpers.cpp:361`).
    ///
    /// In indexed mode this is the index fixing forecast off the curve, forced
    /// on (`ibor_index.fixing(fixing_date, true)`); in par mode it is the simple
    /// forward `(discount(earliest)/discount(maturity) - 1)/spanning_time` read
    /// straight from the curve's discount factors.
    fn implied_quote(&self) -> QlResult<Real> {
        self.validate_dates()?;
        let term_structure = self.base.term_structure()?;
        if self.use_indexed_coupon {
            self.index.fixing(self.fixing_date.get(), true)
        } else {
            let discount_earliest =
                term_structure.discount_date(self.base.earliest_date(), false)?;
            let discount_maturity =
                term_structure.discount_date(self.base.maturity_date(), false)?;
            Ok((discount_earliest / discount_maturity - 1.0) / self.spanning_time.get())
        }
    }

    /// Weak-links the helper's own pricing handle to the bootstrapping curve,
    /// then records the curve on the base - both non-owning and unobserved
    /// (`ratehelpers.cpp:372`, `observer = false`).
    fn set_term_structure(&self, term_structure: &Shared<dyn YieldTermStructure>) {
        self.term_structure_handle
            .link_to_weak(Shared::downgrade(term_structure));
        self.base.set_term_structure(term_structure);
    }
}

impl RelativeDateRateHelper for FraRateHelper {
    /// Rebuilds the schedule off the current evaluation date (`initializeDates`,
    /// v1.44 `ratehelpers.cpp:392-397`).
    ///
    /// When the helper tracks the evaluation date (the relative constructors),
    /// spot is the index fixing days advanced on the fixing calendar from the
    /// unadjusted evaluation date (not the index value date, so no Libor
    /// joint-calendar adjust), the earliest date is `period_to_start` past spot
    /// and the maturity is the
    /// combined `period_to_start + tenor` past spot - both advanced from spot,
    /// not chained, so a business-day roll on the intermediate date cannot leak
    /// into the maturity. The explicit-date constructor sets those two dates at
    /// construction and skips this block. Either way the latest-relevant date,
    /// pillar, latest date and fixing date follow: indexed mode pins the node at
    /// `index.maturity_date(earliest)`, par mode at the maturity and caches the
    /// spanning year fraction.
    fn initialize_dates(&self) {
        *self.date_error.borrow_mut() = self.try_initialize_dates().err();
    }
}

impl FraRateHelper {
    fn try_initialize_dates(&self) -> QlResult<()> {
        let (earliest, maturity, latest_relevant, pillar, fixing_date, spanning_time) =
            rebuild_dates(|| {
                let (earliest, maturity) = if self.base.update_dates() {
                    let evaluation_date = self.base.evaluation_date().ok_or_else(|| {
                        QlError::new("evaluation date is not set", file!(), line!())
                    })?;
                    let calendar = self.index.fixing_calendar();
                    let spot = calendar.advance(
                        evaluation_date,
                        self.index.fixing_days() as Integer,
                        TimeUnit::Days,
                        BusinessDayConvention::Following,
                        false,
                    );
                    let period_to_start = self
                        .period_to_start
                        .expect("a relative-date FRA helper carries a period to start");
                    let convention = self.index.business_day_convention();
                    let end_of_month = self.index.end_of_month();
                    let earliest =
                        calendar.advance_by_period(spot, period_to_start, convention, end_of_month);
                    let maturity = calendar.advance_by_period(
                        spot,
                        period_to_start + self.index.tenor(),
                        convention,
                        end_of_month,
                    );
                    (earliest, maturity)
                } else {
                    (self.base.earliest_date(), self.base.maturity_date())
                };
                let spanning_time = self.index.day_counter().year_fraction(earliest, maturity);
                let latest_relevant = if self.use_indexed_coupon {
                    self.index.maturity_date(earliest)?
                } else {
                    maturity
                };
                let pillar = self.pillar.resolve(earliest, maturity, latest_relevant)?;
                let fixing_date = self.index.fixing_date(earliest);
                Ok((
                    earliest,
                    maturity,
                    latest_relevant,
                    pillar,
                    fixing_date,
                    spanning_time,
                ))
            })?;
        self.base.set_earliest_date(earliest);
        self.base.set_maturity_date(maturity);
        self.base.set_latest_relevant_date(latest_relevant);

        self.base.set_pillar_date(pillar);
        self.base.set_latest_date(pillar);
        self.fixing_date.set(fixing_date);
        self.spanning_time.set(spanning_time);
        Ok(())
    }
}

/// Bootstrap helper over a par swap rate (`SwapRateHelper`).
///
/// The helper fits the fixed rate at which a spot-starting vanilla swap of the
/// quoted tenor is worth par on the bootstrapping curve. Its own swap is built
/// through [`MakeVanillaSwap`] (`ratehelpers.cpp:557`) off a cloned index and a
/// relinkable discounting handle, so the helper prices against the curve it is
/// being bootstrapped against.
///
/// [`implied_quote`](RateHelper::implied_quote) is **not** the swap's fair rate:
/// it is the par-rate reconstruction of `ratehelpers.cpp:633-646`, over the
/// floating- and fixed-leg NPV and BPS, carrying the spread term that a bare
/// `fair_rate()` would drop. Because the helper deliberately does not observe
/// the curve (its pricing handles are weak-linked, unobserved), the swap's
/// cached results go stale when the bootstrap moves the curve; the C++
/// `swap_->deepUpdate()` forces a fresh calculation each call, and this port
/// reproduces that with [`Instrument::recalculate`] before reading the legs.
///
/// The indexed-vs-at-par coupon mode is not read from a global singleton: the
/// helper carries the C++ `useIndexedCoupons_` `optional<bool>` (default `None`)
/// and forwards it to [`MakeVanillaSwap::with_indexed_coupons`], which resolves
/// `None` against [`Settings::using_at_par_coupons`] (D5, #315/#342).
pub struct SwapRateHelper {
    base: BootstrapHelperBase,
    date_error: RefCell<Option<QlError>>,
    swap: RefCell<Option<VanillaSwap>>,
    ibor_index: Shared<IborIndex>,
    term_structure_handle: RelinkableHandle<dyn YieldTermStructure>,
    discount_relinkable_handle: RelinkableHandle<dyn YieldTermStructure>,
    discount_handle: Option<Handle<dyn YieldTermStructure>>,
    spread: Handle<dyn Quote>,
    settings: Shared<Settings<Date>>,
    tenor: Period,
    forward_start: Period,
    calendar: Calendar,
    fixed_frequency: Frequency,
    fixed_convention: BusinessDayConvention,
    fixed_day_count: DayCounter,
    end_of_month: bool,
    use_indexed_coupons: Option<bool>,
    pillar: Pillar,
}

impl SwapRateHelper {
    /// Builds the helper and returns schedule or custom-pillar errors.
    #[allow(clippy::too_many_arguments)]
    pub fn try_with_details(
        quote: Handle<dyn Quote>,
        tenor: Period,
        calendar: Calendar,
        fixed_frequency: Frequency,
        fixed_convention: BusinessDayConvention,
        fixed_day_count: DayCounter,
        ibor_index: &IborIndex,
        spread: Handle<dyn Quote>,
        forward_start: Period,
        discounting_curve: Option<Handle<dyn YieldTermStructure>>,
        pillar: Pillar,
    ) -> QlResult<Shared<SwapRateHelper>> {
        let helper = Self::with_details(
            quote,
            tenor,
            calendar,
            fixed_frequency,
            fixed_convention,
            fixed_day_count,
            ibor_index,
            spread,
            forward_start,
            discounting_curve,
            pillar,
        );
        helper.validate_dates()?;
        Ok(helper)
    }

    /// Returns the last schedule error, if a date change invalidated the helper.
    pub fn validate_dates(&self) -> QlResult<()> {
        match self.date_error.borrow().as_ref() {
            Some(error) => Err(error.clone()),
            None => Ok(()),
        }
    }

    /// A swap helper fitting `quote` with the schedule of a spot-starting swap
    /// of `tenor`, the form the curve-consistency oracle builds
    /// (`piecewiseyieldcurve.cpp:293`): no spread, no forward start, no exogenous
    /// discounting curve, and the default [`Pillar::LastRelevantDate`].
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        quote: Handle<dyn Quote>,
        tenor: Period,
        calendar: Calendar,
        fixed_frequency: Frequency,
        fixed_convention: BusinessDayConvention,
        fixed_day_count: DayCounter,
        ibor_index: &IborIndex,
    ) -> Shared<SwapRateHelper> {
        Self::build(
            quote,
            tenor,
            calendar,
            fixed_frequency,
            fixed_convention,
            fixed_day_count,
            ibor_index,
            Handle::empty(),
            Period::new(0, TimeUnit::Days),
            None,
            Pillar::LastRelevantDate,
        )
    }

    /// A swap helper fitting a fixed `rate`, wrapped in a [`SimpleQuote`].
    #[allow(clippy::too_many_arguments)]
    pub fn from_rate(
        rate: Real,
        tenor: Period,
        calendar: Calendar,
        fixed_frequency: Frequency,
        fixed_convention: BusinessDayConvention,
        fixed_day_count: DayCounter,
        ibor_index: &IborIndex,
    ) -> Shared<SwapRateHelper> {
        let quote = Handle::new(shared(SimpleQuote::new(rate)) as Shared<dyn Quote>);
        Self::new(
            quote,
            tenor,
            calendar,
            fixed_frequency,
            fixed_convention,
            fixed_day_count,
            ibor_index,
        )
    }

    /// The full constructor of the ported (tenor-based) form: a market `spread`
    /// handle (empty for none), a `forward_start`, an optional exogenous
    /// `discounting_curve`, and the [`Pillar`] choice.
    #[allow(clippy::too_many_arguments)]
    pub fn with_details(
        quote: Handle<dyn Quote>,
        tenor: Period,
        calendar: Calendar,
        fixed_frequency: Frequency,
        fixed_convention: BusinessDayConvention,
        fixed_day_count: DayCounter,
        ibor_index: &IborIndex,
        spread: Handle<dyn Quote>,
        forward_start: Period,
        discounting_curve: Option<Handle<dyn YieldTermStructure>>,
        pillar: Pillar,
    ) -> Shared<SwapRateHelper> {
        Self::build(
            quote,
            tenor,
            calendar,
            fixed_frequency,
            fixed_convention,
            fixed_day_count,
            ibor_index,
            spread,
            forward_start,
            discounting_curve,
            pillar,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn build(
        quote: Handle<dyn Quote>,
        tenor: Period,
        calendar: Calendar,
        fixed_frequency: Frequency,
        fixed_convention: BusinessDayConvention,
        fixed_day_count: DayCounter,
        source_index: &IborIndex,
        spread: Handle<dyn Quote>,
        forward_start: Period,
        discounting_curve: Option<Handle<dyn YieldTermStructure>>,
        pillar: Pillar,
    ) -> Shared<SwapRateHelper> {
        let settings = source_index.base().settings().clone();
        Shared::new_cyclic(|weak: &Weak<SwapRateHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    helper.initialize_dates();
                }
            });
            let term_structure_handle = RelinkableHandle::<dyn YieldTermStructure>::empty();
            let ibor_index = shared(source_index.clone_with(term_structure_handle.handle()));
            let base = BootstrapHelperBase::new_relative(
                quote,
                Shared::clone(&settings),
                true,
                on_eval_change,
            );
            if let Some(discount) = &discounting_curve {
                discount.register_observer(&base.observer());
            }
            spread.register_observer(&base.observer());
            settings.register_fixing_observer(&ibor_index.name(), &base.observer());
            let helper = SwapRateHelper {
                base,
                date_error: RefCell::new(None),
                swap: RefCell::new(None),
                ibor_index,
                term_structure_handle,
                discount_relinkable_handle: RelinkableHandle::<dyn YieldTermStructure>::empty(),
                discount_handle: discounting_curve,
                spread,
                settings,
                tenor,
                forward_start,
                calendar,
                fixed_frequency,
                fixed_convention,
                fixed_day_count,
                end_of_month: false,
                use_indexed_coupons: None,
                pillar,
            };
            helper.initialize_dates();
            helper
        })
    }
}

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

impl RateHelper for SwapRateHelper {
    fn base(&self) -> &BootstrapHelperBase {
        &self.base
    }

    /// The par swap rate implied by the current curve
    /// (`ratehelpers.cpp:633-646`).
    ///
    /// The curve is brought up to date before the swap is borrowed, so a stale
    /// curve re-bootstraps without re-entering this helper's borrowed swap; the
    /// rate is then priced on the converged curve, as C++ does through
    /// `LazyObject::calculate` (`lazyobject.hpp:257-258`).
    ///
    /// The swap is force-recalculated first (the C++ `swap_->deepUpdate()`,
    /// forced because the helper does not observe the curve); then the rate is
    /// reconstructed from the floating-leg NPV, the spread carried on the
    /// floating-leg BPS, and the fixed-leg BPS, rather than read from
    /// `fair_rate()`.
    fn implied_quote(&self) -> QlResult<Real> {
        self.validate_dates()?;
        let curve = self.base.term_structure()?;
        curve.discount(0.0, true)?;
        let mut guard = self.swap.borrow_mut();
        let swap = guard
            .as_mut()
            .expect("initialize_dates populates the swap at construction");
        swap.recalculate()?;

        const BASIS_POINT: Real = 1.0e-4;
        let floating_leg_npv = swap.fixed_vs_floating_mut().floating_leg_npv()?;
        let spread = if self.spread.is_empty() {
            0.0
        } else {
            self.spread.current_link()?.value()?
        };
        let spread_npv = swap.fixed_vs_floating_mut().floating_leg_bps()? / BASIS_POINT * spread;
        let total_npv = -(floating_leg_npv + spread_npv);
        let fixed_leg_bps = swap.fixed_vs_floating_mut().fixed_leg_bps()?;
        Ok(total_npv / (fixed_leg_bps / BASIS_POINT))
    }

    /// Weak-links both the forecasting handle (used by the cloned index) and the
    /// discounting handle to the bootstrapping curve - or, when an exogenous
    /// discounting curve was supplied, links the discounting handle to that
    /// instead - then records the curve on the base (`ratehelpers.cpp:614`). All
    /// links are non-owning and unobserved.
    fn set_term_structure(&self, term_structure: &Shared<dyn YieldTermStructure>) {
        self.term_structure_handle
            .link_to_weak(Shared::downgrade(term_structure));
        match &self.discount_handle {
            Some(discount) if !discount.is_empty() => {
                let curve = discount
                    .current_link()
                    .expect("a non-empty discount handle resolves");
                self.discount_relinkable_handle
                    .link_to_weak(Shared::downgrade(&curve));
            }
            _ => self
                .discount_relinkable_handle
                .link_to_weak(Shared::downgrade(term_structure)),
        }
        self.base.set_term_structure(term_structure);
    }
}

impl RelativeDateRateHelper for SwapRateHelper {
    /// Rebuilds the swap and its schedule off the current evaluation date
    /// (`initializeDates`, `ratehelpers.cpp:530`): a spot-starting swap of the
    /// helper's tenor, built through [`MakeVanillaSwap`] with a 0% fixed rate so
    /// it does not price at construction. Earliest and maturity come from the
    /// leg schedules; the pillar follows the [`Pillar`] choice.
    ///
    /// The latest relevant date includes the final floating coupon fixing end.
    fn initialize_dates(&self) {
        *self.date_error.borrow_mut() = self.try_initialize_dates().err();
    }
}

impl SwapRateHelper {
    fn try_initialize_dates(&self) -> QlResult<()> {
        let (swap, earliest, maturity, latest_relevant, pillar) = rebuild_dates(|| {
            let fixed_tenor = if self.fixed_frequency == Frequency::Once {
                self.tenor
            } else {
                Period::try_from(self.fixed_frequency)
                    .expect("a swap's fixed frequency maps to a valid period")
            };
            let swap = MakeVanillaSwap::new(
                self.tenor,
                Shared::clone(&self.ibor_index),
                Some(0.0),
                self.forward_start,
                Shared::clone(&self.settings),
            )
            .with_discounting_term_structure(self.discount_relinkable_handle.handle())
            .with_fixed_leg_day_count(self.fixed_day_count.clone())
            .with_fixed_leg_tenor(fixed_tenor)
            .with_fixed_leg_convention(self.fixed_convention)
            .with_fixed_leg_termination_date_convention(self.fixed_convention)
            .with_fixed_leg_calendar(self.calendar.clone())
            .with_fixed_leg_end_of_month(self.end_of_month)
            .with_floating_leg_calendar(self.calendar.clone())
            .with_floating_leg_end_of_month(self.end_of_month)
            .with_indexed_coupons(self.use_indexed_coupons)
            .build()?;

            let base = swap.fixed_vs_floating();
            let earliest = base
                .fixed_schedule()
                .start_date()
                .min(base.floating_schedule().start_date());
            let maturity = base
                .fixed_schedule()
                .end_date()
                .max(base.floating_schedule().end_date());

            let latest_relevant = maturity.max(swap.last_fixing_end_date()?);
            let pillar = self.pillar.resolve(earliest, maturity, latest_relevant)?;
            Ok((swap, earliest, maturity, latest_relevant, pillar))
        })?;
        self.base.set_earliest_date(earliest);
        self.base.set_maturity_date(maturity);
        self.base.set_latest_relevant_date(latest_relevant);

        self.base.set_pillar_date(pillar);
        self.base.set_latest_date(pillar);

        *self.swap.borrow_mut() = Some(swap);
        Ok(())
    }
}

/// Bootstrap helper over an overnight-indexed-swap (OIS) rate (`OISRateHelper`).
///
/// The helper fits the fixed rate at which an OIS of the quoted tenor is worth
/// par on the bootstrapping curve. Its own swap is built through [`MakeOis`]
/// (`oisratehelper.cpp:130`) off a cloned overnight index and a relinkable
/// discounting handle, so it prices against the curve it is being bootstrapped
/// against.
///
/// [`implied_quote`](RateHelper::implied_quote) is the par-rate reconstruction
/// of `oisratehelper.cpp:220-232` (the same shape as [`SwapRateHelper`]'s, not
/// `fair_rate()`): over the overnight-leg NPV and BPS and the fixed-leg BPS,
/// carrying the spread term. Because the helper deliberately does not observe
/// the curve (its pricing handles are weak-linked, unobserved), the swap's
/// cached results go stale when the bootstrap moves the curve; the C++
/// `swap_->deepUpdate()` forces a fresh calculation each call, reproduced here
/// with [`Instrument::recalculate`] before reading the legs.
pub struct OISRateHelper {
    base: BootstrapHelperBase,
    date_error: RefCell<Option<QlError>>,
    swap: RefCell<Option<OvernightIndexedSwap>>,
    overnight_index: Shared<OvernightIndex>,
    term_structure_handle: RelinkableHandle<dyn YieldTermStructure>,
    discount_relinkable_handle: RelinkableHandle<dyn YieldTermStructure>,
    discount_handle: Option<Handle<dyn YieldTermStructure>>,
    overnight_spread: Handle<dyn Quote>,
    settings: Shared<Settings<Date>>,
    settlement_days: Natural,
    tenor: Period,
    forward_start: Period,
    payment_lag: Integer,
    payment_convention: BusinessDayConvention,
    payment_frequency: Frequency,
    averaging_method: RateAveraging,
    pillar: Pillar,
}

impl OISRateHelper {
    /// Builds the helper and returns schedule or custom-pillar errors.
    #[allow(clippy::too_many_arguments)]
    pub fn try_new(
        settlement_days: Natural,
        tenor: Period,
        quote: Handle<dyn Quote>,
        overnight_index: &OvernightIndex,
        discounting_curve: Option<Handle<dyn YieldTermStructure>>,
        payment_lag: Integer,
        payment_convention: BusinessDayConvention,
        payment_frequency: Frequency,
        forward_start: Period,
        overnight_spread: Handle<dyn Quote>,
        pillar: Pillar,
        averaging_method: RateAveraging,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Shared<OISRateHelper>> {
        let helper = Self::new(
            settlement_days,
            tenor,
            quote,
            overnight_index,
            discounting_curve,
            payment_lag,
            payment_convention,
            payment_frequency,
            forward_start,
            overnight_spread,
            pillar,
            averaging_method,
            settings,
        );
        helper.validate_dates()?;
        Ok(helper)
    }

    /// Returns the last schedule error, if a date change invalidated the helper.
    pub fn validate_dates(&self) -> QlResult<()> {
        match self.date_error.borrow().as_ref() {
            Some(error) => Err(error.clone()),
            None => Ok(()),
        }
    }

    /// An OIS helper fitting `quote` with the schedule of a swap of `tenor`
    /// starting `settlement_days` after the evaluation date, the form the
    /// bootstrap oracle builds (`overnightindexedswap.cpp:236-256`).
    ///
    /// `discounting_curve` is the exogenous discounting curve (empty `None` to
    /// discount off the bootstrapping curve). `overnight_spread` is the market
    /// spread handle (empty for none). The deferred knobs the C++ constructor
    /// carries past `averaging_method` (telescopic value dates, lookback,
    /// lockout, observation shift, custom pillar, per-leg calendars) take their
    /// benign defaults, mirroring the oracle's positional construction.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        settlement_days: Natural,
        tenor: Period,
        quote: Handle<dyn Quote>,
        overnight_index: &OvernightIndex,
        discounting_curve: Option<Handle<dyn YieldTermStructure>>,
        payment_lag: Integer,
        payment_convention: BusinessDayConvention,
        payment_frequency: Frequency,
        forward_start: Period,
        overnight_spread: Handle<dyn Quote>,
        pillar: Pillar,
        averaging_method: RateAveraging,
        settings: Shared<Settings<Date>>,
    ) -> Shared<OISRateHelper> {
        Shared::new_cyclic(|weak: &Weak<OISRateHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    helper.initialize_dates();
                }
            });
            let term_structure_handle = RelinkableHandle::<dyn YieldTermStructure>::empty();
            let cloned_index = overnight_index.clone_with(term_structure_handle.handle());
            let base = BootstrapHelperBase::new_relative(
                quote,
                Shared::clone(&settings),
                true,
                on_eval_change,
            );
            if let Some(discount) = &discounting_curve {
                discount.register_observer(&base.observer());
            }
            overnight_spread.register_observer(&base.observer());
            settings.register_fixing_observer(&cloned_index.name(), &base.observer());
            let helper = OISRateHelper {
                base,
                date_error: RefCell::new(None),
                swap: RefCell::new(None),
                overnight_index: cloned_index,
                term_structure_handle,
                discount_relinkable_handle: RelinkableHandle::<dyn YieldTermStructure>::empty(),
                discount_handle: discounting_curve,
                overnight_spread,
                settings,
                settlement_days,
                tenor,
                forward_start,
                payment_lag,
                payment_convention,
                payment_frequency,
                averaging_method,
                pillar,
            };
            helper.initialize_dates();
            helper
        })
    }
}

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

impl RateHelper for OISRateHelper {
    fn base(&self) -> &BootstrapHelperBase {
        &self.base
    }

    /// The par OIS rate implied by the current curve (`oisratehelper.cpp:220-232`).
    ///
    /// The curve is brought up to date before the swap is borrowed, so a stale
    /// curve re-bootstraps without re-entering this helper's borrowed swap; the
    /// rate is then priced on the converged curve, as C++ does through
    /// `LazyObject::calculate` (`lazyobject.hpp:257-258`).
    ///
    /// The swap is force-recalculated first (the C++ `swap_->deepUpdate()`,
    /// forced because the helper does not observe the curve); then the rate is
    /// reconstructed from the overnight-leg NPV, the spread carried on the
    /// overnight-leg BPS, and the fixed-leg BPS, rather than read from
    /// `fair_rate()`.
    fn implied_quote(&self) -> QlResult<Real> {
        self.validate_dates()?;
        let curve = self.base.term_structure()?;
        curve.discount(0.0, true)?;
        let mut guard = self.swap.borrow_mut();
        let swap = guard
            .as_mut()
            .expect("initialize_dates populates the swap at construction");
        swap.recalculate()?;

        const BASIS_POINT: Real = 1.0e-4;
        let overnight_leg_npv = swap.overnight_leg_npv()?;
        let spread = if self.overnight_spread.is_empty() {
            0.0
        } else {
            self.overnight_spread.current_link()?.value()?
        };
        let spread_npv = swap.overnight_leg_bps()? / BASIS_POINT * spread;
        let total_npv = -(overnight_leg_npv + spread_npv);
        let fixed_leg_bps = swap.fixed_vs_floating_mut().fixed_leg_bps()?;
        Ok(total_npv / (fixed_leg_bps / BASIS_POINT))
    }

    /// Weak-links the forecasting handle (used by the cloned overnight index) and
    /// the discounting handle to the bootstrapping curve - or, when an exogenous
    /// discounting curve was supplied, links the discounting handle to that
    /// instead - then records the curve on the base (`oisratehelper.cpp:198-210`).
    /// All links are non-owning and unobserved.
    fn set_term_structure(&self, term_structure: &Shared<dyn YieldTermStructure>) {
        self.term_structure_handle
            .link_to_weak(Shared::downgrade(term_structure));
        match &self.discount_handle {
            Some(discount) if !discount.is_empty() => {
                let curve = discount
                    .current_link()
                    .expect("a non-empty discount handle resolves");
                self.discount_relinkable_handle
                    .link_to_weak(Shared::downgrade(&curve));
            }
            _ => self
                .discount_relinkable_handle
                .link_to_weak(Shared::downgrade(term_structure)),
        }
        self.base.set_term_structure(term_structure);
    }
}

impl RelativeDateRateHelper for OISRateHelper {
    /// Rebuilds the OIS and its schedule off the current evaluation date
    /// (`initializeDates`, `oisratehelper.cpp:128-193`): a swap of the helper's
    /// tenor built through [`MakeOis`]' whole builder chain with a 0% fixed rate
    /// so it does not price at construction.
    ///
    /// The latest relevant date includes payments and the final fixing end.
    fn initialize_dates(&self) {
        *self.date_error.borrow_mut() = self.try_initialize_dates().err();
    }
}

impl OISRateHelper {
    fn try_initialize_dates(&self) -> QlResult<()> {
        let (swap, earliest, maturity, latest_relevant, pillar) = rebuild_dates(|| {
            let swap = MakeOis::new(
                self.tenor,
                Shared::clone(&self.overnight_index),
                Some(0.0),
                self.forward_start,
                Shared::clone(&self.settings),
            )
            .with_discounting_term_structure(self.discount_relinkable_handle.handle())
            .with_telescopic_value_dates(false)
            .with_payment_lag(self.payment_lag)
            .with_payment_adjustment(self.payment_convention)
            .with_payment_frequency(self.payment_frequency)
            .with_averaging_method(self.averaging_method)
            .with_lookback_days(None)
            .with_lockout_days(0)
            .with_rule(DateGeneration::Backward)
            .with_convention(BusinessDayConvention::ModifiedFollowing)
            .with_termination_date_convention(BusinessDayConvention::ModifiedFollowing)
            .with_observation_shift(false)
            .with_settlement_days(self.settlement_days)
            .build()?;

            let base_swap = swap.fixed_vs_floating();
            let earliest = swap
                .overnight_schedule()
                .start_date()
                .min(base_swap.fixed_schedule().start_date());
            let maturity = swap
                .overnight_schedule()
                .end_date()
                .max(base_swap.fixed_schedule().end_date());

            let last_overnight_payment =
                swap.overnight_leg().last().map_or(maturity, |cf| cf.date());
            let last_fixed_payment = base_swap
                .fixed_leg()
                .last()
                .map_or(maturity, |cf| cf.date());
            let latest_relevant = maturity
                .max(last_overnight_payment)
                .max(last_fixed_payment)
                .max(swap.last_fixing_end_date()?);

            let pillar = self.pillar.resolve(earliest, maturity, latest_relevant)?;
            Ok((swap, earliest, maturity, latest_relevant, pillar))
        })?;
        self.base.set_earliest_date(earliest);
        self.base.set_maturity_date(maturity);
        self.base.set_latest_relevant_date(latest_relevant);
        self.base.set_latest_date(latest_relevant);

        self.base.set_pillar_date(pillar);

        *self.swap.borrow_mut() = Some(swap);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::interestrate::Compounding;
    use crate::math::interpolations::loglinear::LogLinear;
    use crate::settings::Settings;
    use crate::termstructures::bootstraptraits::Discount;
    use crate::termstructures::yields::FlatForward;
    use crate::termstructures::yields::PiecewiseYieldCurve;
    use crate::test_support::{Flag, as_observer, implied_quote_on_dirty_curve};
    use crate::time::calendars::target::Target;
    use crate::time::date::{Date, Month};
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::frequency::Frequency;
    use crate::time::period::Period;
    use crate::time::timeunit::TimeUnit;
    use crate::{currency::Currency, types::Rate};

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

    fn euribor(
        tenor: Period,
        forwarding: Handle<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> IborIndex {
        IborIndex::new(
            "Euribor".into(),
            tenor,
            2,
            Currency::eur(),
            Target::new(),
            BusinessDayConvention::Following,
            false,
            Actual360::new(),
            forwarding,
            settings,
        )
    }

    fn flat_curve(reference: Date, rate: Rate) -> Shared<dyn YieldTermStructure> {
        shared(FlatForward::with_rate(
            reference,
            rate,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>
    }

    fn today() -> Date {
        Date::new(15, Month::June, 2026)
    }

    /// Standalone oracle: off a flat continuously-compounded curve the implied
    /// deposit rate is the closed-form simple forward `(exp(r*t) - 1)/t` over
    /// the helper's value-to-maturity window, and equals the index fixing path.
    #[test]
    fn implied_quote_matches_closed_form_deposit_rate() {
        let settings = settings_on(today());
        let source = euribor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);
        let helper = DepositRateHelper::from_rate(0.02, &source);

        let rate = 0.03;
        let curve = flat_curve(today(), rate);
        helper.set_term_structure(&curve);

        let d1 = helper.earliest_date();
        let d2 = helper.maturity_date();
        let t = Actual360::new().year_fraction(d1, d2);
        let implied = helper.implied_quote().unwrap();

        let closed_form = ((rate * t).exp() - 1.0) / t;
        assert!((implied - closed_form).abs() < 1e-12);
    }

    /// `initializeDates` derives earliest/maturity/pillar from the index
    /// conventions off the evaluation date (`ratehelpers.cpp:228`).
    #[test]
    fn initialize_dates_follows_the_index_conventions() {
        let settings = settings_on(today());
        let source = euribor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);
        let helper = DepositRateHelper::from_rate(0.02, &source);

        let reference = source
            .fixing_calendar()
            .adjust(today(), BusinessDayConvention::Following);
        let earliest = source.value_date(reference).unwrap();
        let maturity = source.maturity_date(earliest).unwrap();

        assert_eq!(helper.earliest_date(), earliest);
        assert!(earliest > today(), "the value date is spot, past today");
        assert_eq!(helper.maturity_date(), maturity);
        assert_eq!(helper.pillar_date(), maturity);
        assert_eq!(helper.latest_relevant_date(), maturity);
    }

    /// The clone mechanism: the helper forecasts off its OWN handle (the curve
    /// it is bootstrapped against), leaving the source index - here on an empty
    /// handle - untouched.
    #[test]
    fn helper_prices_off_its_own_handle_not_the_source_index() {
        let settings = settings_on(today());
        let source = euribor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);
        let helper = DepositRateHelper::from_rate(0.02, &source);

        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);
        let implied_low = helper.implied_quote().unwrap();

        let curve_high = flat_curve(today(), 0.06);
        helper.set_term_structure(&curve_high);
        let implied_high = helper.implied_quote().unwrap();

        assert!(
            implied_high > implied_low,
            "relinking the helper's handle moves its implied quote"
        );
        assert!(
            source.forecast_fixing(helper.earliest_date()).is_err(),
            "the source index's own empty handle is untouched"
        );
    }

    /// `quote_error` is market minus implied.
    #[test]
    fn quote_error_is_market_minus_implied() {
        let settings = settings_on(today());
        let source = euribor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);
        let helper = DepositRateHelper::from_rate(0.05, &source);

        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);

        let implied = helper.implied_quote().unwrap();
        assert!((helper.quote_error().unwrap() - (0.05 - implied)).abs() < 1e-15);
    }

    /// An evaluation-date change reruns `initializeDates` and notifies observers.
    #[test]
    fn evaluation_date_change_reinitializes_dates() {
        let settings = settings_on(today());
        let source = euribor(
            Period::new(6, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let helper = DepositRateHelper::from_rate(0.02, &source);
        let before = helper.earliest_date();

        let flag = Flag::new();
        helper.observable().register_observer(&as_observer(&flag));

        let moved = today() + 30;
        settings.set_evaluation_date(moved);

        assert!(Flag::is_up(&flag), "date change must notify observers");
        assert!(
            helper.earliest_date() > before,
            "date change must rerun initialize_dates"
        );
    }

    fn swap_setup() -> (Shared<Settings<Date>>, IborIndex) {
        let settings = settings_on(today());
        let source = euribor(
            Period::new(6, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        (settings, source)
    }

    /// Builds the same spot-starting swap the helper builds, directly on `curve`,
    /// for a cross-implementation identity: a separate [`MakeVanillaSwap`]
    /// instance priced by its own [`DiscountingSwapEngine`].
    fn independent_swap(
        source: &IborIndex,
        tenor: Period,
        calendar: Calendar,
        convention: BusinessDayConvention,
        curve: &Shared<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> VanillaSwap {
        let curve_handle = Handle::new(Shared::clone(curve));
        let index = shared(source.clone_with(curve_handle.clone()));
        MakeVanillaSwap::new(
            tenor,
            index,
            Some(0.0),
            Period::new(0, TimeUnit::Days),
            settings,
        )
        .with_discounting_term_structure(curve_handle)
        .with_fixed_leg_day_count(Actual360::new())
        .with_fixed_leg_tenor(Period::try_from(Frequency::Annual).unwrap())
        .with_fixed_leg_convention(convention)
        .with_fixed_leg_termination_date_convention(convention)
        .with_fixed_leg_calendar(calendar.clone())
        .with_fixed_leg_end_of_month(false)
        .with_floating_leg_calendar(calendar)
        .with_floating_leg_end_of_month(false)
        .build()
        .unwrap()
    }

    /// With no spread, the reconstructed `implied_quote` equals the fair rate of
    /// the same swap computed independently - the par-rate formula reduces to the
    /// fair rate exactly.
    #[test]
    fn implied_quote_matches_fair_rate_of_the_same_swap() {
        let (settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let calendar = Target::new();
        let convention = BusinessDayConvention::ModifiedFollowing;
        let helper = SwapRateHelper::from_rate(
            0.02,
            tenor,
            calendar.clone(),
            Frequency::Annual,
            convention,
            Actual360::new(),
            &source,
        );
        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);

        let implied = helper.implied_quote().unwrap();
        let mut independent =
            independent_swap(&source, tenor, calendar, convention, &curve, settings);
        let fair = independent.fixed_vs_floating_mut().fair_rate().unwrap();
        assert!(
            (implied - fair).abs() < 1e-12,
            "implied {implied} vs fair {fair}"
        );
    }

    /// A nonzero spread shifts the implied quote off the fair rate by exactly
    /// `spread * floatingLegBPS / fixedLegBPS` (BPS from an independent swap) -
    /// the term a bare `fair_rate()` would drop.
    #[test]
    fn nonzero_spread_shifts_the_implied_quote_by_the_bps_ratio() {
        let (settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let calendar = Target::new();
        let convention = BusinessDayConvention::ModifiedFollowing;
        let curve = flat_curve(today(), 0.03);

        let helper0 = SwapRateHelper::from_rate(
            0.02,
            tenor,
            calendar.clone(),
            Frequency::Annual,
            convention,
            Actual360::new(),
            &source,
        );
        helper0.set_term_structure(&curve);
        let implied0 = helper0.implied_quote().unwrap();

        let spread = 0.001;
        let spread_handle = Handle::new(shared(SimpleQuote::new(spread)) as Shared<dyn Quote>);
        let helper_s = SwapRateHelper::with_details(
            Handle::new(shared(SimpleQuote::new(0.02)) as Shared<dyn Quote>),
            tenor,
            calendar.clone(),
            Frequency::Annual,
            convention,
            Actual360::new(),
            &source,
            spread_handle,
            Period::new(0, TimeUnit::Days),
            None,
            Pillar::LastRelevantDate,
        );
        helper_s.set_term_structure(&curve);
        let implied_s = helper_s.implied_quote().unwrap();

        assert!(
            (implied_s - implied0).abs() > 1e-8,
            "the spread must move the implied quote"
        );

        let mut independent =
            independent_swap(&source, tenor, calendar, convention, &curve, settings);
        let floating_bps = independent
            .fixed_vs_floating_mut()
            .floating_leg_bps()
            .unwrap();
        let fixed_bps = independent.fixed_vs_floating_mut().fixed_leg_bps().unwrap();
        let expected = implied0 - spread * floating_bps / fixed_bps;
        assert!(
            (implied_s - expected).abs() < 1e-12,
            "implied_s {implied_s} vs expected {expected}"
        );
    }

    /// The forced recalculation: moving the curve (mutating its underlying quote,
    /// not relinking) changes the implied quote even though the helper never
    /// observes the curve and receives no notification - proving `implied_quote`
    /// forces a fresh calculation rather than reading a stale cache.
    #[test]
    fn moving_the_curve_updates_the_quote_without_notifying_the_helper() {
        let (_settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let helper = SwapRateHelper::from_rate(
            0.02,
            tenor,
            Target::new(),
            Frequency::Annual,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            &source,
        );

        let quote = shared(SimpleQuote::new(0.03));
        let curve: Shared<dyn YieldTermStructure> = shared(FlatForward::new(
            today(),
            Handle::new(Shared::clone(&quote) as Shared<dyn Quote>),
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        ));
        helper.set_term_structure(&curve);
        let implied_before = helper.implied_quote().unwrap();

        let flag = Flag::new();
        helper.observable().register_observer(&as_observer(&flag));

        quote.set_value(0.05);
        assert!(
            !Flag::is_up(&flag),
            "the helper must not observe the bootstrapping curve"
        );

        let implied_after = helper.implied_quote().unwrap();
        assert!(
            (implied_after - implied_before).abs() > 1e-6,
            "the forced recalculation must surface the curve move without a notification"
        );
    }

    /// `initialize_dates` builds a spot-starting swap and the pillar follows the
    /// [`Pillar`] choice.
    #[test]
    fn initialize_dates_spot_starts_and_pillar_follows_the_choice() {
        let (_settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let helper = SwapRateHelper::with_details(
            Handle::new(shared(SimpleQuote::new(0.02)) as Shared<dyn Quote>),
            tenor,
            Target::new(),
            Frequency::Annual,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            &source,
            Handle::empty(),
            Period::new(0, TimeUnit::Days),
            None,
            Pillar::MaturityDate,
        );
        assert!(
            helper.earliest_date() > today(),
            "the swap starts spot, past today"
        );
        assert!(helper.maturity_date() > helper.earliest_date());
        assert_eq!(
            helper.pillar_date(),
            helper.maturity_date(),
            "the MaturityDate pillar equals the maturity"
        );
    }

    /// `quote_error` is market minus implied.
    #[test]
    fn swap_quote_error_is_market_minus_implied() {
        let (_settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let helper = SwapRateHelper::from_rate(
            0.05,
            tenor,
            Target::new(),
            Frequency::Annual,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            &source,
        );
        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);

        let implied = helper.implied_quote().unwrap();
        assert!((helper.quote_error().unwrap() - (0.05 - implied)).abs() < 1e-15);
    }

    /// Bootstraps a curve through the helper `build` makes on an exogenous
    /// discounting curve backed by a [`SimpleQuote`], moves that quote, and
    /// checks the existing curve re-bootstraps to the same discount factor as a
    /// curve built fresh on the moved quote (`ratehelpers.cpp:544`,
    /// `oisratehelper.cpp:119`). Without the helper observing its discounting
    /// handle the existing curve stays stale.
    fn assert_curve_tracks_exogenous_discount(
        build: impl Fn(Handle<dyn YieldTermStructure>) -> Shared<dyn RateHelper>,
    ) {
        let discount_curve = |quote: &Shared<SimpleQuote>| {
            Handle::new(shared(FlatForward::new(
                today(),
                Handle::new(Shared::clone(quote) as Shared<dyn Quote>),
                Actual360::new(),
                Compounding::Continuous,
                Frequency::Annual,
            )) as Shared<dyn YieldTermStructure>)
        };
        let bootstrap = |helper: Shared<dyn RateHelper>| {
            let maturity = helper.maturity_date();
            let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
                today(),
                vec![helper],
                Actual360::new(),
                LogLinear,
            )
            .unwrap();
            (curve, maturity)
        };

        let quote = shared(SimpleQuote::new(0.01));
        let (curve, maturity) = bootstrap(build(discount_curve(&quote)));
        let before = curve.discount_date(maturity, false).unwrap();

        quote.set_value(0.05);
        let moved = curve.discount_date(maturity, false).unwrap();

        let fresh_quote = shared(SimpleQuote::new(0.05));
        let (fresh_curve, _) = bootstrap(build(discount_curve(&fresh_quote)));
        let fresh = fresh_curve.discount_date(maturity, false).unwrap();

        assert!(
            (fresh - before).abs() > 1e-8,
            "degenerate fixture: the discounting curve does not move the bootstrap"
        );
        assert!(
            (moved - fresh).abs() < 1e-12,
            "stale curve after the discounting quote moved: {moved} vs fresh {fresh}"
        );
    }

    #[test]
    fn swap_helper_observes_its_exogenous_discounting_curve() {
        let (_settings, source) = swap_setup();
        assert_curve_tracks_exogenous_discount(|discount| {
            SwapRateHelper::with_details(
                Handle::new(shared(SimpleQuote::new(0.03)) as Shared<dyn Quote>),
                Period::new(5, TimeUnit::Years),
                Target::new(),
                Frequency::Annual,
                BusinessDayConvention::ModifiedFollowing,
                Actual360::new(),
                &source,
                Handle::empty(),
                Period::new(0, TimeUnit::Days),
                Some(discount),
                Pillar::LastRelevantDate,
            ) as Shared<dyn RateHelper>
        });
    }

    /// Bootstraps a curve through a [`SwapRateHelper`] carrying a market spread,
    /// moves the spread, and checks the existing curve re-bootstraps to the same
    /// discount factor as a curve built fresh on the moved spread
    /// (`ratehelpers.cpp:543`). The spread is observed even through a handle
    /// that is empty at construction and linked later, as C++ `registerWith`
    /// registers an empty handle.
    #[test]
    fn swap_helper_observes_its_spread() {
        let (_settings, source) = swap_setup();
        let bootstrap = |spread: Handle<dyn Quote>| {
            let helper = SwapRateHelper::with_details(
                Handle::new(shared(SimpleQuote::new(0.03)) as Shared<dyn Quote>),
                Period::new(5, TimeUnit::Years),
                Target::new(),
                Frequency::Annual,
                BusinessDayConvention::ModifiedFollowing,
                Actual360::new(),
                &source,
                spread,
                Period::new(0, TimeUnit::Days),
                None,
                Pillar::LastRelevantDate,
            );
            let maturity = helper.maturity_date();
            let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
                today(),
                vec![helper as Shared<dyn RateHelper>],
                Actual360::new(),
                LogLinear,
            )
            .unwrap();
            (curve, maturity)
        };
        let quote_handle =
            |value: Real| Handle::new(shared(SimpleQuote::new(value)) as Shared<dyn Quote>);

        let spread = shared(SimpleQuote::new(0.001));
        let (curve, maturity) = bootstrap(Handle::new(Shared::clone(&spread) as Shared<dyn Quote>));
        let before = curve.discount_date(maturity, false).unwrap();
        spread.set_value(0.004);
        let moved = curve.discount_date(maturity, false).unwrap();
        let (fresh_curve, _) = bootstrap(quote_handle(0.004));
        let fresh = fresh_curve.discount_date(maturity, false).unwrap();
        assert!(
            (fresh - before).abs() > 1e-6,
            "degenerate fixture: the spread does not move the bootstrap"
        );
        assert!(
            (moved - fresh).abs() < 1e-12,
            "stale curve after the spread moved: {moved} vs fresh {fresh}"
        );

        let relinkable = RelinkableHandle::<dyn Quote>::empty();
        let (curve, _) = bootstrap(relinkable.handle());
        let unspread = curve.discount_date(maturity, false).unwrap();
        relinkable.link_to(shared(SimpleQuote::new(0.004)) as Shared<dyn Quote>);
        let linked = curve.discount_date(maturity, false).unwrap();
        assert!((unspread - fresh).abs() > 1e-6);
        assert!(
            (linked - fresh).abs() < 1e-12,
            "stale curve after linking the spread: {linked} vs fresh {fresh}"
        );
    }

    /// Bootstraps a curve through the helper `build` makes, records a fixing
    /// dated on the evaluation date (the first floating coupon's fixing), and
    /// checks the existing curve re-bootstraps to the same discount factor as a
    /// curve built fresh with that fixing present (`ratehelpers.cpp:542`,
    /// `oisratehelper.cpp:118`). Without the helper observing the fixing
    /// history the existing curve stays stale.
    fn assert_curve_tracks_todays_fixing(
        build: impl Fn() -> Shared<dyn RateHelper>,
        add_fixing: impl FnOnce(),
    ) {
        let bootstrap = || {
            let helper = build();
            let maturity = helper.maturity_date();
            let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
                today(),
                vec![helper],
                Actual360::new(),
                LogLinear,
            )
            .unwrap();
            (curve, maturity)
        };

        let (curve, maturity) = bootstrap();
        let before = curve.discount_date(maturity, false).unwrap();
        add_fixing();
        let moved = curve.discount_date(maturity, false).unwrap();
        let (fresh_curve, _) = bootstrap();
        let fresh = fresh_curve.discount_date(maturity, false).unwrap();

        assert!(
            (fresh - before).abs() > 1e-6,
            "degenerate fixture: today's fixing does not move the bootstrap"
        );
        assert!(
            (moved - fresh).abs() < 1e-12,
            "stale curve after today's fixing: {moved} vs fresh {fresh}"
        );
    }

    fn five_year_swap_helper(source: &IborIndex) -> Shared<SwapRateHelper> {
        SwapRateHelper::with_details(
            Handle::new(shared(SimpleQuote::new(0.03)) as Shared<dyn Quote>),
            Period::new(5, TimeUnit::Years),
            Target::new(),
            Frequency::Annual,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            source,
            Handle::empty(),
            Period::new(0, TimeUnit::Days),
            None,
            Pillar::LastRelevantDate,
        )
    }

    #[test]
    fn swap_helper_observes_todays_fixing() {
        let (_settings, source) = swap_setup();
        assert_curve_tracks_todays_fixing(
            || five_year_swap_helper(&source) as Shared<dyn RateHelper>,
            || source.add_fixing(today(), 0.08).unwrap(),
        );
    }

    #[test]
    fn ois_helper_observes_todays_fixing() {
        use crate::indexes::ibor::Estr;

        let settings = settings_on(today());
        let estr = Estr::new(Handle::empty(), settings.clone());
        assert_curve_tracks_todays_fixing(
            || {
                OISRateHelper::new(
                    0,
                    Period::new(1, TimeUnit::Months),
                    Handle::new(shared(SimpleQuote::new(0.03)) as Shared<dyn Quote>),
                    &estr,
                    None,
                    0,
                    BusinessDayConvention::Following,
                    Frequency::Annual,
                    Period::new(0, TimeUnit::Days),
                    Handle::empty(),
                    Pillar::LastRelevantDate,
                    RateAveraging::Compound,
                    settings.clone(),
                ) as Shared<dyn RateHelper>
            },
            || estr.add_fixing(today(), 0.08).unwrap(),
        );
    }

    /// A direct `implied_quote()` on a dirty curve re-bootstraps first and
    /// prices on the converged curve, as C++ does (`lazyobject.hpp:257-258`),
    /// rather than re-borrowing the swap from inside the nested bootstrap.
    #[test]
    fn swap_implied_quote_on_a_dirty_curve_reprices_the_new_quote() {
        let (_settings, source) = swap_setup();
        let (dirty, fresh) = implied_quote_on_dirty_curve(today(), 0.03, 0.04, |quote| {
            SwapRateHelper::with_details(
                quote,
                Period::new(1, TimeUnit::Years),
                Target::new(),
                Frequency::Annual,
                BusinessDayConvention::ModifiedFollowing,
                Actual360::new(),
                &source,
                Handle::empty(),
                Period::new(0, TimeUnit::Days),
                None,
                Pillar::LastRelevantDate,
            ) as Shared<dyn RateHelper>
        });
        assert!((dirty - fresh).abs() < 1e-10, "{dirty} vs {fresh}");
        assert!((dirty - 0.04).abs() < 1e-9, "{dirty}");
    }

    #[test]
    fn ois_implied_quote_on_a_dirty_curve_reprices_the_new_quote() {
        use crate::indexes::ibor::Estr;

        let settings = settings_on(today());
        let estr = Estr::new(Handle::empty(), settings.clone());
        let (dirty, fresh) = implied_quote_on_dirty_curve(today(), 0.03, 0.04, |quote| {
            OISRateHelper::new(
                2,
                Period::new(1, TimeUnit::Years),
                quote,
                &estr,
                None,
                0,
                BusinessDayConvention::Following,
                Frequency::Annual,
                Period::new(0, TimeUnit::Days),
                Handle::empty(),
                Pillar::LastRelevantDate,
                RateAveraging::Compound,
                settings.clone(),
            ) as Shared<dyn RateHelper>
        });
        assert!((dirty - fresh).abs() < 1e-10, "{dirty} vs {fresh}");
        assert!((dirty - 0.04).abs() < 1e-9, "{dirty}");
    }

    /// The FRA helper is notified of a fixing (`ratehelpers.cpp:318`), and so
    /// invalidates the curve, but its value cannot move: the indexed quote
    /// forecasts even today's fixing (`ratehelpers.cpp:364`) and the par quote
    /// reads discount factors only.
    #[test]
    fn fra_helper_observes_fixings_without_moving_the_curve() {
        let (_settings, source) = swap_setup();
        let helper = FraRateHelper::new(
            Handle::new(shared(SimpleQuote::new(0.03)) as Shared<dyn Quote>),
            Period::new(0, TimeUnit::Months),
            &source,
            true,
            Pillar::LastRelevantDate,
        );
        let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
            today(),
            vec![Shared::clone(&helper) as Shared<dyn RateHelper>],
            Actual360::new(),
            LogLinear,
        )
        .unwrap();
        let maturity = helper.maturity_date();
        let before = curve.discount_date(maturity, false).unwrap();
        let helper_flag = Flag::new();
        let curve_flag = Flag::new();
        helper
            .observable()
            .register_observer(&as_observer(&helper_flag));
        curve.register_observer(&as_observer(&curve_flag));

        source.add_fixing(today(), 0.08).unwrap();

        assert!(Flag::is_up(&helper_flag), "a fixing must notify the helper");
        assert!(
            Flag::is_up(&curve_flag),
            "a fixing must invalidate the curve"
        );
        let after = curve.discount_date(maturity, false).unwrap();
        assert!((after - before).abs() < 1e-12);
    }

    /// Relinking the source index's forwarding handle to the curve the helper
    /// bootstraps, and away again, neither notifies the helper nor loops; a
    /// fixing still reaches it through the fixing history.
    #[test]
    fn swap_helper_relinks_do_not_loop_and_fixings_still_notify() {
        let settings = settings_on(today());
        let forwarding = RelinkableHandle::<dyn YieldTermStructure>::empty();
        let source = euribor(
            Period::new(6, TimeUnit::Months),
            forwarding.handle(),
            settings,
        );
        let helper = five_year_swap_helper(&source);
        let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
            today(),
            vec![Shared::clone(&helper) as Shared<dyn RateHelper>],
            Actual360::new(),
            LogLinear,
        )
        .unwrap();
        let maturity = helper.maturity_date();
        let flag = Flag::new();
        helper.observable().register_observer(&as_observer(&flag));

        forwarding.link_to(Shared::clone(&curve) as Shared<dyn YieldTermStructure>);
        let linked = curve.discount_date(maturity, false).unwrap();
        forwarding.link_to(flat_curve(today(), 0.04));
        let relinked = curve.discount_date(maturity, false).unwrap();
        assert!(!Flag::is_up(&flag), "a relink must not notify the helper");
        assert!((linked - relinked).abs() < 1e-12);

        forwarding.link_to(Shared::clone(&curve) as Shared<dyn YieldTermStructure>);
        source.add_fixing(today(), 0.08).unwrap();
        assert!(Flag::is_up(&flag), "a fixing must notify the helper");
        let fixed = curve.discount_date(maturity, false).unwrap();
        assert!((fixed - linked).abs() > 1e-6);
    }

    #[test]
    fn ois_helper_observes_its_exogenous_discounting_curve() {
        use crate::indexes::ibor::Estr;

        let settings = settings_on(today());
        let estr = Estr::new(Handle::empty(), settings.clone());
        assert_curve_tracks_exogenous_discount(|discount| {
            OISRateHelper::new(
                2,
                Period::new(5, TimeUnit::Years),
                Handle::new(shared(SimpleQuote::new(0.03)) as Shared<dyn Quote>),
                &estr,
                Some(discount),
                2,
                BusinessDayConvention::Following,
                Frequency::Annual,
                Period::new(0, TimeUnit::Days),
                Handle::empty(),
                Pillar::LastRelevantDate,
                RateAveraging::Compound,
                settings.clone(),
            ) as Shared<dyn RateHelper>
        });
    }

    /// QuantLib 1.43 values from `tests/fixtures/overnight_averaging/bindings.json`.
    #[test]
    fn ois_spread_updates_rebootstrap_without_retaining_the_curve() {
        use crate::indexes::ibor::Estr;
        use crate::math::interpolations::loglinear::LogLinear;
        use crate::termstructures::bootstraptraits::Discount;
        use crate::termstructures::yields::PiecewiseYieldCurve;

        for (averaging, initial_discount, updated_discount) in [
            (
                RateAveraging::Compound,
                0.9533435978894659,
                0.9542712749129756,
            ),
            (
                RateAveraging::Simple,
                0.9522505927886751,
                0.9532216074564187,
            ),
        ] {
            let reference = Date::new(7, Month::July, 2026);
            let settings = settings_on(reference);
            let index = Estr::new(Handle::empty(), settings.clone());
            let spread = shared(SimpleQuote::new(0.002));
            let spread_handle = RelinkableHandle::new(spread.clone() as Shared<dyn Quote>);
            let helper = OISRateHelper::new(
                2,
                Period::new(1, TimeUnit::Years),
                Handle::new(shared(SimpleQuote::new(0.05)) as Shared<dyn Quote>),
                &index,
                None,
                2,
                BusinessDayConvention::Following,
                Frequency::Annual,
                Period::new(0, TimeUnit::Days),
                spread_handle.handle(),
                Pillar::LastRelevantDate,
                averaging,
                settings,
            );
            let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
                reference,
                vec![helper.clone() as Shared<dyn RateHelper>],
                Actual360::new(),
                LogLinear,
            )
            .unwrap();
            let maturity = helper.maturity_date();
            assert!(
                (curve.discount_date(maturity, false).unwrap() - initial_discount).abs() < 1e-12
            );
            spread.set_value(0.003);
            assert!(
                (curve.discount_date(maturity, false).unwrap() - updated_discount).abs() < 1e-12
            );
            assert!((helper.implied_quote().unwrap() - 0.05).abs() < 1e-12);
            spread_handle.link_to(shared(SimpleQuote::new(0.002)) as Shared<dyn Quote>);
            assert!(
                (curve.discount_date(maturity, false).unwrap() - initial_discount).abs() < 1e-12
            );
            let weak_helper = Shared::downgrade(&helper);
            let weak_curve = Shared::downgrade(&curve);
            drop(helper);
            drop(curve);
            assert!(weak_helper.upgrade().is_none());
            assert!(weak_curve.upgrade().is_none());
            spread.set_value(0.004);
        }
    }

    /// `overnightindexedswap.cpp estrSwapData` (`:92-125`): the OIS quotes the
    /// bootstrap oracle fits, `(tenor length, unit, rate %)`; all use two
    /// settlement days.
    const ESTR_SWAP_DATA: [(i32, TimeUnit, Real); 33] = [
        (1, TimeUnit::Weeks, 1.245),
        (2, TimeUnit::Weeks, 1.269),
        (3, TimeUnit::Weeks, 1.277),
        (1, TimeUnit::Months, 1.281),
        (2, TimeUnit::Months, 1.18),
        (3, TimeUnit::Months, 1.143),
        (4, TimeUnit::Months, 1.125),
        (5, TimeUnit::Months, 1.116),
        (6, TimeUnit::Months, 1.111),
        (7, TimeUnit::Months, 1.109),
        (8, TimeUnit::Months, 1.111),
        (9, TimeUnit::Months, 1.117),
        (10, TimeUnit::Months, 1.129),
        (11, TimeUnit::Months, 1.141),
        (12, TimeUnit::Months, 1.153),
        (15, TimeUnit::Months, 1.218),
        (18, TimeUnit::Months, 1.308),
        (21, TimeUnit::Months, 1.407),
        (2, TimeUnit::Years, 1.510),
        (3, TimeUnit::Years, 1.916),
        (4, TimeUnit::Years, 2.254),
        (5, TimeUnit::Years, 2.523),
        (6, TimeUnit::Years, 2.746),
        (7, TimeUnit::Years, 2.934),
        (8, TimeUnit::Years, 3.092),
        (9, TimeUnit::Years, 3.231),
        (10, TimeUnit::Years, 3.380),
        (11, TimeUnit::Years, 3.457),
        (12, TimeUnit::Years, 3.544),
        (15, TimeUnit::Years, 3.702),
        (20, TimeUnit::Years, 3.703),
        (25, TimeUnit::Years, 3.541),
        (30, TimeUnit::Years, 3.369),
    ];

    /// `overnightindexedswap.cpp testBaseBootstrap` (`:397` ->
    /// `testBootstrap(false, RateAveraging::Compound)`, `:208`): an Estr
    /// discounting curve bootstrapped purely from [`OISRateHelper`]s reprices
    /// every OIS quote to 1e-8.
    ///
    /// The deposit helpers of the C++ setup are omitted deliberately: for a zero
    /// spread `implied_quote == fair_rate`, and each swap tenor is self-pinned by
    /// its own OIS node solved so `implied_quote_i == quote_i`, so
    /// `fair_rate_i == quote_i` to solver accuracy independent of the sub-week
    /// short end the deposits shape. `paymentLag = 2` and `today = 5 Feb 2009`
    /// are transcribed from `CommonVars` / `testBootstrap` (`:180-215`).
    ///
    /// The three sibling cases stay deferred: `testBootstrapWithArithmeticAverage`
    /// (`:402`) needs the arithmetic-averaging pricer, and the two telescopic
    /// cases (`:407`/`:413`) need telescopic value dates - neither on main.
    #[test]
    fn ois_bootstrap_reprices_the_quotes() {
        use crate::indexes::ibor::Estr;
        use crate::math::interpolations::loglinear::LogLinear;
        use crate::termstructures::bootstraptraits::Discount;
        use crate::termstructures::yields::PiecewiseYieldCurve;
        use crate::time::daycounters::actual365fixed::Actual365Fixed;

        const PAYMENT_LAG: Integer = 2;
        let today = Date::new(5, Month::February, 2009);
        let settings = settings_on(today);
        let calendar = Target::new();
        let settlement = calendar.advance(
            today,
            2,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );

        let estr = Estr::new(Handle::empty(), settings.clone());
        let mut instruments: Vec<Shared<dyn RateHelper>> = Vec::new();
        for (n, unit, rate) in ESTR_SWAP_DATA {
            let quote = Handle::new(shared(SimpleQuote::new(rate / 100.0)) as Shared<dyn Quote>);
            let helper = OISRateHelper::new(
                2,
                Period::new(n, unit),
                quote,
                &estr,
                None,
                PAYMENT_LAG,
                BusinessDayConvention::Following,
                Frequency::Annual,
                Period::new(0, TimeUnit::Days),
                Handle::empty(),
                Pillar::LastRelevantDate,
                RateAveraging::Compound,
                settings.clone(),
            );
            instruments.push(helper as Shared<dyn RateHelper>);
        }

        let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
            today,
            instruments,
            Actual365Fixed::new(),
            LogLinear,
        )
        .unwrap();
        let handle: Handle<dyn YieldTermStructure> =
            Handle::new(Shared::clone(&curve) as Shared<dyn YieldTermStructure>);

        for (n, unit, rate) in ESTR_SWAP_DATA {
            let priced_estr = shared(Estr::new(handle.clone(), settings.clone()));
            let mut swap = MakeOis::new(
                Period::new(n, unit),
                priced_estr,
                Some(0.0),
                Period::new(0, TimeUnit::Days),
                settings.clone(),
            )
            .with_effective_date(settlement)
            .with_nominal(100.0)
            .with_payment_lag(PAYMENT_LAG)
            .with_discounting_term_structure(handle.clone())
            .with_averaging_method(RateAveraging::Compound)
            .build()
            .unwrap();

            let calculated = swap.fixed_vs_floating_mut().fair_rate().unwrap();
            let expected = rate / 100.0;
            assert!(
                (calculated - expected).abs() < 1.0e-8,
                "{n} {unit:?} OIS: calculated {calculated} vs expected {expected}"
            );
        }
    }

    fn quote_handle(value: Real) -> Handle<dyn Quote> {
        Handle::new(shared(SimpleQuote::new(value)) as Shared<dyn Quote>)
    }

    /// The convexity-shift pin (`ratehelpers.cpp:157`): two curves bootstrapped
    /// through a single [`FuturesRateHelper`] at the same price, one with zero
    /// convexity and one with `c`, produce forwards that differ by exactly `c`.
    ///
    /// Non-circular: the bootstrap only pins `implied_quote == price` at the
    /// pillar, which fixes `forward = (100 - price)/100 - conv_adj` per curve, so
    /// `forward_c == forward_0 - c` is a property of the convexity term itself,
    /// independent of the discount interpolation. Stubbing
    /// `convexity_adjustment()` to zero collapses both curves onto the same
    /// forward and this assertion fails.
    #[test]
    fn convexity_adjustment_shifts_the_bootstrapped_forward() {
        use crate::math::interpolations::loglinear::LogLinear;
        use crate::termstructures::bootstraptraits::Discount;
        use crate::termstructures::yields::PiecewiseYieldCurve;
        use crate::time::daycounters::actual365fixed::Actual365Fixed;

        let reference = today();
        let imm_start = imm::next_date(reference, false);
        let price = 96.0;
        let c = 0.001;

        let forward_from = |conv_adj: Handle<dyn Quote>| -> Real {
            let helper = FuturesRateHelper::from_end_date(
                quote_handle(price),
                imm_start,
                None,
                Actual360::new(),
                conv_adj,
                FuturesType::Imm,
            )
            .unwrap();
            let earliest = helper.earliest_date();
            let maturity = helper.maturity_date();
            let instruments: Vec<Shared<dyn RateHelper>> = vec![helper as Shared<dyn RateHelper>];
            let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
                reference,
                instruments,
                Actual365Fixed::new(),
                LogLinear,
            )
            .unwrap();
            let disc_e = curve.discount_date(earliest, false).unwrap();
            let disc_m = curve.discount_date(maturity, false).unwrap();
            let yf = Actual360::new().year_fraction_ref(earliest, maturity, earliest, maturity);
            (disc_e / disc_m - 1.0) / yf
        };

        let forward_0 = forward_from(Handle::empty());
        let forward_c = forward_from(quote_handle(c));
        assert!(
            (forward_c - (forward_0 - c)).abs() < 1e-10,
            "forward_c {forward_c} vs forward_0 - c {}",
            forward_0 - c
        );
    }

    /// The bootstrap reprices the futures quote (`ratehelpers.cpp:157`): the
    /// forward recomputed from the bootstrapped discounts reproduces the quoted
    /// price through `100 * (1 - forward - conv_adj)`, and [`implied_quote`] on
    /// the fitted curve returns the price to solver accuracy.
    ///
    /// [`implied_quote`]: RateHelper::implied_quote
    #[test]
    fn bootstrap_reprices_the_futures_quote() {
        use crate::math::interpolations::loglinear::LogLinear;
        use crate::termstructures::bootstraptraits::Discount;
        use crate::termstructures::yields::PiecewiseYieldCurve;
        use crate::time::daycounters::actual365fixed::Actual365Fixed;

        let reference = today();
        let imm_start = imm::next_date(reference, false);
        let price = 96.0;
        let c = 0.001;
        let helper = FuturesRateHelper::from_end_date(
            quote_handle(price),
            imm_start,
            None,
            Actual360::new(),
            quote_handle(c),
            FuturesType::Imm,
        )
        .unwrap();
        let earliest = helper.earliest_date();
        let maturity = helper.maturity_date();
        let instruments: Vec<Shared<dyn RateHelper>> =
            vec![Shared::clone(&helper) as Shared<dyn RateHelper>];
        let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
            reference,
            instruments,
            Actual365Fixed::new(),
            LogLinear,
        )
        .unwrap();

        let disc_e = curve.discount_date(earliest, false).unwrap();
        let disc_m = curve.discount_date(maturity, false).unwrap();
        let yf = Actual360::new().year_fraction_ref(earliest, maturity, earliest, maturity);
        let forward = (disc_e / disc_m - 1.0) / yf;
        let repriced = 100.0 * (1.0 - forward - c);
        assert!(
            (repriced - price).abs() < 1e-9,
            "repriced {repriced} vs {price}"
        );

        let implied = helper.implied_quote().unwrap();
        assert!(
            (implied - price).abs() < 1e-9,
            "implied {implied} vs {price}"
        );
    }

    /// The explicit-date constructor with no end date advances three IMM periods
    /// and pins every schedule date to that window (`ratehelpers.cpp:91`).
    /// Stubbing the three-period advance to a single one makes the expected
    /// maturity disagree and this assertion fails.
    #[test]
    fn from_end_date_advances_three_imm_periods_and_pins_the_schedule() {
        let imm_start = imm::next_date(today(), false);
        assert!(imm::is_imm_date(imm_start, false));
        let helper = FuturesRateHelper::from_end_date(
            quote_handle(96.0),
            imm_start,
            None,
            Actual360::new(),
            Handle::empty(),
            FuturesType::Imm,
        )
        .unwrap();

        let expected_maturity = imm::next_date(
            imm::next_date(imm::next_date(imm_start, false), false),
            false,
        );
        assert_eq!(helper.earliest_date(), imm_start);
        assert_eq!(helper.maturity_date(), expected_maturity);
        assert_eq!(helper.pillar_date(), expected_maturity);
        assert_eq!(helper.latest_date(), expected_maturity);
        assert_eq!(helper.latest_relevant_date(), expected_maturity);
    }

    /// A start that is not a valid IMM date is rejected under the IMM convention
    /// (`CheckDate`, `ratehelpers.cpp:46`).
    #[test]
    fn a_non_imm_start_is_rejected_under_the_imm_convention() {
        let start = today();
        assert!(
            !imm::is_imm_date(start, false),
            "the fixture start must not be an IMM date"
        );
        let result = FuturesRateHelper::from_end_date(
            quote_handle(96.0),
            start,
            None,
            Actual360::new(),
            Handle::empty(),
            FuturesType::Imm,
        );
        assert!(result.is_err());
    }

    /// A Custom helper needs an explicit end date; the C++ null-maturity path is
    /// an error here (divergence documented on [`FuturesRateHelper::from_end_date`]).
    #[test]
    fn a_custom_helper_requires_an_explicit_end_date() {
        let start = today();
        let result = FuturesRateHelper::from_end_date(
            quote_handle(96.0),
            start,
            None,
            Actual360::new(),
            Handle::empty(),
            FuturesType::Custom,
        );
        assert!(result.is_err());
    }

    /// The index constructor takes its window from the index conventions: the
    /// maturity is the start advanced by the index tenor on its fixing calendar
    /// (`ratehelpers.cpp:139`).
    #[test]
    fn from_index_takes_the_window_from_the_index_conventions() {
        let settings = settings_on(today());
        let index = euribor(Period::new(3, TimeUnit::Months), Handle::empty(), settings);
        let imm_start = imm::next_date(today(), false);
        let helper = FuturesRateHelper::from_index(
            quote_handle(96.0),
            imm_start,
            &index,
            Handle::empty(),
            FuturesType::Imm,
        )
        .unwrap();

        let expected_maturity = index.fixing_calendar().advance_by_period(
            imm_start,
            index.tenor(),
            index.business_day_convention(),
            false,
        );
        assert_eq!(helper.earliest_date(), imm_start);
        assert_eq!(helper.maturity_date(), expected_maturity);
    }

    /// `FraRateHelper::initializeDates` (`ratehelpers.cpp:393`): the earliest
    /// date is `period_to_start` past spot and the maturity is the *combined*
    /// `period_to_start + tenor` past spot. The degeneracy guard asserts that on
    /// this evaluation date the faithful (advance-from-spot) maturity really
    /// differs from the plausible-wrong chained reading `advance(earliest,
    /// tenor)`; without the difference the pin would not discriminate the trap.
    #[test]
    fn fra_initialize_dates_advances_maturity_from_spot_not_chained() {
        let eval = Date::new(13, Month::May, 2026);
        let settings = settings_on(eval);
        let index = euribor(Period::new(3, TimeUnit::Months), Handle::empty(), settings);
        let period_to_start = Period::new(3, TimeUnit::Months);
        let helper = FraRateHelper::from_rate(
            0.03,
            period_to_start,
            &index,
            true,
            Pillar::LastRelevantDate,
        );

        let calendar = index.fixing_calendar();
        let reference = calendar.adjust(eval, BusinessDayConvention::Following);
        let spot = index.value_date(reference).unwrap();
        let convention = index.business_day_convention();
        let eom = index.end_of_month();
        let earliest = calendar.advance_by_period(spot, period_to_start, convention, eom);
        let maturity_from_spot =
            calendar.advance_by_period(spot, period_to_start + index.tenor(), convention, eom);
        let maturity_chained = calendar.advance_by_period(earliest, index.tenor(), convention, eom);
        assert_ne!(
            maturity_from_spot, maturity_chained,
            "degenerate fixture: pick an evaluation date where the roll separates the two maturities"
        );

        assert_eq!(helper.earliest_date(), earliest);
        assert_eq!(helper.maturity_date(), maturity_from_spot);
        let latest_relevant = index.maturity_date(earliest).unwrap();
        assert_eq!(helper.latest_relevant_date(), latest_relevant);
        assert_eq!(helper.pillar_date(), latest_relevant);
        assert_eq!(helper.latest_date(), latest_relevant);
    }

    /// The explicit-date constructor (`ratehelpers.cpp:341`, built on
    /// `RelativeDateRateHelper(rate, false)`): its window is fixed at
    /// construction and, unlike the relative constructors, does not shift when
    /// the evaluation date moves. Par mode with the `MaturityDate` pillar pins
    /// the latest-relevant date and pillar at the explicit end date.
    #[test]
    fn fra_from_dates_pins_explicit_window_and_ignores_eval_change() {
        let settings = settings_on(today());
        let index = euribor(
            Period::new(3, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let start = Date::new(15, Month::September, 2026);
        let end = Date::new(15, Month::December, 2026);
        let helper = FraRateHelper::from_dates(
            Handle::new(shared(SimpleQuote::new(0.03)) as Shared<dyn Quote>),
            start,
            end,
            &index,
            false,
            Pillar::MaturityDate,
        );

        assert_eq!(helper.earliest_date(), start);
        assert_eq!(helper.maturity_date(), end);
        assert_eq!(helper.latest_relevant_date(), end);
        assert_eq!(helper.pillar_date(), end);

        settings.set_evaluation_date(today() + 90);
        assert_eq!(
            helper.earliest_date(),
            start,
            "an explicit-date FRA must not shift on an evaluation-date change"
        );
        assert_eq!(helper.maturity_date(), end);
    }

    /// The bootstrap fixture: a short deposit anchor plus one FRA node built by
    /// `factory`, bootstrapped into a `Discount`/`LogLinear` curve. Returns the
    /// curve handle, the evaluation date and the shared settings so the caller
    /// can reprice the FRA arm off independently-reconstructed dates.
    fn bootstrap_with_fra(
        fra: Shared<dyn RateHelper>,
        settings: Shared<Settings<Date>>,
        today: Date,
    ) -> Handle<dyn YieldTermStructure> {
        let calendar = Target::new();
        let settlement = calendar.advance(
            today,
            2,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );
        let deposit_index = euribor(
            Period::new(3, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let deposit = DepositRateHelper::from_rate(0.02, &deposit_index);
        let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
            settlement,
            vec![deposit as Shared<dyn RateHelper>, fra],
            Actual360::new(),
            LogLinear,
        )
        .unwrap();
        Handle::new(Shared::clone(&curve) as Shared<dyn YieldTermStructure>)
    }

    /// Independently reconstructs the FRA `[start, end]` window off `index`'s
    /// conventions for the given evaluation date, so the reprice arms do not
    /// reuse the helper's own (possibly wrong) dates - the discrimination lives
    /// in this from-scratch reconstruction, not in crossing modes.
    fn reconstruct_window(index: &IborIndex, eval: Date, period_to_start: Period) -> (Date, Date) {
        let calendar = index.fixing_calendar();
        let reference = calendar.adjust(eval, BusinessDayConvention::Following);
        let spot = index.value_date(reference).unwrap();
        let convention = index.business_day_convention();
        let eom = index.end_of_month();
        let start = calendar.advance_by_period(spot, period_to_start, convention, eom);
        let end =
            calendar.advance_by_period(spot, period_to_start + index.tenor(), convention, eom);
        (start, end)
    }

    /// Indexed arm (`ratehelpers.cpp:363`): bootstrap through an indexed FRA,
    /// then forecast the fixing off the curve through a fresh index over an
    /// independently reconstructed window and assert it reproduces the input
    /// rate. Passing proves bootstrap convergence; the confirm-by-stubbing gate
    /// (perturbing `fixing_date`) is what proves the date math discriminates.
    #[test]
    fn fra_indexed_bootstrap_reprices_the_input_rate() {
        let eval = Date::new(13, Month::May, 2026);
        let settings = settings_on(eval);
        let period_to_start = Period::new(3, TimeUnit::Months);
        let fra_rate = 0.03;
        let fra_index = euribor(
            Period::new(3, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let fra = FraRateHelper::from_rate(
            fra_rate,
            period_to_start,
            &fra_index,
            true,
            Pillar::LastRelevantDate,
        );
        let handle = bootstrap_with_fra(
            Shared::clone(&fra) as Shared<dyn RateHelper>,
            settings.clone(),
            eval,
        );

        let reprice_index = euribor(
            Period::new(3, TimeUnit::Months),
            handle.clone(),
            settings.clone(),
        );
        let (start, _end) = reconstruct_window(&reprice_index, eval, period_to_start);
        let fixing_date = reprice_index.fixing_date(start);
        let estimated = reprice_index.fixing(fixing_date, true).unwrap();
        assert!(
            (estimated - fra_rate).abs() <= 1.0e-9,
            "indexed reprice {estimated} vs input {fra_rate}"
        );
    }

    /// Par arm (`ratehelpers.cpp:365`): bootstrap through a par FRA, then
    /// recompute the simple forward `(disc(start)/disc(end) - 1)/tau` off the
    /// curve over an independently reconstructed window and assert it reproduces
    /// the input rate. The confirm-by-stubbing gate (perturbing the maturity)
    /// proves the date math discriminates.
    #[test]
    fn fra_par_bootstrap_reprices_the_input_rate() {
        let eval = Date::new(13, Month::May, 2026);
        let settings = settings_on(eval);
        let period_to_start = Period::new(3, TimeUnit::Months);
        let fra_rate = 0.03;
        let fra_index = euribor(
            Period::new(3, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let fra = FraRateHelper::from_rate(
            fra_rate,
            period_to_start,
            &fra_index,
            false,
            Pillar::LastRelevantDate,
        );
        let handle = bootstrap_with_fra(
            Shared::clone(&fra) as Shared<dyn RateHelper>,
            settings.clone(),
            eval,
        );

        let reprice_index = euribor(
            Period::new(3, TimeUnit::Months),
            handle.clone(),
            settings.clone(),
        );
        let (start, end) = reconstruct_window(&reprice_index, eval, period_to_start);
        let chained_end = reprice_index.fixing_calendar().advance_by_period(
            start,
            reprice_index.tenor(),
            reprice_index.business_day_convention(),
            reprice_index.end_of_month(),
        );
        assert_ne!(
            end, chained_end,
            "degenerate fixture: the maturity trap does not bite on this window, so the par reprice would not discriminate it"
        );
        let curve = handle.current_link().unwrap();
        let discount_start = curve.discount_date(start, false).unwrap();
        let discount_end = curve.discount_date(end, false).unwrap();
        let tau = reprice_index.day_counter().year_fraction(start, end);
        let estimated = (discount_start / discount_end - 1.0) / tau;
        assert!(
            (estimated - fra_rate).abs() <= 1.0e-9,
            "par reprice {estimated} vs input {fra_rate}"
        );
    }

    /// D10: a deposit helper built before the evaluation date is set does not
    /// panic; its first read returns the unset-date error, and setting the
    /// date rebuilds a usable schedule.
    #[test]
    fn deposit_unset_evaluation_date_is_an_error_on_first_read() {
        let settings = shared(Settings::<Date>::new());
        let source = euribor(
            Period::new(6, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let helper = DepositRateHelper::from_rate(0.02, &source);
        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);

        let error = helper.quote_error().unwrap_err();
        assert_eq!(error.message(), "evaluation date is not set");

        settings.set_evaluation_date(today());
        assert!(helper.earliest_date() > today());
        helper.quote_error().unwrap();
    }

    /// D10: the FRA helper's unset evaluation date surfaces as that error, not
    /// as the `rebuild_dates` panic fallback "helper dates exceed supported
    /// range", and clears once the date is set.
    #[test]
    fn fra_unset_evaluation_date_is_an_error_on_first_read() {
        let settings = shared(Settings::<Date>::new());
        let source = euribor(
            Period::new(3, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let error = FraRateHelper::try_from_rate(
            0.02,
            Period::new(3, TimeUnit::Months),
            &source,
            true,
            Pillar::LastRelevantDate,
        )
        .err()
        .unwrap();
        assert_eq!(error.message(), "evaluation date is not set");

        let helper = FraRateHelper::from_rate(
            0.02,
            Period::new(3, TimeUnit::Months),
            &source,
            true,
            Pillar::LastRelevantDate,
        );
        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);
        let error = helper.quote_error().unwrap_err();
        assert_eq!(error.message(), "evaluation date is not set");

        settings.set_evaluation_date(today());
        assert!(helper.validate_dates().is_ok());
        assert!(helper.earliest_date() > today());
        helper.quote_error().unwrap();
    }

    /// `testHelperDatesFromNonBusinessEvaluationDate` (v1.44
    /// `piecewiseyieldcurve.cpp:2422`): on Saturday 20 June 2026 the deposit,
    /// FRA and BMA helpers count their fixing / settlement days from the
    /// Saturday itself (`ratehelpers.cpp:232-233/396-397/676-678`). The C++
    /// deposit is built from explicit Euribor6M parameters; the port's
    /// index-based [`DepositRateHelper::from_rate`] builds the same schedule.
    #[test]
    fn helper_dates_from_a_saturday_evaluation_date() {
        use crate::indexes::ibor::Euribor;
        use crate::indexes::{BMAIndex, UsdLibor};
        use crate::termstructures::yields::BMASwapRateHelper;
        use crate::time::calendars::{JointCalendar, JointCalendarRule};

        let settings = settings_on(Date::new(20, Month::June, 2026));
        let euribor6m = Euribor::six_months(Handle::empty(), Shared::clone(&settings));

        let depo = DepositRateHelper::from_rate(0.03, &euribor6m);
        assert_eq!(
            depo.base().earliest_date(),
            Date::new(23, Month::June, 2026)
        );

        let fra = FraRateHelper::from_months(
            Handle::new(shared(SimpleQuote::new(0.03)) as Shared<dyn Quote>),
            3,
            &euribor6m,
            true,
            Pillar::LastRelevantDate,
        );
        assert_eq!(
            fra.base().earliest_date(),
            Date::new(23, Month::September, 2026)
        );

        let bma_index = shared(BMAIndex::new(Handle::empty(), Shared::clone(&settings)));
        let libor = shared(
            UsdLibor::new(
                Period::new(3, TimeUnit::Months),
                Handle::empty(),
                Shared::clone(&settings),
            )
            .unwrap(),
        );
        let bma_calendar = JointCalendar::of_two(
            bma_index.fixing_calendar(),
            libor.fixing_calendar(),
            JointCalendarRule::JoinHolidays,
        );
        let bma = BMASwapRateHelper::new(
            Handle::new(shared(SimpleQuote::new(0.75)) as Shared<dyn Quote>),
            Period::new(5, TimeUnit::Years),
            3,
            bma_calendar,
            Period::new(3, TimeUnit::Months),
            BusinessDayConvention::Following,
            Actual360::new(),
            &bma_index,
            &libor,
        )
        .unwrap();
        assert_eq!(bma.base().earliest_date(), Date::new(24, Month::June, 2026));
    }
}