quantsupport 0.1.7

Rust quantitative finance library for derivatives pricing, yield-curve bootstrapping, AAD risk, Monte Carlo exposure, and XVA.
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
use serde::{Deserialize, Serialize};

use crate::{
    ad::scalar::Scalar,
    currencies::currency::Currency,
    indices::marketindex::MarketIndex,
    instruments::{
        equity::{
            equityeuropeanoption::{EquityEuropeanOption, EuroOptionType},
            makeequityeuropeanoption::MakeEquityEuropeanOption,
        },
        fixedincome::{
            fixedratedeposit::FixedRateDeposit, makefixedratedeposit::MakeFixedRateDeposit,
        },
        fx::{
            fxeuropeanoption::FxEuropeanOption, fxforward::FxForward,
            makefxeuropeanoption::MakeFxEuropeanOption, makefxforward::MakeFxForward,
        },
        rates::{
            basisswap::BasisSwap,
            capfloor::{CapFloor, CapFloorType},
            capletfloorlet::CapletFloorlet,
            europeanswaption::EuropeanSwaption,
            fixfloatcrosscurrencyswap::FixFloatCrossCurrencySwap,
            floatfloatcrosscurrencyswap::FloatFloatCrossCurrencySwap,
            makebasisswap::MakeBasisSwap,
            makecapfloor::MakeCapFloor,
            makeeuropeanswaption::MakeSwaption,
            makefixfloatcrosscurrencyswap::MakeFixFloatCrossCurrencySwap,
            makefloatfloatcrosscurrencyswap::MakeFloatFloatCrossCurrencySwap,
            makeratefutures::MakeRateFutures,
            makeswap::MakeSwap,
            ratefutures::RateFutures,
            swap::Swap,
        },
    },
    time::{date::Date, enums::Frequency, imm::IMM, period::Period},
    utils::errors::{QSError, Result},
    volatility::volatilityindexing::{Strike, VolatilityType},
};

/// Splits a 6-character FX pair string (e.g. `"EURUSD"`) into two currencies.
fn parse_fx_pair(pair: &str) -> Result<(Currency, Currency)> {
    if pair.len() < 6 {
        return Err(QSError::InvalidValueErr(format!(
            "Invalid FX currency pair: {pair}"
        )));
    }
    let base: Currency = pair[..3].parse()?;
    let quote_ccy: Currency = pair[3..6].parse()?;
    Ok((base, quote_ccy))
}

fn parse_strike(id: &str, kind: &str, value: &str) -> Result<Strike> {
    let strike_kind = kind.parse::<Strike>()?;
    let strike_value = value
        .parse::<f64>()
        .map_err(|e| QSError::InvalidValueErr(format!("Bad strike in {id}: {e}")))?;
    match strike_kind {
        Strike::Absolute(_) => Ok(Strike::Absolute(strike_value)),
        Strike::Relative(_) => Ok(Strike::Relative(strike_value)),
        Strike::Atm => Err(QSError::InvalidValueErr(format!(
            "ATM strike in {id} must not have a strike value"
        ))),
    }
}

/// Quote level enumeration.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum Level {
    /// Mid (average between Bid and Ask) price.
    Mid,
    /// Bid (buy) price.
    Bid,
    /// Ask (sell) price.
    Ask,
}

/// Quote levels associated with an instrument identifier. When multiple levels are provided the `mid` is preferred, otherwise `bid/ask`
/// are used to compute a fallback representative value.
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
pub struct QuoteLevels {
    /// Mid price/level.
    #[serde(default)]
    mid: Option<f64>,
    /// Bid price/level.
    #[serde(default)]
    bid: Option<f64>,
    /// Ask price/level.
    #[serde(default)]
    ask: Option<f64>,
}

impl QuoteLevels {
    /// Creates quote levels from optional values.
    #[must_use]
    pub const fn new(mid: Option<f64>, bid: Option<f64>, ask: Option<f64>) -> Self {
        Self { mid, bid, ask }
    }

    /// Creates quote levels with only a mid value.
    #[must_use]
    pub const fn with_mid(mid: f64) -> Self {
        Self {
            mid: Some(mid),
            bid: None,
            ask: None,
        }
    }

    /// Returns the mid quote if available.
    #[must_use]
    pub const fn mid(&self) -> Option<f64> {
        self.mid
    }

    /// Returns the bid quote if available.
    #[must_use]
    pub const fn bid(&self) -> Option<f64> {
        self.bid
    }

    /// Returns the ask quote if available.
    #[must_use]
    pub const fn ask(&self) -> Option<f64> {
        self.ask
    }

    /// Resolves a representative quote value for the given [`Level`].
    ///
    /// ## Errors
    /// Returns an error if the requested level is not available.
    pub fn value(&self, level: Level) -> Result<f64> {
        match level {
            Level::Mid => self
                .mid
                .ok_or_else(|| QSError::NotFoundErr("No mid quote available".into())),
            Level::Bid => self
                .bid
                .ok_or_else(|| QSError::NotFoundErr("No bid quote available".into())),
            Level::Ask => self
                .ask
                .ok_or_else(|| QSError::NotFoundErr("No ask quote available".into())),
        }
    }
}

/// Represents the type of instruments that can be handled by the quoting system.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum QuoteInstrument {
    /// Deposit instrument.
    FixedRateDeposit,
    /// Basis swap instrument.
    BasisSwap,
    /// OIS swap instrument.
    OIS,
    /// Equity call option.
    EquityCall,
    /// Equity put option.
    EquityPut,
    /// FX call option.
    FxCall,
    /// FX put option.
    FxPut,
    /// Cross currency swap instrument (fixed vs floating).
    FixFloatCrossCurrencySwap,
    /// Float-float cross currency swap instrument (both legs floating).
    FloatFloatCrossCurrencySwap,
    /// FX forward points.
    FxForwardPoints,
    /// FX outright forward instrument.
    FxOutrightForward,
    /// Future instrument.
    Future,
    /// Convexity adjustment.
    ConvexityAdjustment,
    /// Caplet or floorlet instrument.
    CapletFloorlet,
    /// Swaption instrument.
    EuropeanSwaption,
    /// Cap/Floor (requires stripping).
    CapFloor,
    /// Credit default swap (par-spread quote).
    Cds,
}

/// Represents the strategy for which the volatility quotes.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum OptionStrategy {
    /// Straddle strategy.
    Straddle,
    /// Strangle strategy.
    Strangle,
    /// Risk reversal strategy.
    RiskReversal,
    /// Butterfly strategy.
    Butterfly,
}

impl std::str::FromStr for OptionStrategy {
    type Err = QSError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "Straddle" => Ok(Self::Straddle),
            "Strangle" => Ok(Self::Strangle),
            "RiskReversal" => Ok(Self::RiskReversal),
            "Butterfly" => Ok(Self::Butterfly),
            _ => Err(QSError::InvalidValueErr(format!(
                "Unknown option strategy: {s}"
            ))),
        }
    }
}

/// A [`QuoteDetails`] contains all details related to a particular quote.
///
/// Instances can be built manually via [`QuoteDetails::new`] + builder setters,
/// or parsed from an identifier string via the [`std::str::FromStr`] trait.
///
/// # Identifier format
///
/// Each identifier is an underscore-separated string whose first segment
/// determines the instrument type. The table below shows the positional
/// parameters for every supported product. Square brackets denote optional
/// segments.
///
/// | Product                      | Pos 0                       | Pos 1       | Pos 2         | Pos 3      | Pos 4          | Pos 5           | Pos 6            | Pos 7     | Pos 8 |
/// |-----------------------------|-----------------------------|-------------|---------------|------------|----------------|-----------------|------------------|----------|-------|
/// | `OIS`                       | `OIS`                       | CCY         | Index         | Tenor      | \[`PayFreq`\]  | \[`RecvFreq`\]  |                   |          |       |
/// | `FixedRateDeposit`          | `FixedRateDeposit`          | CCY         | Index         | Tenor      |                |                 |                   |          |       |
/// | `FixedRateBond`             | `FixedRateBond`             | CCY         | Index         | Tenor      | \[`PayFreq`\]  |                 |                   |          |       |
/// | `BasisSwap`                 | `BasisSwap`                 | CCY         | `PayIndex`    | `RecvIndex`| Tenor          | \[`PayFreq`\]   | \[`RecvFreq`\]    |          |       |
/// | `FixFloatCrossCurrencySwap` | `FixFloatCrossCurrencySwap` | `DomCCY`    | `FloatIndex`  | `ForCCY`   | Tenor          | \[`DomFreq`\]   | \[`ForFreq`\]     |          |       |
/// |`FloatFloatCrossCurrencySwap`|`FloatFloatCrossCurrencySwap`| `DomCCY`    | `DomIndex`    | `ForIndex` | `ForCCY`       | Tenor           | \[`DomFreq`\]     | \[`ForFreq`\] |       |
/// | `CapFloor`                  | `CapFloor`                  | CCY         | Index         | Tenor      | \[Freq\]       | Strike          | \[`StrikeValue`\] | `VolType` |       |
/// | `CapletFloorlet`            | `CapletFloorlet`            | CCY         | Index         | `IdxTenor` | Expiry         | Strike          | \[`StrikeValue`\] | Strategy  | `VolType` |
/// | `Future`                    | `Future`                    | CCY         | Index         | `IMMCode`  |                |                 |                   |          |       |
/// | `ConvexityAdjustment`       | `ConvexityAdjustment`       | CCY         | Index         | `IMMCode`  |                |                 |                   |          |       |
/// | `Swaption`                  | `Swaption`                  | CCY         | Index         | Expiry     | `SwapTenor`    | \[`PayFreq`\]   | \[`RecvFreq`\]    | Strike   | \[`StrikeValue`\] `VolType` |
/// | `FxOutrightForward`         | `FxOutrightForward`         | CCYPAIR     | Tenor         |            |                |                 |                   |          |       |
/// | `FxForwardPoints`           | `FxForwardPoints`           | CCYPAIR     | Tenor         |            |                |                 |                   |          |       |
/// | `EquityCall`                | `EquityCall`                | CCY         | Index         | Tenor      | Strike kind    | Strike          |                   |          |       |
/// | `EquityPut`                 | `EquityPut`                 | CCY         | Index         | Tenor      | Strike kind    | Strike          |                   |          |       |
/// | `FxCall`                    | `FxCall`                    | CCYPAIR     | Tenor         | Strike kind| Strike         |                 |                   |          |       |
/// | `FxPut`                     | `FxPut`                     | CCYPAIR     | Tenor         | Strike kind| Strike         |                 |                   |          |       |
///
/// **Frequency values**: `Annual`, `Semiannual`, `Quarterly`, `Monthly`,
/// `Bimonthly`, `Biweekly`, `Weekly`, `Daily`, `EveryFourthMonth`,
/// `EveryFourthWeek`, `Once`, `NoFrequency`.
///
/// # Examples
///
/// ```text
/// OIS_USD_SOFR_1Y
/// OIS_USD_SOFR_1Y_Semiannual_Semiannual
/// BasisSwap_USD_SOFR_TermSOFR3m_1Y_Quarterly_Quarterly
/// FixFloatCrossCurrencySwap_USD_ICP_CLP_1Y_Semiannual_Quarterly
/// Swaption_USD_SOFR_3M_2Y_Semiannual_Semiannual_Absolute_0.04_Black
/// CapFloor_USD_SOFR_1Y_Quarterly_Absolute_0.03_Black
/// EquityCall_USD_SPX_1Y_Absolute_5000
/// FxCall_EURUSD_1Y_Absolute_1.10
/// ```
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct QuoteDetails {
    identifier: String,
    instrument: QuoteInstrument,
    #[serde(default)]
    market_index: Option<MarketIndex>,
    #[serde(default)]
    strategy: Option<OptionStrategy>,
    #[serde(default)]
    vol_type: Option<VolatilityType>,
    #[serde(default)]
    rate: Option<f64>,
    #[serde(default)]
    price: Option<f64>,
    #[serde(default)]
    coupon_rate: Option<f64>,
    #[serde(default)]
    pay_currency: Option<Currency>,
    #[serde(default)]
    receive_currency: Option<Currency>,
    #[serde(default)]
    strike: Option<Strike>,
    #[serde(default)]
    maturity: Option<Date>,
    #[serde(default)]
    tenor: Option<Period>,
    #[serde(default)]
    vol_shift: Option<f64>,
    /// Primary instrument currency.
    #[serde(default)]
    currency: Option<Currency>,
    /// Secondary market index (e.g. receive-leg index on a basis swap).
    #[serde(default)]
    secondary_market_index: Option<MarketIndex>,
    /// Option expiry tenor (swaptions, caplets).
    #[serde(default)]
    option_expiry: Option<Period>,
    /// Futures / convexity-adjustment IMM contract code (e.g. "H6").
    #[serde(default)]
    contract_code: Option<String>,
    /// Underlying index tenor (caplet/floorlet frequency).
    #[serde(default)]
    index_tenor: Option<Period>,
    /// Pay (or fixed / domestic) leg frequency.
    #[serde(default)]
    pay_leg_frequency: Option<Frequency>,
    /// Receive (or floating / foreign) leg frequency.
    #[serde(default)]
    receive_leg_frequency: Option<Frequency>,
}

impl QuoteDetails {
    /// Creates a new quote details container with required fields.
    #[must_use]
    pub const fn new(identifier: String, instrument: QuoteInstrument) -> Self {
        Self {
            identifier,
            instrument,
            market_index: None,
            strategy: None,
            vol_type: None,
            rate: None,
            price: None,
            coupon_rate: None,
            pay_currency: None,
            receive_currency: None,
            strike: None,
            maturity: None,
            tenor: None,
            vol_shift: None,
            currency: None,
            secondary_market_index: None,
            option_expiry: None,
            contract_code: None,
            index_tenor: None,
            pay_leg_frequency: None,
            receive_leg_frequency: None,
        }
    }

    // -----------------------------------------------------------------------
    // Getters
    // -----------------------------------------------------------------------

    /// Returns the quote identifier.
    #[must_use]
    pub fn identifier(&self) -> String {
        self.identifier.clone()
    }

    /// Returns the primary market index.
    #[must_use]
    pub const fn market_index(&self) -> Option<&MarketIndex> {
        self.market_index.as_ref()
    }

    /// Returns the instrument type.
    #[must_use]
    pub const fn instrument(&self) -> &QuoteInstrument {
        &self.instrument
    }

    /// Returns the option strategy, if present.
    #[must_use]
    pub const fn strategy(&self) -> Option<OptionStrategy> {
        self.strategy
    }

    /// Returns the volatility type, if present.
    #[must_use]
    pub const fn vol_type(&self) -> Option<&VolatilityType> {
        self.vol_type.as_ref()
    }

    /// Returns the rate, if present.
    #[must_use]
    pub const fn rate(&self) -> Option<f64> {
        self.rate
    }

    /// Returns the price, if present.
    #[must_use]
    pub const fn price(&self) -> Option<f64> {
        self.price
    }

    /// Returns the coupon rate, if present.
    #[must_use]
    pub const fn coupon_rate(&self) -> Option<f64> {
        self.coupon_rate
    }

    /// Returns the pay / base currency, if present.
    #[must_use]
    pub const fn pay_currency(&self) -> Option<Currency> {
        self.pay_currency
    }

    /// Returns the receive / quote currency, if present.
    #[must_use]
    pub const fn receive_currency(&self) -> Option<Currency> {
        self.receive_currency
    }

    /// Returns the strike, if present.
    #[must_use]
    pub const fn strike(&self) -> Option<Strike> {
        self.strike
    }

    /// Returns the vol shift, if present.
    #[must_use]
    pub const fn shift(&self) -> Option<f64> {
        self.vol_shift
    }

    /// Returns the maturity, if present.
    #[must_use]
    pub const fn maturity(&self) -> Option<Date> {
        self.maturity
    }

    /// Returns the tenor, if present.
    #[must_use]
    pub const fn tenor(&self) -> Option<Period> {
        self.tenor
    }

    /// Returns the primary instrument currency, if present.
    #[must_use]
    pub const fn currency(&self) -> Option<Currency> {
        self.currency
    }

    /// Returns the secondary market index (e.g. receive-leg index on a basis swap).
    #[must_use]
    pub const fn secondary_market_index(&self) -> Option<&MarketIndex> {
        self.secondary_market_index.as_ref()
    }

    /// Returns the option expiry tenor, if present.
    #[must_use]
    pub const fn option_expiry(&self) -> Option<Period> {
        self.option_expiry
    }

    /// Returns the futures contract code (IMM code), if present.
    #[must_use]
    pub fn contract_code(&self) -> Option<&str> {
        self.contract_code.as_deref()
    }

    /// Returns the underlying index tenor, if present.
    #[must_use]
    pub const fn index_tenor(&self) -> Option<Period> {
        self.index_tenor
    }

    /// Returns the pay (or fixed / domestic) leg frequency, if present.
    #[must_use]
    pub const fn pay_leg_frequency(&self) -> Option<Frequency> {
        self.pay_leg_frequency
    }

    /// Returns the receive (or floating / foreign) leg frequency, if present.
    #[must_use]
    pub const fn receive_leg_frequency(&self) -> Option<Frequency> {
        self.receive_leg_frequency
    }

    // -----------------------------------------------------------------------
    // Builder setters
    // -----------------------------------------------------------------------

    /// Sets the option strategy.
    #[must_use]
    pub const fn with_strategy(mut self, s: OptionStrategy) -> Self {
        self.strategy = Some(s);
        self
    }
    /// Sets the volatility type.
    #[must_use]
    pub const fn with_vol_type(mut self, v: VolatilityType) -> Self {
        self.vol_type = Some(v);
        self
    }
    /// Sets the rate.
    #[must_use]
    pub const fn with_rate(mut self, r: f64) -> Self {
        self.rate = Some(r);
        self
    }
    /// Sets the price.
    #[must_use]
    pub const fn with_price(mut self, p: f64) -> Self {
        self.price = Some(p);
        self
    }
    /// Sets the coupon rate.
    #[must_use]
    pub const fn with_coupon_rate(mut self, r: f64) -> Self {
        self.coupon_rate = Some(r);
        self
    }
    /// Sets the pay / base currency.
    #[must_use]
    pub const fn with_pay_currency(mut self, c: Currency) -> Self {
        self.pay_currency = Some(c);
        self
    }
    /// Sets the receive / quote currency.
    #[must_use]
    pub const fn with_receive_currency(mut self, c: Currency) -> Self {
        self.receive_currency = Some(c);
        self
    }
    /// Sets the strike.
    #[must_use]
    pub const fn with_strike(mut self, s: Strike) -> Self {
        self.strike = Some(s);
        self
    }

    /// Sets the maturity.
    #[must_use]
    pub const fn with_maturity(mut self, d: Date) -> Self {
        self.maturity = Some(d);
        self
    }
    /// Sets the tenor.
    #[must_use]
    pub const fn with_tenor(mut self, p: Period) -> Self {
        self.tenor = Some(p);
        self
    }
    /// Sets the vol shift.
    #[must_use]
    pub const fn with_vol_shift(mut self, s: f64) -> Self {
        self.vol_shift = Some(s);
        self
    }
    /// Sets the primary instrument currency.
    #[must_use]
    pub const fn with_currency(mut self, c: Currency) -> Self {
        self.currency = Some(c);
        self
    }
    /// Sets the secondary market index.
    #[must_use]
    pub fn with_secondary_market_index(mut self, idx: MarketIndex) -> Self {
        self.secondary_market_index = Some(idx);
        self
    }
    /// Sets the option expiry tenor.
    #[must_use]
    pub const fn with_option_expiry(mut self, p: Period) -> Self {
        self.option_expiry = Some(p);
        self
    }
    /// Sets the futures contract code.
    #[must_use]
    pub fn with_contract_code(mut self, code: String) -> Self {
        self.contract_code = Some(code);
        self
    }
    /// Sets the underlying index tenor.
    #[must_use]
    pub const fn with_index_tenor(mut self, p: Period) -> Self {
        self.index_tenor = Some(p);
        self
    }

    /// Sets the pay (or fixed / domestic) leg frequency.
    #[must_use]
    pub const fn with_pay_leg_frequency(mut self, f: Frequency) -> Self {
        self.pay_leg_frequency = Some(f);
        self
    }

    /// Sets the receive (or floating / foreign) leg frequency.
    #[must_use]
    pub const fn with_receive_leg_frequency(mut self, f: Frequency) -> Self {
        self.receive_leg_frequency = Some(f);
        self
    }

    /// Sets the primary market index.
    #[must_use]
    pub fn with_market_index(mut self, idx: MarketIndex) -> Self {
        self.market_index = Some(idx);
        self
    }

    // -----------------------------------------------------------------------
    // Identifier parsing helpers
    // -----------------------------------------------------------------------

    /// Tries to parse one or two optional [`Frequency`] values starting at
    /// `parts[start]`.
    ///
    /// Returns `(pay_freq, recv_freq, next_index)` where `next_index` is the
    /// position of the first part that was *not* consumed as a frequency.
    fn try_parse_frequencies(
        parts: &[&str],
        start: usize,
    ) -> (Option<Frequency>, Option<Frequency>, usize) {
        let pay: Option<Frequency> = parts.get(start).and_then(|s| s.parse().ok());
        pay.map_or((None, None, start), |p| {
            let recv: Option<Frequency> = parts.get(start + 1).and_then(|s| s.parse().ok());
            recv.map_or_else(
                || (Some(p), None, start + 1),
                |r| (Some(p), Some(r), start + 2),
            )
        })
    }

    /// `{Instrument}_CCY_{Index}_{Tenor}[_{PayFreq}[_{RecvFreq}]]`
    /// e.g. `OIS_USD_SOFR_1Y` or `OIS_USD_SOFR_1Y_Semiannual_Semiannual`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_ois(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 4 {
            return Err(QSError::InvalidValueErr(format!(
                "OIS identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let index = parts[2].parse::<MarketIndex>()?;
        let tenor = Period::from_str(parts[3])?;

        let (pay_freq, recv_freq, _) = Self::try_parse_frequencies(parts, 4);

        let mut det = Self::new(id.to_string(), QuoteInstrument::OIS)
            .with_market_index(index)
            .with_currency(currency)
            .with_tenor(tenor);
        if let Some(f) = pay_freq {
            det = det.with_pay_leg_frequency(f);
        }
        if let Some(f) = recv_freq {
            det = det.with_receive_leg_frequency(f);
        }
        Ok(det)
    }

    /// `{Instrument}_CCY_{Index}_{Tenor}` — e.g. `FixedRateDeposit_USD_SOFR_1Y`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_fixed_rate_deposit(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 4 {
            return Err(QSError::InvalidValueErr(format!(
                "FixedRateDeposit identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let index = parts[2].parse::<MarketIndex>()?;
        let tenor = Period::from_str(parts[3])?;
        Ok(Self::new(id.to_string(), QuoteInstrument::FixedRateDeposit)
            .with_market_index(index)
            .with_currency(currency)
            .with_tenor(tenor))
    }

    /// `{Instrument}_{Entity}_{CCY}_{Tenor}` — e.g. `Cds_ACME_USD_5Y`
    ///
    /// The quote level is the CDS par spread (decimal, e.g. `0.0125`).
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_cds(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 4 {
            return Err(QSError::InvalidValueErr(format!(
                "Cds identifier too short: {id}"
            )));
        }
        let entity = parts[1].to_string();
        let currency: Currency = parts[2].parse()?;
        let tenor = Period::from_str(parts[3])?;
        Ok(Self::new(id.to_string(), QuoteInstrument::Cds)
            .with_market_index(MarketIndex::Credit(entity))
            .with_currency(currency)
            .with_tenor(tenor))
    }

    /// `{Instrument}_CCY_{PayIndex}_{RecvIndex}_{Tenor}[_{PayFreq}_{RecvFreq}]`
    /// e.g. `BasisSwap_USD_SOFR_TermSOFR3m_1Y` or
    /// `BasisSwap_USD_SOFR_TermSOFR3m_1Y_Quarterly_Quarterly`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_basis_swap(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 5 {
            return Err(QSError::InvalidValueErr(format!(
                "BasisSwap identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let pay_index = parts[2].parse::<MarketIndex>()?;
        let recv_index = parts[3].parse::<MarketIndex>()?;
        let tenor = Period::from_str(parts[4])?;

        let (pay_freq, recv_freq, _) = Self::try_parse_frequencies(parts, 5);

        let mut det = Self::new(id.to_string(), QuoteInstrument::BasisSwap)
            .with_market_index(pay_index)
            .with_currency(currency)
            .with_secondary_market_index(recv_index)
            .with_tenor(tenor);
        if let Some(f) = pay_freq {
            det = det.with_pay_leg_frequency(f);
        }
        if let Some(f) = recv_freq {
            det = det.with_receive_leg_frequency(f);
        }
        Ok(det)
    }

    /// `{Instrument}_DomesticCCY_{FloatingIndex}_{ForeignCCY}_{Tenor}[_{DomFreq}_{ForFreq}]`
    /// e.g. `FixFloatCrossCurrencySwap_USD_ICP_CLP_1Y` or
    /// `FixFloatCrossCurrencySwap_USD_ICP_CLP_1Y_Semiannual_Quarterly`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_fix_float_cross_currency_swap(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 5 {
            return Err(QSError::InvalidValueErr(format!(
                "FixFloatCrossCurrencySwap identifier too short: {id}"
            )));
        }
        let domestic_currency: Currency = parts[1].parse()?;
        let floating_index = parts[2].parse::<MarketIndex>()?;
        let foreign_currency: Currency = parts[3].parse()?;
        let tenor = Period::from_str(parts[4])?;

        let (dom_freq, for_freq, _) = Self::try_parse_frequencies(parts, 5);

        let mut det = Self::new(id.to_string(), QuoteInstrument::FixFloatCrossCurrencySwap)
            .with_market_index(floating_index)
            .with_currency(domestic_currency)
            .with_pay_currency(domestic_currency)
            .with_receive_currency(foreign_currency)
            .with_tenor(tenor);
        if let Some(f) = dom_freq {
            det = det.with_pay_leg_frequency(f);
        }
        if let Some(f) = for_freq {
            det = det.with_receive_leg_frequency(f);
        }
        Ok(det)
    }

    /// `{Instrument}_{DomCCY}_{DomIndex}_{ForIndex}_{ForCCY}_{Tenor}[_{DomFreq}_{ForFreq}]`
    /// e.g. `FloatFloatCrossCurrencySwap_CLP_ICP_SOFR_USD_1Y` or
    /// `FloatFloatCrossCurrencySwap_CLP_ICP_SOFR_USD_1Y_Quarterly_Quarterly`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_float_float_cross_currency_swap(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 6 {
            return Err(QSError::InvalidValueErr(format!(
                "FloatFloatCrossCurrencySwap identifier too short: {id}"
            )));
        }
        let domestic_currency: Currency = parts[1].parse()?;
        let dom_index = parts[2].parse::<MarketIndex>()?;
        let for_index = parts[3].parse::<MarketIndex>()?;
        let foreign_currency: Currency = parts[4].parse()?;
        let tenor = Period::from_str(parts[5])?;

        let (dom_freq, for_freq, _) = Self::try_parse_frequencies(parts, 6);

        let mut det = Self::new(id.to_string(), QuoteInstrument::FloatFloatCrossCurrencySwap)
            .with_market_index(dom_index)
            .with_currency(domestic_currency)
            .with_pay_currency(domestic_currency)
            .with_receive_currency(foreign_currency)
            .with_secondary_market_index(for_index)
            .with_tenor(tenor);
        if let Some(f) = dom_freq {
            det = det.with_pay_leg_frequency(f);
        }
        if let Some(f) = for_freq {
            det = det.with_receive_leg_frequency(f);
        }
        Ok(det)
    }

    /// `{Instrument}_CCY_{Index}_{Tenor}[_{Freq}]_{Strike}_{VolType}` (without strike value)
    ///
    /// `{Instrument}_CCY_{Index}_{Tenor}[_{Freq}]_{Strike}_{StrikeValue}_{VolType}` (with strike value)
    ///
    /// e.g. `CapFloor_USD_SOFR_1Y_Absolute_Black` or
    /// `CapFloor_USD_SOFR_1Y_Quarterly_Absolute_Black`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_cap_floor(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 6 {
            return Err(QSError::InvalidValueErr(format!(
                "CapFloor identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let index = parts[2].parse::<MarketIndex>()?;
        let tenor = Period::from_str(parts[3])?;

        // Try optional frequency after tenor
        let (freq, next) = parts
            .get(4)
            .and_then(|s| s.parse::<Frequency>().ok())
            .map_or((None, 4), |f| (Some(f), 5));

        let strike_base = parts[next].parse::<Strike>()?;

        // Try parsing next+1 as f64 (strike value). If it succeeds, the vol
        // type follows at next+2; otherwise next+1 is the vol type.
        let strike_idx = next + 1;
        let (strike, vol_idx) = parts
            .get(strike_idx)
            .and_then(|s| s.parse::<f64>().ok())
            .map_or((strike_base, strike_idx), |s| {
                let st = match strike_base {
                    Strike::Absolute(_) => Strike::Absolute(s),
                    Strike::Relative(_) => Strike::Relative(s),
                    Strike::Atm => Strike::Atm,
                };
                (st, strike_idx + 1)
            });
        let vol_type: VolatilityType = parts
            .get(vol_idx)
            .ok_or_else(|| QSError::InvalidValueErr(format!("Missing vol type in: {id}")))?
            .parse()?;

        let mut det = Self::new(id.to_string(), QuoteInstrument::CapFloor)
            .with_market_index(index)
            .with_currency(currency)
            .with_tenor(tenor)
            .with_strike(strike)
            .with_vol_type(vol_type);
        if let Some(f) = freq {
            det = det.with_pay_leg_frequency(f);
        }
        Ok(det)
    }

    /// `{Instrument}_CCY_{Index}_{IdxTenor}_{Expiry}_{Strike}_{StrikeValue}_{Strategy}_{VolType}`
    ///
    /// Or without explicit strike value: `.._{Strike}_{Strategy}_{VolType}`.
    ///
    /// e.g. `CapletFloorlet_USD_TermSOFR3m_3M_3M_Absolute_0.010_Straddle_Black`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_caplet_floorlet(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 8 {
            return Err(QSError::InvalidValueErr(format!(
                "CapletFloorlet identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let index = parts[2].parse::<MarketIndex>()?;
        let index_tenor = Period::from_str(parts[3])?;
        let option_expiry = Period::from_str(parts[4])?;
        let strike_base = parts[5].parse::<Strike>()?;

        let (strike, next_idx) = parts[6].parse::<f64>().map_or((strike_base, 6), |s| {
            let st = match strike_base {
                Strike::Absolute(_) => Strike::Absolute(s),
                Strike::Relative(_) => Strike::Relative(s),
                Strike::Atm => Strike::Atm,
            };
            (st, 7)
        });

        let strategy: OptionStrategy = parts
            .get(next_idx)
            .ok_or_else(|| QSError::InvalidValueErr(format!("Missing strategy in: {id}")))?
            .parse()?;
        let vol_type: VolatilityType = parts
            .get(next_idx + 1)
            .ok_or_else(|| QSError::InvalidValueErr(format!("Missing vol type in: {id}")))?
            .parse()?;

        let det = Self::new(id.to_string(), QuoteInstrument::CapletFloorlet)
            .with_market_index(index)
            .with_currency(currency)
            .with_index_tenor(index_tenor)
            .with_option_expiry(option_expiry)
            .with_strike(strike)
            .with_strategy(strategy)
            .with_vol_type(vol_type);
        Ok(det)
    }

    /// `{Instrument}_CCY_{Index}_{IMMCode}` — e.g. `Future_USD_SOFR_H6`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_future(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 4 {
            return Err(QSError::InvalidValueErr(format!(
                "Future identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let index = parts[2].parse::<MarketIndex>()?;
        let code = parts[3].to_string();
        Ok(Self::new(id.to_string(), QuoteInstrument::Future)
            .with_market_index(index)
            .with_currency(currency)
            .with_contract_code(code))
    }

    /// `{Instrument}_CCY_{Index}_{IMMCode}` — e.g. `ConvexityAdjustment_USD_SOFR_H6`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_convexity_adjustment(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 4 {
            return Err(QSError::InvalidValueErr(format!(
                "ConvexityAdjustment identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let index = parts[2].parse::<MarketIndex>()?;
        let code = parts[3].to_string();
        Ok(
            Self::new(id.to_string(), QuoteInstrument::ConvexityAdjustment)
                .with_market_index(index)
                .with_currency(currency)
                .with_contract_code(code),
        )
    }

    /// Swaption identifier parser.
    ///
    /// `{Instrument}_CCY_{Index}_{Expiry}_{SwapTenor}[_{PayFreq}_{RecvFreq}]_{Strike}_{VolType}` (no strike value)
    /// `{Instrument}_CCY_{Index}_{Expiry}_{SwapTenor}[_{PayFreq}_{RecvFreq}]_{Strike}_{StrikeValue}_{VolType}` (with strike value)
    /// e.g. `Swaption_USD_SOFR_3M_2Y_Absolute_Black` or
    /// `Swaption_USD_SOFR_3M_2Y_Semiannual_Semiannual_Absolute_Black`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_swaption(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 7 {
            return Err(QSError::InvalidValueErr(format!(
                "Swaption identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let index = parts[2].parse::<MarketIndex>()?;
        let option_expiry = Period::from_str(parts[3])?;
        let swap_tenor = Period::from_str(parts[4])?;

        let (pay_freq, recv_freq, next) = Self::try_parse_frequencies(parts, 5);

        let strike_base = parts[next].parse::<Strike>()?;

        let strike_idx = next + 1;
        let (strike, vol_idx) = parts
            .get(strike_idx)
            .and_then(|s| s.parse::<f64>().ok())
            .map_or((strike_base, strike_idx), |s| {
                let st = match strike_base {
                    Strike::Absolute(_) => Strike::Absolute(s),
                    Strike::Relative(_) => Strike::Relative(s),
                    Strike::Atm => Strike::Atm,
                };
                (st, strike_idx + 1)
            });
        let vol_type: VolatilityType = parts
            .get(vol_idx)
            .ok_or_else(|| QSError::InvalidValueErr(format!("Missing vol type in: {id}")))?
            .parse()?;

        let mut det = Self::new(id.to_string(), QuoteInstrument::EuropeanSwaption)
            .with_market_index(index)
            .with_currency(currency)
            .with_option_expiry(option_expiry)
            .with_tenor(swap_tenor)
            .with_strike(strike)
            .with_vol_type(vol_type);
        if let Some(f) = pay_freq {
            det = det.with_pay_leg_frequency(f);
        }
        if let Some(f) = recv_freq {
            det = det.with_receive_leg_frequency(f);
        }
        Ok(det)
    }

    /// `{Instrument}_{CCYPAIR}_{Tenor}` — e.g. `FxOutrightForward_EURUSD_1M`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_outright_forward(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 3 {
            return Err(QSError::InvalidValueErr(format!(
                "OutrightForward identifier too short: {id}"
            )));
        }
        let (base, quote_ccy) = parse_fx_pair(parts[1])?;
        let tenor = Period::from_str(parts[2])?;
        Ok(
            Self::new(id.to_string(), QuoteInstrument::FxOutrightForward)
                .with_pay_currency(base)
                .with_receive_currency(quote_ccy)
                .with_tenor(tenor),
        )
    }

    /// `{Instrument}_{CCYPAIR}_{Tenor}` — e.g. `FxForwardPoints_EURUSD_1M`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_forward_points(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 3 {
            return Err(QSError::InvalidValueErr(format!(
                "ForwardPoints identifier too short: {id}"
            )));
        }
        let (base, quote_ccy) = parse_fx_pair(parts[1])?;
        let tenor = Period::from_str(parts[2])?;
        Ok(Self::new(id.to_string(), QuoteInstrument::FxForwardPoints)
            .with_pay_currency(base)
            .with_receive_currency(quote_ccy)
            .with_tenor(tenor))
    }

    /// `{Instrument}_CCY_{Index}_{Expiry}_{StrikeKind}_{Strike}` — e.g. `EquityCall_USD_SPX_1Y_Absolute_5000`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_equity_call(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 6 {
            return Err(QSError::InvalidValueErr(format!(
                "Call identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let index = parts[2].parse::<MarketIndex>()?;
        let tenor = Period::from_str(parts[3])?;
        let strike = parse_strike(id, parts[4], parts[5])?;
        Ok(Self::new(id.to_string(), QuoteInstrument::EquityCall)
            .with_market_index(index)
            .with_currency(currency)
            .with_tenor(tenor)
            .with_strike(strike))
    }

    /// `{Instrument}_CCY_{Index}_{Expiry}_{StrikeKind}_{Strike}` — e.g. `EquityPut_USD_SPX_1Y_Absolute_5000`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_equity_put(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 6 {
            return Err(QSError::InvalidValueErr(format!(
                "Put identifier too short: {id}"
            )));
        }
        let currency: Currency = parts[1].parse()?;
        let index = parts[2].parse::<MarketIndex>()?;
        let tenor = Period::from_str(parts[3])?;
        let strike = parse_strike(id, parts[4], parts[5])?;
        Ok(Self::new(id.to_string(), QuoteInstrument::EquityPut)
            .with_market_index(index)
            .with_currency(currency)
            .with_tenor(tenor)
            .with_strike(strike))
    }

    /// `{Instrument}_{CCYPAIR}_{Expiry}_{StrikeKind}_{Strike}` — e.g. `FxCall_EURUSD_1Y_Absolute_1.10`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_fx_call(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 5 {
            return Err(QSError::InvalidValueErr(format!(
                "FxCall identifier too short: {id}"
            )));
        }
        let (base, quote_ccy) = parse_fx_pair(parts[1])?;
        let tenor = Period::from_str(parts[2])?;
        let strike = parse_strike(id, parts[3], parts[4])?;

        Ok(Self::new(id.to_string(), QuoteInstrument::FxCall)
            .with_pay_currency(base)
            .with_receive_currency(quote_ccy)
            .with_tenor(tenor)
            .with_strike(strike))
    }

    /// `{Instrument}_{CCYPAIR}_{Expiry}_{StrikeKind}_{Strike}` — e.g. `FxPut_EURUSD_1Y_Absolute_1.10`
    ///
    /// # Errors
    /// Returns an error if the identifier is too short or fields cannot be parsed.
    pub fn parse_fx_put(id: &str, parts: &[&str]) -> Result<Self> {
        if parts.len() < 5 {
            return Err(QSError::InvalidValueErr(format!(
                "FxPut identifier too short: {id}"
            )));
        }
        let (base, quote_ccy) = parse_fx_pair(parts[1])?;
        let tenor = Period::from_str(parts[2])?;
        let strike = parse_strike(id, parts[3], parts[4])?;

        Ok(Self::new(id.to_string(), QuoteInstrument::FxPut)
            .with_pay_currency(base)
            .with_receive_currency(quote_ccy)
            .with_tenor(tenor)
            .with_strike(strike))
    }

    /// Parses a quote identifier using a custom separator.
    ///
    /// ## Errors
    /// Returns an error if the identifier cannot be parsed with the given separator.
    pub fn parse(s: &str, separator: char) -> Result<Self> {
        let parts: Vec<&str> = s.split(separator).collect();
        if parts.len() < 3 {
            return Err(QSError::InvalidValueErr(format!(
                "Identifier has fewer than 3 parts: {s}"
            )));
        }
        // Previous accepted identifiers:
        // "FxForwardOutright" | "ForwardOutright"
        // Added "FxOutrightForward" to support existing test identifiers
        // and maintain backward compatibility.

        match parts[0] {
            "OIS" => Self::parse_ois(s, &parts),
            "FixedRateDeposit" => Self::parse_fixed_rate_deposit(s, &parts),
            "BasisSwap" => Self::parse_basis_swap(s, &parts),
            "FixFloatCrossCurrencySwap" => Self::parse_fix_float_cross_currency_swap(s, &parts),
            "CapFloor" => Self::parse_cap_floor(s, &parts),
            "CapletFloorlet" => Self::parse_caplet_floorlet(s, &parts),
            "Future" => Self::parse_future(s, &parts),
            "ConvexityAdjustment" => Self::parse_convexity_adjustment(s, &parts),
            "Swaption" => Self::parse_swaption(s, &parts),
            "FxForwardOutright" | "FxOutrightForward" | "ForwardOutright" => {
                Self::parse_outright_forward(s, &parts)
            }
            "FloatFloatCrossCurrencySwap" => Self::parse_float_float_cross_currency_swap(s, &parts),
            "FxForwardPoints" => Self::parse_forward_points(s, &parts),
            "EquityCall" => Self::parse_equity_call(s, &parts),
            "EquityPut" => Self::parse_equity_put(s, &parts),
            "FxCall" => Self::parse_fx_call(s, &parts),
            "FxPut" => Self::parse_fx_put(s, &parts),
            "Cds" => Self::parse_cds(s, &parts),
            other => Err(QSError::InvalidValueErr(format!(
                "Unknown instrument type in identifier: {other}"
            ))),
        }
    }
}

impl std::str::FromStr for QuoteDetails {
    type Err = QSError;

    /// Parses a quote identifier string (underscore-separated) into [`QuoteDetails`].
    ///
    /// The first `_`-delimited segment determines the instrument type and must
    /// match the exact [`QuoteInstrument`] variant name (e.g.
    /// [`FxOutrightForward`]/[`FxForwardPoints`]).
    ///
    /// # Errors
    /// Returns an error if the identifier cannot be parsed.
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Self::parse(s, '_')
    }
}

/// Wraps every concrete instrument type that can be produced from a [`Quote`].
#[derive(Clone)]
pub enum CalibrationInstrumentType<T = f64>
where
    T: Scalar,
{
    /// A vanilla fixed-rate deposit.
    FixedRateDeposit(FixedRateDeposit<T>),
    /// A fixed-vs-floating interest rate swap (e.g. OIS).
    Swap(Swap<T>),
    /// A floating-vs-floating basis swap.
    BasisSwap(BasisSwap<T>),
    /// A rate futures contract.
    RateFutures(RateFutures),
    /// An FX outright forward.
    FxForward(FxForward),
    /// A cross-currency swap (fixed domestic vs floating foreign).
    FixFloatCrossCurrencySwap(FixFloatCrossCurrencySwap<T>),
    /// A float-float cross-currency swap (both legs floating).
    FloatFloatCrossCurrencySwap(FloatFloatCrossCurrencySwap<T>),
    /// A European equity call option.
    EquityCall(EquityEuropeanOption),
    /// A European equity put option.
    EquityPut(EquityEuropeanOption),
    /// A European FX call option.
    FxCall(FxEuropeanOption),
    /// A European FX put option.
    FxPut(FxEuropeanOption),
    /// An interest rate cap or floor.
    CapFloor(CapFloor),
    /// A single caplet or floorlet.
    CapletFloorlet(CapletFloorlet),
    /// A European swaption (option on a swap).
    EuropeanSwaption(EuropeanSwaption<T>),
}

impl<T: Scalar> std::fmt::Debug for CalibrationInstrumentType<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::FixedRateDeposit(_) => write!(f, "CalibrationInstrumentType::FixedRateDeposit"),
            Self::Swap(_) => write!(f, "CalibrationInstrumentType::Swap"),
            Self::BasisSwap(_) => write!(f, "CalibrationInstrumentType::BasisSwap"),
            Self::RateFutures(_) => write!(f, "CalibrationInstrumentType::RateFutures"),
            Self::FxForward(_) => write!(f, "CalibrationInstrumentType::FxForward"),
            Self::FixFloatCrossCurrencySwap(_) => {
                write!(f, "CalibrationInstrumentType::FixFloatCrossCurrencySwap")
            }
            Self::FloatFloatCrossCurrencySwap(_) => {
                write!(f, "CalibrationInstrumentType::FloatFloatCrossCurrencySwap")
            }
            Self::EquityCall(_) => write!(f, "CalibrationInstrumentType::EquityCall"),
            Self::EquityPut(_) => write!(f, "CalibrationInstrumentType::EquityPut"),
            Self::FxCall(_) => write!(f, "CalibrationInstrumentType::FxCall"),
            Self::FxPut(_) => write!(f, "CalibrationInstrumentType::FxPut"),
            Self::CapFloor(_) => write!(f, "CalibrationInstrumentType::CapFloor"),
            Self::CapletFloorlet(_) => write!(f, "CalibrationInstrumentType::CapletFloorlet"),
            Self::EuropeanSwaption(_) => write!(f, "CalibrationInstrumentType::EuropeanSwaption"),
        }
    }
}

impl<T> CalibrationInstrumentType<T>
where
    T: Scalar,
{
    /// Returns the final date that defines the calibration pillar for the instrument.
    ///
    /// # Errors
    /// Returns an error if the instrument type is not supported or if underlying instrument data is invalid.
    pub fn pillar_date(&self) -> Result<Date> {
        match self {
            Self::FixedRateDeposit(x) => Ok(x.leg().last_payment_date()),
            Self::Swap(x) => Ok(x
                .fixed_leg()
                .last_payment_date()
                .max(x.floating_leg().last_payment_date())),
            Self::BasisSwap(x) => Ok(x
                .pay_leg()
                .last_payment_date()
                .max(x.receive_leg().last_payment_date())),
            Self::FixFloatCrossCurrencySwap(x) => Ok(x
                .domestic_leg()
                .last_payment_date()
                .max(x.foreign_leg().last_payment_date())),
            Self::FloatFloatCrossCurrencySwap(x) => Ok(x
                .domestic_leg()
                .last_payment_date()
                .max(x.foreign_leg().last_payment_date())),
            Self::RateFutures(x) => Ok(x.end_date()),
            Self::FxForward(x) => Ok(x.delivery_date()),
            Self::EquityCall(x) | Self::EquityPut(x) => Ok(x.expiry_date()),
            Self::FxCall(x) | Self::FxPut(x) => Ok(x.expiry_date()),
            Self::CapletFloorlet(x) => Ok(x.fixing_date()),
            Self::CapFloor(x) => x.last_fixing_date().ok_or_else(|| {
                crate::utils::errors::QSError::ValueNotSetErr(
                    "cap/floor has no caplet/floorlets".into(),
                )
            }),
            Self::EuropeanSwaption(x) => Ok(x.expiry_date()),
        }
    }
}

/// Contains the quote information.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Quote {
    details: QuoteDetails,
    levels: QuoteLevels,
}

impl Quote {
    /// Creates a new quote.
    #[must_use]
    pub const fn new(details: QuoteDetails, levels: QuoteLevels) -> Self {
        Self { details, levels }
    }

    /// Returns the quote details.
    #[must_use]
    pub const fn details(&self) -> &QuoteDetails {
        &self.details
    }

    /// Returns the quote levels.
    #[must_use]
    pub const fn levels(&self) -> &QuoteLevels {
        &self.levels
    }

    /// Builds a concrete financial instrument from this quote.
    ///
    /// # Arguments
    /// * `reference_date` – the as-of / valuation date. Tenors are rolled
    ///   from this date to determine maturity / delivery.
    /// * `level` – which price level to extract (`Mid`, `Bid`, `Ask`).
    /// * `fx_spot` – optional FX spot rate for cross-currency instruments.
    ///   When provided, the domestic notional is set to
    ///   `fx_spot × foreign_notional` so that notional exchanges are
    ///   balanced at inception.
    ///
    /// # Errors
    /// Returns an error when:
    /// * the quote level is unavailable,
    /// * required detail fields are missing,
    /// * the instrument type is not directly buildable (e.g. vol-only quotes), or
    /// * the underlying maker returns an error.
    pub fn build_instrument(
        &self,
        reference_date: Date,
        level: Level,
        fx_spot: Option<f64>,
    ) -> Result<CalibrationInstrumentType<f64>> {
        let value = self.levels.value(level)?;
        let notional = 1.0;
        match self.details.instrument() {
            QuoteInstrument::OIS => self.build_ois(value, reference_date, notional),
            QuoteInstrument::FixedRateDeposit => {
                self.build_fixed_rate_deposit(value, reference_date, notional)
            }
            QuoteInstrument::BasisSwap => self.build_basis_swap(value, reference_date, notional),
            QuoteInstrument::Future => self.build_rate_futures(value, reference_date),
            QuoteInstrument::FxOutrightForward => self.build_fx_forward(value, reference_date),
            QuoteInstrument::FixFloatCrossCurrencySwap => {
                let domestic_notional = fx_spot.map_or(notional, |fx| notional * fx);
                self.build_fix_float_cross_currency_swap(
                    value,
                    reference_date,
                    domestic_notional,
                    notional,
                )
            }
            QuoteInstrument::FloatFloatCrossCurrencySwap => {
                let domestic_notional = fx_spot.map_or(notional, |fx| notional * fx);
                self.build_float_float_cross_currency_swap(
                    value,
                    reference_date,
                    domestic_notional,
                    notional,
                )
            }
            QuoteInstrument::EquityCall => self.build_equity_call(reference_date),
            QuoteInstrument::EquityPut => self.build_equity_put(reference_date),
            QuoteInstrument::CapFloor => self.build_cap_floor(value, reference_date, notional),
            QuoteInstrument::CapletFloorlet => self.build_caplet_floorlet(reference_date),
            QuoteInstrument::EuropeanSwaption => {
                self.build_swaption(value, reference_date, notional)
            }
            QuoteInstrument::FxForwardPoints => self.build_fx_forward_points(value, reference_date),
            QuoteInstrument::FxCall => self.build_fx_call(reference_date),
            QuoteInstrument::FxPut => self.build_fx_put(reference_date),
            QuoteInstrument::ConvexityAdjustment => Err(QSError::NotImplementedErr(format!(
                "Cannot build instrument for {:?} — it is a vol / auxiliary quote type",
                QuoteInstrument::ConvexityAdjustment
            ))),
            QuoteInstrument::Cds => Err(QSError::NotImplementedErr(
                "CDS quotes are consumed by the credit curve bootstrapper, not the \
                 calibration-instrument builder"
                    .into(),
            )),
        }
    }

    /// Convenience method for getting the quote index.
    fn required_market_index(details: &QuoteDetails, context: &str) -> Result<MarketIndex> {
        details
            .market_index()
            .cloned()
            .ok_or_else(|| QSError::ValueNotSetErr(format!("Market index on {context}")))
    }

    /// OIS swap - mid value is the fixed rate.
    fn build_ois<T: Scalar + Default>(
        &self,
        rate: f64,
        reference_date: Date,
        notional: f64,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let currency = d
            .currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Currency on OIS quote".into()))?;
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on OIS quote".into()))?;

        let maturity = reference_date + tenor;
        let market_index = Self::required_market_index(d, "OIS quote")?;
        let rd = market_index.rate_index_details()?.rate_definition();

        let mut builder = MakeSwap::<T>::default()
            .with_identifier(d.identifier())
            .with_start_date(reference_date)
            .with_maturity_date(maturity)
            .with_fixed_rate(rate)
            .with_notional(notional)
            .with_rate_definition(rd)
            .with_currency(currency)
            .with_market_index(market_index);
        if let Some(f) = d.pay_leg_frequency() {
            builder = builder.with_fixed_leg_frequency(f);
        }
        if let Some(f) = d.receive_leg_frequency() {
            builder = builder.with_floating_leg_frequency(f);
        }
        let swap = builder.build()?;

        Ok(CalibrationInstrumentType::Swap(swap))
    }

    /// Fixed Rate Deposit — mid value is the deposit rate.
    fn build_fixed_rate_deposit<T: Scalar + Default>(
        &self,
        rate: f64,
        reference_date: Date,
        notional: f64,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let currency = d
            .currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Currency on deposit quote".into()))?;
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on deposit quote".into()))?;

        let maturity = reference_date + tenor;
        let market_index = Self::required_market_index(d, "deposit quote")?;
        let rd = market_index.rate_index_details()?.rate_definition();

        let deposit = MakeFixedRateDeposit::<T>::default()
            .with_identifier(d.identifier())
            .with_start_date(reference_date)
            .with_maturity_date(maturity)
            .with_rate(rate)
            .with_notional(notional)
            .with_rate_definition(rd)
            .with_currency(currency)
            .with_discount_index(Some(market_index))
            .build()?;

        Ok(CalibrationInstrumentType::FixedRateDeposit(deposit))
    }

    /// Basis Swap — mid value is the spread applied to the receive leg.
    fn build_basis_swap<T: Scalar + Default>(
        &self,
        spread: f64,
        reference_date: Date,
        notional: f64,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let currency = d
            .currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Currency on basis swap quote".into()))?;
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on basis swap quote".into()))?;
        let recv_index = d
            .secondary_market_index()
            .ok_or_else(|| {
                QSError::ValueNotSetErr("Secondary market index on basis swap quote".into())
            })?
            .clone();
        let pay_index = Self::required_market_index(d, "basis swap quote")?;

        let maturity = reference_date + tenor;

        let mut builder = MakeBasisSwap::<T>::default()
            .with_identifier(d.identifier())
            .with_start_date(reference_date)
            .with_maturity_date(maturity)
            .with_notional(notional)
            .with_currency(currency)
            .with_pay_market_index(pay_index)
            .with_receive_market_index(recv_index)
            .with_pay_spread(spread);
        if let Some(f) = d.pay_leg_frequency() {
            builder = builder.with_pay_leg_frequency(f);
        }
        if let Some(f) = d.receive_leg_frequency() {
            builder = builder.with_receive_leg_frequency(f);
        }
        let basis_swap = builder.build()?;

        Ok(CalibrationInstrumentType::BasisSwap(basis_swap))
    }

    /// Rate Futures — mid value is the futures price, dates resolved from IMM code.
    fn build_rate_futures<T: Scalar + Default>(
        &self,
        price: f64,
        reference_date: Date,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let code = d
            .contract_code()
            .ok_or_else(|| QSError::ValueNotSetErr("Contract code on futures quote".into()))?;

        let start_date = IMM::date(code, reference_date);
        let end_date = IMM::next_date(start_date, true);
        let market_index = Self::required_market_index(d, "futures quote")?;
        let rd = market_index.rate_index_details()?.rate_definition();

        let futures = MakeRateFutures::default()
            .with_identifier(d.identifier())
            .with_market_index(market_index)
            .with_start_date(start_date)
            .with_end_date(end_date)
            .with_futures_price(price)
            .with_rate_definition(rd)
            .build()?;

        Ok(CalibrationInstrumentType::RateFutures(futures))
    }

    /// FX Forward — mid value is the outright forward rate.
    fn build_fx_forward<T: Scalar + Default>(
        &self,
        forward_rate: f64,
        reference_date: Date,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let base = d
            .pay_currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Base currency on FX forward quote".into()))?;
        let quote_ccy = d
            .receive_currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Quote currency on FX forward quote".into()))?;
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on FX forward quote".into()))?;

        let delivery_date = reference_date + tenor;

        let fwd = MakeFxForward::default()
            .with_identifier(d.identifier())
            .with_delivery_date(delivery_date)
            .with_forward_rate(forward_rate)
            .with_base_currency(base)
            .with_quote_currency(quote_ccy)
            .build()?;

        Ok(CalibrationInstrumentType::FxForward(fwd))
    }

    /// FX Forward Points — mid value is the forward points (absolute).
    ///
    /// Builds an [`FxForward`] with `forward_points` set. The bootstrap
    /// residual combines these with the FX spot (from the discount policy)
    /// to solve for discount factors via covered interest-rate parity.
    fn build_fx_forward_points<T: Scalar + Default>(
        &self,
        points: f64,
        reference_date: Date,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let base = d
            .pay_currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Base currency on FX fwd pts quote".into()))?;
        let quote_ccy = d
            .receive_currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Quote currency on FX fwd pts quote".into()))?;
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on FX fwd pts quote".into()))?;

        let delivery_date = reference_date + tenor;

        let fwd = MakeFxForward::default()
            .with_identifier(d.identifier())
            .with_delivery_date(delivery_date)
            .with_forward_points(points)
            .with_base_currency(base)
            .with_quote_currency(quote_ccy)
            .build()?;

        Ok(CalibrationInstrumentType::FxForward(fwd))
    }

    /// Cross-Currency Swap (fixed domestic vs floating foreign).
    /// Mid value is the fixed rate on the domestic leg.
    fn build_fix_float_cross_currency_swap<T: Scalar + Default>(
        &self,
        fixed_rate: f64,
        reference_date: Date,
        domestic_notional: f64,
        foreign_notional: f64,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let domestic_ccy = d.pay_currency().ok_or_else(|| {
            QSError::ValueNotSetErr("Domestic currency on xccy swap quote".into())
        })?;
        let foreign_ccy = d
            .receive_currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Foreign currency on xccy swap quote".into()))?;
        let floating_index = d
            .market_index()
            .ok_or_else(|| {
                QSError::ValueNotSetErr("Foreign market index on xccy swap quote".into())
            })?
            .clone();
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on xccy swap quote".into()))?;

        let maturity = reference_date + tenor;
        let rd = floating_index.rate_index_details()?.rate_definition();

        let mut builder = MakeFixFloatCrossCurrencySwap::<T>::default()
            .with_identifier(d.identifier())
            .with_start_date(reference_date)
            .with_maturity_date(maturity)
            .with_domestic_notional(domestic_notional)
            .with_foreign_notional(foreign_notional)
            .with_fixed_rate(fixed_rate)
            .with_rate_definition(rd)
            .with_domestic_currency(domestic_ccy)
            .with_foreign_currency(foreign_ccy)
            .with_floating_index(floating_index);
        if let Some(f) = d.pay_leg_frequency() {
            builder = builder.with_domestic_leg_frequency(f);
        }
        if let Some(f) = d.receive_leg_frequency() {
            builder = builder.with_foreign_leg_frequency(f);
        }
        let xccy = builder.build()?;

        Ok(CalibrationInstrumentType::FixFloatCrossCurrencySwap(xccy))
    }

    /// Float-float cross-currency swap — mid value is the spread on the
    /// domestic floating leg.
    fn build_float_float_cross_currency_swap<T: Scalar + Default>(
        &self,
        domestic_spread: f64,
        reference_date: Date,
        domestic_notional: f64,
        foreign_notional: f64,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let domestic_ccy = d.pay_currency().ok_or_else(|| {
            QSError::ValueNotSetErr("Domestic currency on ff-xccy swap quote".into())
        })?;
        let foreign_ccy = d.receive_currency().ok_or_else(|| {
            QSError::ValueNotSetErr("Foreign currency on ff-xccy swap quote".into())
        })?;
        let foreign_index = d
            .secondary_market_index()
            .ok_or_else(|| {
                QSError::ValueNotSetErr("Foreign market index on ff-xccy swap quote".into())
            })?
            .clone();
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on ff-xccy swap quote".into()))?;

        let maturity = reference_date + tenor;
        let domestic_index = Self::required_market_index(d, "ff-xccy swap quote")?;

        let mut builder = MakeFloatFloatCrossCurrencySwap::<T>::default()
            .with_identifier(d.identifier())
            .with_start_date(reference_date)
            .with_maturity_date(maturity)
            .with_domestic_notional(domestic_notional)
            .with_foreign_notional(foreign_notional)
            .with_domestic_spread(domestic_spread)
            .with_domestic_currency(domestic_ccy)
            .with_foreign_currency(foreign_ccy)
            .with_domestic_market_index(domestic_index)
            .with_foreign_market_index(foreign_index);
        if let Some(f) = d.pay_leg_frequency() {
            builder = builder.with_domestic_leg_frequency(f);
        }
        if let Some(f) = d.receive_leg_frequency() {
            builder = builder.with_foreign_leg_frequency(f);
        }
        let xccy = builder.build()?;

        Ok(CalibrationInstrumentType::FloatFloatCrossCurrencySwap(xccy))
    }

    /// European Fx Call — strike and expiry from details.
    fn build_fx_call<T: Scalar + Default>(
        &self,
        reference_date: Date,
    ) -> Result<CalibrationInstrumentType<T>> {
        self.build_fx_option(reference_date, EuroOptionType::Call)
    }

    /// European Fx Call — strike and expiry from details.
    fn build_fx_put<T: Scalar + Default>(
        &self,
        reference_date: Date,
    ) -> Result<CalibrationInstrumentType<T>> {
        self.build_fx_option(reference_date, EuroOptionType::Put)
    }

    fn build_fx_option<T: Scalar + Default>(
        &self,
        reference_date: Date,
        option_type: EuroOptionType,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let strike = d
            .strike()
            .ok_or_else(|| QSError::ValueNotSetErr("Strike on FX option quote".into()))?;
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on FX option quote".into()))?;
        let base_currency = d
            .pay_currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Base currency on FX option quote".into()))?;
        let quote_currency = d
            .receive_currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Quote currency on FX option quote".into()))?;
        let pair = crate::indices::fxpair::FxPair::new(base_currency, quote_currency)?;
        let option = MakeFxEuropeanOption::default()
            .with_identifier(d.identifier())
            .with_expiry_date(reference_date + tenor)
            .with_strike_spec(strike)
            .with_option_type(option_type)
            .with_base_currency(base_currency)
            .with_quote_currency(quote_currency)
            .with_pair(pair)
            .build()?;

        Ok(match option_type {
            EuroOptionType::Call => CalibrationInstrumentType::FxCall(option),
            EuroOptionType::Put => CalibrationInstrumentType::FxPut(option),
        })
    }

    /// European equity Call — strike and expiry from details.
    fn build_equity_call<T: Scalar + Default>(
        &self,
        reference_date: Date,
    ) -> Result<CalibrationInstrumentType<T>> {
        self.build_equity_option(reference_date, EuroOptionType::Call)
    }

    /// European equity Put — strike and expiry from details.
    fn build_equity_put<T: Scalar + Default>(
        &self,
        reference_date: Date,
    ) -> Result<CalibrationInstrumentType<T>> {
        self.build_equity_option(reference_date, EuroOptionType::Put)
    }

    fn build_equity_option<T: Scalar + Default>(
        &self,
        reference_date: Date,
        option_type: EuroOptionType,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let strike = d
            .strike()
            .ok_or_else(|| QSError::ValueNotSetErr("Strike on equity option quote".into()))?;
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on equity option quote".into()))?;
        let currency = d
            .currency()
            .ok_or_else(|| QSError::ValueNotSetErr("Currency on equity option quote".into()))?;
        let option = MakeEquityEuropeanOption::default()
            .with_identifier(d.identifier())
            .with_market_index(Self::required_market_index(d, "equity option quote")?)
            .with_expiry_date(reference_date + tenor)
            .with_strike_spec(strike)
            .with_option_type(option_type)
            .with_currency(currency)
            .build()?;

        Ok(match option_type {
            EuroOptionType::Call => CalibrationInstrumentType::EquityCall(option),
            EuroOptionType::Put => CalibrationInstrumentType::EquityPut(option),
        })
    }

    /// Builds a single `CapletFloorlet` from a vol quote.
    ///
    /// The quote value is the market vol; the strike, expiry, and index tenor
    /// are extracted from the parsed `QuoteDetails`.
    fn build_caplet_floorlet(&self, reference_date: Date) -> Result<CalibrationInstrumentType> {
        use crate::instruments::rates::capletfloorlet::{
            CapletFloorlet as CFL, CapletFloorletType,
        };

        let d = &self.details;
        let option_expiry = d
            .option_expiry()
            .ok_or_else(|| QSError::ValueNotSetErr("Option expiry on CapletFloorlet".into()))?;
        let index_tenor = d
            .index_tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Index tenor on CapletFloorlet".into()))?;
        let market_index = Self::required_market_index(d, "CapletFloorlet quote")?;

        let start = reference_date + option_expiry;
        let end = start + index_tenor;

        let strike = d.strike().unwrap_or(Strike::Atm);

        let cfl = CFL::new(
            d.identifier(),
            market_index,
            d.currency()
                .ok_or_else(|| QSError::ValueNotSetErr("Currency on CapletFloorlet".into()))?,
            start,
            start,
            end,
            end, // payment_date = end_date
            CapletFloorletType::Caplet,
            strike,
        );

        Ok(CalibrationInstrumentType::CapletFloorlet(cfl))
    }

    /// Interest rate Cap or Floor — strike and tenor from details.
    /// The quote value is used as the strike when the details don't carry one.
    fn build_cap_floor<T: Scalar + Default>(
        &self,
        value: f64,
        reference_date: Date,
        notional: f64,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Tenor on CapFloor quote".into()))?;
        let maturity = reference_date + tenor;
        let market_index = Self::required_market_index(d, "CapFloor quote")?;
        let rd = market_index.rate_index_details()?.rate_definition();

        // The quote value is treated as the strike. If the details already
        // carry a parsed strike, prefer that.
        let strike = d.strike().unwrap_or(Strike::Absolute(value)).resolve(0.0);

        // Default to Cap for the quote-driven builder.
        let cap_floor_type = CapFloorType::Cap;

        let mut builder = MakeCapFloor::default()
            .with_identifier(d.identifier())
            .with_start_date(reference_date)
            .with_maturity_date(maturity)
            .with_strike(strike)
            .with_notional(notional)
            .with_rate_definition(rd)
            .with_market_index(market_index)
            .with_currency(
                d.currency()
                    .ok_or_else(|| QSError::ValueNotSetErr("Currency on CapFloor quote".into()))?,
            )
            .with_cap_floor_type(cap_floor_type);
        if let Some(f) = d.pay_leg_frequency() {
            builder = builder.with_frequency(f);
        }
        let cf = builder.build()?;

        Ok(CalibrationInstrumentType::CapFloor(cf))
    }

    /// European swaption — builds the underlying swap and wraps it.
    /// The quote value is used as the strike (fixed rate) when the details
    /// don't carry one.
    fn build_swaption<T: Scalar + Default>(
        &self,
        value: f64,
        reference_date: Date,
        notional: f64,
    ) -> Result<CalibrationInstrumentType<T>> {
        let d = &self.details;
        let option_expiry_period = d
            .option_expiry()
            .ok_or_else(|| QSError::ValueNotSetErr("Option expiry on Swaption quote".into()))?;
        let swap_tenor = d
            .tenor()
            .ok_or_else(|| QSError::ValueNotSetErr("Swap tenor on Swaption quote".into()))?;

        let expiry_date = reference_date + option_expiry_period;
        let swap_maturity = expiry_date + swap_tenor;
        let market_index = Self::required_market_index(d, "Swaption quote")?;
        let rd = market_index.rate_index_details()?.rate_definition();

        let strike = d.strike().unwrap_or(Strike::Absolute(value)).resolve(0.0);

        let mut builder = MakeSwaption::<T>::default()
            .with_identifier(d.identifier())
            .with_expiry(expiry_date)
            .with_start_date(expiry_date)
            .with_swap_tenor_date(swap_maturity)
            .with_strike(strike)
            .with_notional(notional)
            .with_rate_definition(rd)
            .with_market_index(market_index)
            .with_currency(
                d.currency()
                    .ok_or_else(|| QSError::ValueNotSetErr("Currency on Swaption quote".into()))?,
            );
        if let Some(f) = d.pay_leg_frequency() {
            builder = builder.with_fixed_leg_frequency(f);
        }
        if let Some(f) = d.receive_leg_frequency() {
            builder = builder.with_floating_leg_frequency(f);
        }
        let swaption = builder.build()?;

        Ok(CalibrationInstrumentType::EuropeanSwaption(swaption))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn ref_date() -> Date {
        Date::new(2026, 2, 24)
    }

    // -- FromStr round-trips ------------------------------------------------

    #[test]
    fn parse_ois_identifier() {
        let det: QuoteDetails = "OIS_USD_SOFR_1Y".parse().unwrap();
        assert_eq!(det.identifier(), "OIS_USD_SOFR_1Y");
        assert_eq!(*det.instrument(), QuoteInstrument::OIS);
        assert_eq!(det.currency(), Some(Currency::USD));
    }

    #[test]
    fn parse_deposit_identifier() {
        let det: QuoteDetails = "FixedRateDeposit_USD_SOFR_6M".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::FixedRateDeposit);
    }

    #[test]
    fn parse_basis_swap_identifier() {
        let det: QuoteDetails = "BasisSwap_USD_SOFR_TermSOFR3m_1Y".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::BasisSwap);
        assert!(det.secondary_market_index().is_some());
    }

    #[test]
    fn parse_future_identifier() {
        let det: QuoteDetails = "Future_USD_SOFR_H6".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::Future);
        assert_eq!(det.contract_code(), Some("H6"));
    }

    #[test]
    fn parse_convexity_adjustment_identifier() {
        let det: QuoteDetails = "ConvexityAdjustment_USD_SOFR_M6".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::ConvexityAdjustment);
    }

    #[test]
    fn parse_cap_floor_identifier() {
        let det: QuoteDetails = "CapFloor_USD_SOFR_1Y_Absolute_Black".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::CapFloor);
        assert_eq!(det.strike(), Some(Strike::Absolute(0.0)));

        let det2: QuoteDetails = "CapFloor_USD_SOFR_1Y_Absolute_0.03_Black".parse().unwrap();
        assert_eq!(det2.strike(), Some(Strike::Absolute(0.03)));
    }

    #[test]
    fn parse_caplet_floorlet_identifier() {
        let det: QuoteDetails = "CapletFloorlet_USD_TermSOFR3m_3M_3M_Absolute_0.010_Straddle_Black"
            .parse()
            .unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::CapletFloorlet);
        assert_eq!(det.strike(), Some(Strike::Absolute(0.010)));
    }

    #[test]
    fn parse_swaption_identifier() {
        let det: QuoteDetails = "Swaption_USD_SOFR_3M_2Y_Absolute_Black".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::EuropeanSwaption);
    }

    #[test]
    fn parse_outright_forward_identifier() {
        let det: QuoteDetails = "FxOutrightForward_EURUSD_1M".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::FxOutrightForward);
        assert_eq!(det.pay_currency(), Some(Currency::EUR));
        assert_eq!(det.receive_currency(), Some(Currency::USD));
    }

    #[test]
    fn parse_forward_points_identifier() {
        let det: QuoteDetails = "FxForwardPoints_EURUSD_1Y".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::FxForwardPoints);
    }

    #[test]
    fn parse_cross_currency_swap_identifier() {
        let det: QuoteDetails = "FixFloatCrossCurrencySwap_USD_ICP_CLP_1Y".parse().unwrap();
        assert_eq!(
            *det.instrument(),
            QuoteInstrument::FixFloatCrossCurrencySwap
        );
        assert_eq!(det.pay_currency(), Some(Currency::USD));
        assert_eq!(det.receive_currency(), Some(Currency::CLP));
    }

    #[test]
    fn parse_call_identifier() {
        let det: QuoteDetails = "EquityCall_USD_SPX_1Y_Absolute_5000".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::EquityCall);
        assert_eq!(det.strike(), Some(Strike::Absolute(5000.0)));
    }

    #[test]
    fn parse_put_identifier() {
        let det: QuoteDetails = "EquityPut_USD_SPX_1Y_Relative_0.05".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::EquityPut);
        assert_eq!(det.strike(), Some(Strike::Relative(0.05)));
    }

    #[test]
    fn parse_fx_call_identifier() {
        let det: QuoteDetails = "FxCall_EURUSD_1Y_Relative_0.05".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::FxCall);
        assert_eq!(det.pay_currency(), Some(Currency::EUR));
        assert_eq!(det.receive_currency(), Some(Currency::USD));
        assert_eq!(det.strike(), Some(Strike::Relative(0.05)));
    }

    #[test]
    fn parse_with_custom_separator() {
        let det = QuoteDetails::parse("EquityCall|USD|SPX|1Y|Absolute|5000", '|').unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::EquityCall);
        assert_eq!(det.currency(), Some(Currency::USD));
        assert_eq!(det.strike(), Some(Strike::Absolute(5000.0)));
    }

    // -- build_instrument ---------------------------------------------------

    #[test]
    fn build_ois_swap() {
        let details: QuoteDetails = "OIS_USD_SOFR_1Y".parse().unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(0.0484));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(inst, CalibrationInstrumentType::Swap(_)));
    }

    #[test]
    fn build_deposit() {
        let details: QuoteDetails = "FixedRateDeposit_USD_SOFR_6M".parse().unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(0.05));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(
            inst,
            CalibrationInstrumentType::FixedRateDeposit(_)
        ));
    }

    #[test]
    fn build_basis_swap() {
        let details: QuoteDetails = "BasisSwap_USD_SOFR_TermSOFR3m_1Y".parse().unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(0.0003));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(inst, CalibrationInstrumentType::BasisSwap(_)));
    }

    #[test]
    fn build_rate_futures() {
        let details: QuoteDetails = "Future_USD_SOFR_H6".parse().unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(94.75));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(inst, CalibrationInstrumentType::RateFutures(_)));
    }

    #[test]
    fn build_fx_forward() {
        let details: QuoteDetails = "FxOutrightForward_EURUSD_1M".parse().unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(1.08));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(inst, CalibrationInstrumentType::FxForward(_)));
    }

    #[test]
    fn build_cross_currency_swap() {
        let details: QuoteDetails = "FixFloatCrossCurrencySwap_USD_ICP_CLP_1Y".parse().unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(0.05));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(
            inst,
            CalibrationInstrumentType::FixFloatCrossCurrencySwap(_)
        ));
    }

    #[test]
    fn build_call_option() {
        let details: QuoteDetails = "EquityCall_USD_SPX_1Y_Absolute_5000".parse().unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(150.0));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(
            inst,
            CalibrationInstrumentType::EquityCall(option)
                if option.strike() == Strike::Absolute(5000.0)
        ));
    }

    #[test]
    fn build_put_option() {
        let details: QuoteDetails = "EquityPut_USD_SPX_1Y_Relative_0.05".parse().unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(100.0));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(
            inst,
            CalibrationInstrumentType::EquityPut(option)
                if option.strike() == Strike::Relative(0.05)
        ));
    }

    #[test]
    fn build_fx_options() {
        let call = Quote::new(
            "FxCall_EURUSD_1Y_Absolute_1.10".parse().unwrap(),
            QuoteLevels::with_mid(0.12),
        )
        .build_instrument(ref_date(), Level::Mid, None)
        .unwrap();
        let put = Quote::new(
            "FxPut_EURUSD_1Y_Relative_0.05".parse().unwrap(),
            QuoteLevels::with_mid(0.11),
        )
        .build_instrument(ref_date(), Level::Mid, None)
        .unwrap();

        assert!(matches!(
            call,
            CalibrationInstrumentType::FxCall(option)
                if option.strike() == Strike::Absolute(1.10)
        ));
        assert!(matches!(
            put,
            CalibrationInstrumentType::FxPut(option)
                if option.strike() == Strike::Relative(0.05)
        ));
    }

    #[test]
    fn build_swaption() {
        let details: QuoteDetails = "Swaption_USD_SOFR_3M_2Y_Absolute_0.04_Black"
            .parse()
            .unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(0.33));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(
            inst,
            CalibrationInstrumentType::EuropeanSwaption(_)
        ));
    }

    #[test]
    fn build_cap_floor() {
        let details: QuoteDetails = "CapFloor_USD_SOFR_1Y_Absolute_0.03_Black".parse().unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(0.005));
        let inst = quote
            .build_instrument(ref_date(), Level::Mid, None)
            .unwrap();
        assert!(matches!(inst, CalibrationInstrumentType::CapFloor(_)));
    }

    #[test]
    fn vol_quote_builds_caplet_floorlet() {
        let details: QuoteDetails =
            "CapletFloorlet_USD_TermSOFR3m_3M_3M_Absolute_0.010_Straddle_Black"
                .parse()
                .unwrap();
        let quote = Quote::new(details, QuoteLevels::with_mid(0.33));
        let result = quote.build_instrument(ref_date(), Level::Mid, None);
        assert!(result.is_ok());
        let inst = result.unwrap();
        assert!(matches!(inst, CalibrationInstrumentType::CapletFloorlet(_)));
    }

    // -- frequency parsing --------------------------------------------------

    #[test]
    fn parse_ois_with_frequencies() {
        let det: QuoteDetails = "OIS_USD_SOFR_1Y_Semiannual_Quarterly".parse().unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::OIS);
        assert_eq!(det.pay_leg_frequency(), Some(Frequency::Semiannual));
        assert_eq!(det.receive_leg_frequency(), Some(Frequency::Quarterly));
    }

    #[test]
    fn parse_ois_with_single_frequency() {
        let det: QuoteDetails = "OIS_USD_SOFR_1Y_Annual".parse().unwrap();
        assert_eq!(det.pay_leg_frequency(), Some(Frequency::Annual));
        assert_eq!(det.receive_leg_frequency(), None);
    }

    #[test]
    fn parse_ois_without_frequency_still_works() {
        let det: QuoteDetails = "OIS_USD_SOFR_1Y".parse().unwrap();
        assert_eq!(det.pay_leg_frequency(), None);
        assert_eq!(det.receive_leg_frequency(), None);
    }

    #[test]
    fn parse_basis_swap_with_frequencies() {
        let det: QuoteDetails = "BasisSwap_USD_SOFR_TermSOFR3m_1Y_Quarterly_Monthly"
            .parse()
            .unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::BasisSwap);
        assert_eq!(det.pay_leg_frequency(), Some(Frequency::Quarterly));
        assert_eq!(det.receive_leg_frequency(), Some(Frequency::Monthly));
    }

    #[test]
    fn parse_fix_float_xccy_with_frequencies() {
        let det: QuoteDetails = "FixFloatCrossCurrencySwap_USD_ICP_CLP_1Y_Semiannual_Quarterly"
            .parse()
            .unwrap();
        assert_eq!(
            *det.instrument(),
            QuoteInstrument::FixFloatCrossCurrencySwap
        );
        assert_eq!(det.pay_leg_frequency(), Some(Frequency::Semiannual));
        assert_eq!(det.receive_leg_frequency(), Some(Frequency::Quarterly));
    }

    #[test]
    fn parse_float_float_xccy_with_frequencies() {
        let det: QuoteDetails =
            "FloatFloatCrossCurrencySwap_CLP_ICP_SOFR_USD_1Y_Quarterly_Quarterly"
                .parse()
                .unwrap();
        assert_eq!(
            *det.instrument(),
            QuoteInstrument::FloatFloatCrossCurrencySwap
        );
        assert_eq!(det.pay_leg_frequency(), Some(Frequency::Quarterly));
        assert_eq!(det.receive_leg_frequency(), Some(Frequency::Quarterly));
    }

    #[test]
    fn parse_swaption_with_frequencies() {
        let det: QuoteDetails = "Swaption_USD_SOFR_3M_2Y_Semiannual_Semiannual_Absolute_0.04_Black"
            .parse()
            .unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::EuropeanSwaption);
        assert_eq!(det.pay_leg_frequency(), Some(Frequency::Semiannual));
        assert_eq!(det.receive_leg_frequency(), Some(Frequency::Semiannual));
        assert_eq!(det.strike(), Some(Strike::Absolute(0.04)));
    }

    #[test]
    fn parse_swaption_without_frequencies_still_works() {
        let det: QuoteDetails = "Swaption_USD_SOFR_3M_2Y_Absolute_Black".parse().unwrap();
        assert_eq!(det.pay_leg_frequency(), None);
        assert_eq!(det.receive_leg_frequency(), None);
    }

    #[test]
    fn parse_cap_floor_with_frequency() {
        let det: QuoteDetails = "CapFloor_USD_SOFR_1Y_Quarterly_Absolute_0.03_Black"
            .parse()
            .unwrap();
        assert_eq!(*det.instrument(), QuoteInstrument::CapFloor);
        assert_eq!(det.pay_leg_frequency(), Some(Frequency::Quarterly));
        assert_eq!(det.strike(), Some(Strike::Absolute(0.03)));
    }

    #[test]
    fn parse_cap_floor_without_frequency_still_works() {
        let det: QuoteDetails = "CapFloor_USD_SOFR_1Y_Absolute_Black".parse().unwrap();
        assert_eq!(det.pay_leg_frequency(), None);
    }
}