optionstratlib 0.15.3

OptionStratLib is a comprehensive Rust library for options trading and strategy development across multiple asset classes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
use crate::ExpirationDate;
use crate::chains::OptionData;
use crate::constants::{IV_TOLERANCE, MAX_ITERATIONS_IV, ZERO};
use crate::error::{
    GreeksError, OptionsError, OptionsResult, PricingError, StrategyError, VolatilityError,
};
use crate::greeks::Greeks;
use crate::model::types::{OptionBasicType, OptionStyle, OptionType, Side};
use crate::model::utils::calculate_optimal_price_range;
use crate::pnl::utils::{PnL, PnLCalculator};
use crate::pricing::monte_carlo::price_option_monte_carlo;
use crate::pricing::{
    BinomialPricingParams, Payoff, PayoffInfo, Profit, black_scholes, generate_binomial_tree,
    price_binomial, telegraph,
};
use crate::strategies::base::BasicAble;
use crate::visualization::{
    ColorScheme, Graph, GraphConfig, GraphData, LineStyle, Series2D, TraceMode,
};
use num_traits::FromPrimitive;
use positive::{Positive, pos_or_panic};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use tracing::{error, trace};
use utoipa::ToSchema;

/// Result type for binomial tree pricing models, containing:
/// - The option price
/// - Price tree (asset price evolution)
/// - Option value tree (option value at each node)
type PriceBinomialTree = OptionsResult<(Decimal, Vec<Vec<Decimal>>, Vec<Vec<Decimal>>)>;

/// Parameters for exotic option pricing models.
///
/// This structure holds specific data required by various exotic option types
/// such as Asian options (which depend on average prices) and Lookback options
/// (which depend on minimum/maximum prices during the option's lifetime).
///
/// Each field is optional since different exotic option types require different parameters.
#[derive(Clone, Default, PartialEq, Serialize, Deserialize, Debug, ToSchema)]
pub struct ExoticParams {
    /// Historical spot prices, primarily used for Asian options which
    /// depend on the average price of the underlying asset.
    pub spot_prices: Option<Vec<Positive>>, // Asian

    /// Minimum observed spot price during the option's lifetime,
    /// used for lookback option pricing.
    pub spot_min: Option<Decimal>, // Lookback

    /// Maximum observed spot price during the option's lifetime,
    /// used for lookback option pricing.
    pub spot_max: Option<Decimal>, // Lookback

    /// Local cap for Cliquet options, limiting the periodic return.
    pub cliquet_local_cap: Option<Decimal>, // Cliquet

    /// Local floor for Cliquet options, limiting the periodic return.
    pub cliquet_local_floor: Option<Decimal>, // Cliquet

    /// Global cap for Cliquet options, limiting the total return.
    pub cliquet_global_cap: Option<Decimal>, // Cliquet

    /// Global floor for Cliquet options, limiting the total return.
    pub cliquet_global_floor: Option<Decimal>, // Cliquet

    /// Price of the second underlying asset for Rainbow options.
    pub rainbow_second_asset_price: Option<Positive>, // Rainbow

    /// Volatility of the second underlying asset for Rainbow options.
    pub rainbow_second_asset_volatility: Option<Positive>, // Rainbow

    /// Dividend yield of the second underlying asset for Rainbow options.
    pub rainbow_second_asset_dividend: Option<Positive>, // Rainbow

    /// Correlation between the two underlying assets for Rainbow options.
    /// Must be between -1.0 and 1.0.
    pub rainbow_correlation: Option<Decimal>, // Rainbow

    /// Volatility of the second underlying asset for Spread options.
    pub spread_second_asset_volatility: Option<Positive>, // Spread

    /// Dividend yield of the second underlying asset for Spread options.
    pub spread_second_asset_dividend: Option<Positive>, // Spread

    /// Correlation between the two underlying assets for Spread options.
    /// Must be between -1.0 and 1.0.
    pub spread_correlation: Option<Decimal>, // Spread

    /// Volatility of the exchange rate for Quanto options.
    pub quanto_fx_volatility: Option<Positive>, // Quanto

    /// Correlation between the underlying asset and the exchange rate for Quanto options.
    /// Must be between -1.0 and 1.0.
    pub quanto_fx_correlation: Option<Decimal>, // Quanto

    /// Foreign risk-free interest rate for Quanto options.
    pub quanto_foreign_rate: Option<Decimal>, // Quanto

    /// Volatility of the second underlying asset for Exchange options.
    pub exchange_second_asset_volatility: Option<Positive>, // Exchange

    /// Dividend yield of the second underlying asset for Exchange options.
    pub exchange_second_asset_dividend: Option<Positive>, // Exchange

    /// Correlation between the two underlying assets for Exchange options.
    /// Must be between -1.0 and 1.0.
    pub exchange_correlation: Option<Decimal>, // Exchange
}

/// Represents a financial option contract with its essential parameters and characteristics.
///
/// This structure contains all the necessary information to define an options contract,
/// including its type (call/put), market position (long/short), pricing parameters,
/// and contract specifications. It serves as the core data model for option pricing,
/// risk analysis, and strategy development.
///
/// The `Options` struct supports both standard option types and exotic options through
/// the optional `exotic_params` field, making it versatile for various financial modeling
/// scenarios.
#[derive(Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct Options {
    /// Specifies whether this is a European or American option
    pub option_type: OptionType,

    /// Indicates whether the position is Long (purchased) or Short (sold/written),
    /// which determines the profit/loss direction and risk profile.
    pub side: Side,

    /// The ticker symbol or identifier of the underlying asset (e.g., "AAPL" for Apple stock).
    pub underlying_symbol: String,

    /// The price at which the option holder can exercise their right to buy (for calls)
    /// or sell (for puts) the underlying asset.
    pub strike_price: Positive,

    /// When the option contract expires, either as days from now or as a specific date.
    pub expiration_date: ExpirationDate,

    /// The market's expectation for future volatility of the underlying asset,
    /// a key parameter for option pricing models.
    pub implied_volatility: Positive,

    /// The number of contracts in this position.
    pub quantity: Positive,

    /// The current market price of the underlying asset.
    pub underlying_price: Positive,

    /// The current risk-free interest rate used in option pricing models,
    /// typically based on treasury yields of similar duration.
    pub risk_free_rate: Decimal,

    /// The option is a Call or Put option, determining the fundamental right
    /// option can be exercised.
    pub option_style: OptionStyle,

    /// The annualized dividend yield of the underlying asset, affecting option pricing
    /// particularly for longer-dated contracts.
    pub dividend_yield: Positive,

    /// Additional parameters required for exotic option types like Asian or Lookback options.
    /// This field is None for standard (vanilla) options.
    pub exotic_params: Option<ExoticParams>,
}

impl Options {
    /// Creates a new options contract with the specified parameters.
    ///
    /// This constructor creates an instance of `Options` with all the required parameters
    /// for defining and pricing an option contract. It supports both standard (vanilla)
    /// options and exotic options through the optional `exotic_params` parameter.
    ///
    /// # Parameters
    ///
    /// * `option_type` - Specifies whether this is a Call or Put option, determining the fundamental
    ///   right the option contract provides.
    /// * `side` - Indicates whether the position is Long (purchased) or Short (sold/written),
    ///   which determines the profit/loss direction.
    /// * `underlying_symbol` - The ticker symbol or identifier of the underlying asset (e.g., "AAPL").
    /// * `strike_price` - The price at which the option can be exercised, represented as a `Positive` value.
    /// * `expiration_date` - When the option contract expires, either as days from now or as a specific date.
    /// * `implied_volatility` - The market's expectation for future volatility of the underlying asset,
    ///   a key parameter for option pricing.
    /// * `quantity` - The number of contracts in this position, represented as a `Positive` value.
    /// * `underlying_price` - The current market price of the underlying asset.
    /// * `risk_free_rate` - The current risk-free interest rate used in option pricing models.
    /// * `option_style` - The option exercise style (European or American), determining when the
    ///   option can be exercised.
    /// * `dividend_yield` - The annualized dividend yield of the underlying asset, affecting option pricing.
    /// * `exotic_params` - Additional parameters required for exotic option types. Set to `None` for
    ///   standard (vanilla) options.
    ///
    /// # Returns
    ///
    /// A fully configured `Options` instance with all the specified parameters.
    ///
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        option_type: OptionType,
        side: Side,
        underlying_symbol: String,
        strike_price: Positive,
        expiration_date: ExpirationDate,
        implied_volatility: Positive,
        quantity: Positive,
        underlying_price: Positive,
        risk_free_rate: Decimal,
        option_style: OptionStyle,
        dividend_yield: Positive,
        exotic_params: Option<ExoticParams>,
    ) -> Self {
        Options {
            option_type,
            side,
            underlying_symbol,
            strike_price,
            expiration_date,
            implied_volatility,
            quantity,
            underlying_price,
            risk_free_rate,
            option_style,
            dividend_yield,
            exotic_params,
        }
    }

    /// Updates option parameters using data from an OptionData structure.
    ///
    /// This method updates the option's strike price and implied volatility based on the
    /// values provided in the option_data parameter. If the implied volatility is not
    /// available in the option data, it defaults to zero.
    ///
    /// # Arguments
    ///
    /// * `option_data` - A reference to an OptionData structure containing updated option parameters.
    ///
    pub(crate) fn update_from_option_data(&mut self, option_data: &OptionData) {
        self.strike_price = option_data.strike_price;
        self.implied_volatility = option_data.implied_volatility;
        trace!("Updated Option: {:#?}", self);
    }

    /// Calculates the time to expiration of the option in years.
    ///
    /// This function computes the time remaining until the option's expiration date,
    /// expressed as a positive decimal value representing years. This is a key parameter
    /// used in option pricing models.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Positive>` - A result containing the time to expiration in years
    ///   as a Positive value, or an error if the calculation failed.
    ///
    pub fn time_to_expiration(&self) -> OptionsResult<Positive> {
        Ok(self.expiration_date.get_years()?)
    }

    /// Determines if the option position is long (purchased).
    ///
    /// A long position indicates that the option has been bought, meaning the holder
    /// has the right to exercise the option according to its terms.
    ///
    /// # Returns
    ///
    /// * `bool` - Returns true if the option is held as a long position, false otherwise.
    ///
    pub fn is_long(&self) -> bool {
        matches!(self.side, Side::Long)
    }

    /// Determines if the option position is short (written/sold).
    ///
    /// A short position indicates that the option has been sold or written, meaning
    /// the holder has the obligation to fulfill the contract terms if the option is exercised.
    ///
    /// # Returns
    ///
    /// * `bool` - Returns true if the option is held as a short position, false otherwise.
    ///
    pub fn is_short(&self) -> bool {
        matches!(self.side, Side::Short)
    }

    /// Calculates the price of an option using the binomial tree model.
    ///
    /// This method implements the binomial option pricing model which constructs a
    /// discrete-time lattice (tree) of possible future underlying asset prices to
    /// determine the option's value. The approach is particularly valuable for pricing
    /// American options and other early-exercise scenarios.
    ///
    /// The calculation divides the time to expiration into a specified number of steps,
    /// creating a binomial tree that represents possible price paths of the underlying asset.
    /// The option's value is then calculated by working backward from expiration to the
    /// present value.
    ///
    /// # Parameters
    ///
    /// * `no_steps` - The number of steps to use in the binomial tree calculation.
    ///   Higher values increase accuracy but also computational cost.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Decimal>` - A result containing the calculated option price as a
    ///   Decimal value, or an OptionsError if the calculation failed.
    ///
    /// # Errors
    ///
    /// Returns an `OptionsError::OtherError` if:
    /// * The number of steps is zero
    /// * The time to expiration calculation fails
    /// * The binomial price calculation fails
    pub fn calculate_price_binomial(&self, no_steps: usize) -> OptionsResult<Decimal> {
        if no_steps == 0 {
            return Err(OptionsError::OtherError {
                reason: "Number of steps cannot be zero".to_string(),
            });
        }
        let expiry = self.time_to_expiration()?;
        let cpb = price_binomial(BinomialPricingParams {
            asset: self.underlying_price,
            volatility: self.implied_volatility,
            int_rate: self.risk_free_rate,
            strike: self.strike_price,
            expiry,
            no_steps,
            option_type: &self.option_type,
            option_style: &self.option_style,
            side: &self.side,
        })?;
        Ok(cpb)
    }

    /// Calculates option price using the binomial tree model.
    ///
    /// This method implements a binomial tree (lattice) approach to option pricing, which
    /// discretizes the underlying asset's price movement over time. The model builds a tree
    /// of possible future asset prices and works backwards to determine the current option value.
    ///
    /// # Parameters
    ///
    /// * `no_steps` - The number of discrete time steps to use in the model. Higher values
    ///   increase precision but also computational cost.
    ///
    /// # Returns
    ///
    /// * `PriceBinomialTree` - A result containing:
    ///   - The calculated option price
    ///   - The asset price tree (underlying price evolution)
    ///   - The option value tree (option price at each node)
    ///
    /// This method is particularly valuable for pricing American options and other early-exercise
    /// scenarios that cannot be accurately priced using closed-form solutions.
    pub fn calculate_price_binomial_tree(&self, no_steps: usize) -> PriceBinomialTree {
        let expiry = self.time_to_expiration()?;
        let params = BinomialPricingParams {
            asset: self.underlying_price,
            volatility: self.implied_volatility,
            int_rate: self.risk_free_rate,
            strike: self.strike_price,
            expiry,
            no_steps,
            option_type: &self.option_type,
            option_style: &self.option_style,
            side: &self.side,
        };
        let (asset_tree, option_tree) = generate_binomial_tree(&params)?;
        let price = match self.side {
            Side::Long => option_tree[0][0],
            Side::Short => -option_tree[0][0],
        };
        Ok((price, asset_tree, option_tree))
    }

    /// Calculates option price using the Black-Scholes model.
    ///
    /// This method implements the Black-Scholes option pricing formula, which provides
    /// a closed-form solution for European-style options. The model assumes lognormal
    /// distribution of underlying asset prices and constant volatility.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Decimal>` - A result containing the calculated option price
    ///   as a Decimal value, or an error if the calculation failed.
    ///
    /// This method is computationally efficient but limited to European options without
    /// early exercise capabilities.
    pub fn calculate_price_black_scholes(&self) -> OptionsResult<Decimal> {
        Ok(black_scholes(self)?)
    }

    /// Calculates the price of an option using the Monte Carlo simulation method.
    ///
    /// # Arguments
    ///
    /// * `prices` - A slice of `Positive` values representing the prices used
    ///   in the Monte Carlo simulation.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Positive>` - The calculated price of the option wrapped in
    ///   an `OptionsResult`. This will return a valid `Positive` value if successful,
    ///   or an error if the simulation fails.
    ///
    /// # Errors
    ///
    /// This function will return an error in the `OptionsResult` if the internal
    /// Monte Carlo price computation fails during the execution of `price_option_monte_carlo`.
    ///
    pub fn calculate_price_montecarlo(&self, prices: &[Positive]) -> OptionsResult<Positive> {
        Ok(price_option_monte_carlo(self, prices)?)
    }

    /// Calculates option price using the Telegraph equation approach.
    ///
    /// This method implements a finite-difference method based on the Telegraph equation
    /// to price options. This approach can handle a variety of option styles and types,
    /// including path-dependent options.
    ///
    /// # Parameters
    ///
    /// * `no_steps` - The number of discrete time steps to use in the model. Higher values
    ///   increase precision but also computational cost.
    ///
    /// # Returns
    ///
    /// * `Result<Decimal, PricingError>` - A result containing the calculated option price
    ///   as a Decimal value, or a boxed error if the calculation failed.
    pub fn calculate_price_telegraph(&self, no_steps: usize) -> OptionsResult<Decimal> {
        Ok(telegraph(self, no_steps, None, None)?)
    }

    /// Calculates the intrinsic value (payoff) of the option at the current underlying price.
    ///
    /// The payoff represents what the option would be worth if exercised immediately,
    /// based on the current market conditions. For out-of-the-money options, the payoff
    /// will be zero.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Decimal>` - A result containing the calculated payoff as a
    ///   Decimal value, adjusted for the quantity of contracts held, or an error if
    ///   the calculation failed.
    ///
    /// This method is useful for determining the exercise value of an option and for
    /// analyzing whether an option has intrinsic value.
    pub fn payoff(&self) -> OptionsResult<Decimal> {
        let payoff_info = PayoffInfo {
            spot: self.underlying_price,
            strike: self.strike_price,
            style: self.option_style,
            side: self.side,
            spot_prices: None,
            spot_min: None,
            spot_max: None,
        };
        let payoff = self.option_type.payoff(&payoff_info) * self.quantity.to_f64();
        Ok(Decimal::from_f64(payoff).unwrap_or_default())
    }

    /// Calculates the financial payoff value of the option at a specific underlying price.
    ///
    /// This method determines the option's payoff based on its type, strike price, style,
    /// and side (long/short) at the given underlying price. The result represents the
    /// total profit or loss for the option position at that price, adjusted by the position quantity.
    ///
    /// # Parameters
    ///
    /// * `price` - A `Positive` value representing the hypothetical price of the underlying asset.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Decimal>` - The calculated payoff value as a `Decimal`, wrapped in a `Result` type.
    ///   Returns an `Err` if the payoff calculation encounters an error.
    ///
    pub fn payoff_at_price(&self, price: &Positive) -> OptionsResult<Decimal> {
        let payoff_info = PayoffInfo {
            spot: *price,
            strike: self.strike_price,
            style: self.option_style,
            side: self.side,
            spot_prices: None,
            spot_min: None,
            spot_max: None,
        };
        let price = self.option_type.payoff(&payoff_info) * self.quantity.to_f64();
        Ok(Decimal::from_f64(price).unwrap_or_default())
    }

    /// Calculates the intrinsic value of the option.
    ///
    /// The intrinsic value is the difference between the underlying asset's price and the option's strike price.
    /// For call options, the intrinsic value is the maximum of zero and the difference between the underlying price and the strike price.
    /// For put options, the intrinsic value is the maximum of zero and the difference between the strike price and the underlying price.
    ///
    /// # Arguments
    ///
    /// * `underlying_price` - The current price of the underlying asset.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Decimal>` - The intrinsic value of the option, or an error if the calculation fails.
    pub fn intrinsic_value(&self, underlying_price: Positive) -> OptionsResult<Decimal> {
        let payoff_info = PayoffInfo {
            spot: underlying_price,
            strike: self.strike_price,
            style: self.option_style,
            side: self.side,
            spot_prices: None,
            spot_min: None,
            spot_max: None,
        };
        let iv = self.option_type.payoff(&payoff_info) * self.quantity.to_f64();
        Ok(Decimal::from_f64(iv).unwrap_or_default())
    }

    /// Determines whether an option is "in-the-money" based on its current price relative to strike price.
    ///
    /// An option is considered in-the-money when:
    /// - For Call options: the underlying asset price is greater than or equal to the strike price
    /// - For Put options: the underlying asset price is less than or equal to the strike price
    ///
    /// This status is important for evaluating the option's current value and potential profitability.
    ///
    /// # Returns
    /// `true` if the option is in-the-money, `false` otherwise
    pub fn is_in_the_money(&self) -> bool {
        match self.option_style {
            OptionStyle::Call => self.underlying_price >= self.strike_price,
            OptionStyle::Put => self.underlying_price <= self.strike_price,
        }
    }

    /// Calculates the time value component of an option's price.
    ///
    /// Time value represents the portion of an option's premium that exceeds its intrinsic value.
    /// It reflects the market's expectation that the option may become more valuable before expiration
    /// due to potential favorable movements in the underlying asset price.
    ///
    /// The calculation uses the Black-Scholes model to determine the total option price,
    /// then subtracts the intrinsic value to find the time value component.
    ///
    /// # Returns
    /// - `Ok(Decimal)` containing the time value (never negative, minimum value is zero)
    /// - `Err` if the price calculation encounters an error
    pub fn time_value(&self) -> OptionsResult<Decimal> {
        let option_price = self.calculate_price_black_scholes()?.abs();
        let intrinsic_value = self.intrinsic_value(self.underlying_price)?;
        Ok((option_price - intrinsic_value).max(Decimal::ZERO))
    }

    /// Validates that the option parameters are in a valid state for calculations.
    ///
    /// This function performs comprehensive validation of the option's critical parameters
    /// to ensure they meet basic requirements for meaningful financial calculations.
    /// It logs detailed error messages when validation fails.
    ///
    /// Validation checks include:
    /// - Underlying symbol is not empty
    /// - Implied volatility is non-negative
    /// - Quantity is non-zero
    /// - Risk-free rate is non-negative
    /// - Strike price is positive and non-zero
    /// - Underlying price is positive and non-zero
    ///
    /// # Returns
    /// `true` if all parameters are valid, `false` if any validation fails
    pub(crate) fn validate(&self) -> bool {
        if self.underlying_symbol == *"" {
            error!("Underlying symbol is empty");
            return false;
        }
        if self.implied_volatility < ZERO {
            error!("Implied volatility is less than zero");
            return false;
        }
        if self.quantity == ZERO {
            error!("Quantity is equal to zero");
            return false;
        }
        if self.risk_free_rate < Decimal::ZERO {
            error!("Risk free rate is less than zero");
            return false;
        }
        if self.strike_price == Positive::ZERO {
            error!("Strike is zero");
            return false;
        }
        if self.underlying_price == Positive::ZERO {
            error!("Underlying price is zero");
            return false;
        }
        true
    }

    /// **calculate_implied_volatility**:
    ///
    /// This function estimates the implied volatility of an option based on its market price
    /// using binary search. Implied volatility is a key metric in options trading that reflects
    /// the market's view of the expected volatility of the underlying asset.
    ///
    /// ### Parameters:
    ///
    /// - `market_price`: The market price of the option as a `Decimal`. This represents the cost
    ///   at which the option is traded in the market.
    ///
    /// ### Returns:
    ///
    /// - `Ok(Positive)`: A `Positive` value representing the calculated implied volatility as a percentage.
    /// - `Err(ImpliedVolatilityError)`: An error indicating the reason calculation failed, such as:
    ///     - No convergence within the maximum number of iterations.
    ///     - Invalid option parameters.
    ///
    /// ### Implementation Details:
    ///
    /// - **Binary Search**: The function uses a binary search approach to iteratively find
    ///   the implied volatility (`volatility`) that narrows the difference between the calculated
    ///   option price (via Black-Scholes) and the target `market_price`.
    ///
    /// - **Short Options Adjustment**: For short options, the market price is inverted (negated),
    ///   and this adjustment ensures proper calculation of implied volatility.
    ///
    /// - **Bounds and Iteration**: The method starts with a maximum bound (`5.0`, representing 500%
    ///   volatility) and a lower bound (`0.0`). It adjusts these bounds based on whether the computed
    ///   price is above or below the target and repeats until convergence or the maximum number of
    ///   iterations is reached (`MAX_ITERATIONS_IV`).
    ///
    /// - **Convergence Tolerance**: The function stops iterating when the computed price is within `IV_TOLERANCE`
    ///   of the target market price or when the difference between the high and low bounds is smaller
    ///   than a threshold (`0.0001`).
    ///
    /// ### Error Cases:
    /// - **No Convergence**: If the binary search exhausts the allowed number of iterations (`MAX_ITERATIONS_IV`)
    ///   without sufficiently narrowing down the implied volatility, the function returns an `ImpliedVolatilityError::NoConvergence`.
    /// - **Invalid Parameters**: Bounds violations or invalid market inputs can potentially cause other errors
    ///   during calculations.
    ///
    /// ### Example Usage:
    /// ```rust
    /// use rust_decimal_macros::dec;
    /// use rust_decimal::Decimal;
    /// use tracing::{error, info};
    /// use positive::{pos_or_panic, Positive};
    /// use optionstratlib::{ExpirationDate, OptionStyle, OptionType, Options, Side};
    ///
    /// let options = Options::new(
    ///             OptionType::European,
    ///             Side::Short,
    ///             "TEST".to_string(),
    ///             pos_or_panic!(6050.0), // strike
    ///             ExpirationDate::Days(pos_or_panic!(60.0)),
    ///             pos_or_panic!(0.1),     // initial iv
    ///             Positive::ONE,     // qty
    ///             pos_or_panic!(6032.18), // underlying
    ///             dec!(0.0),     // rate
    ///             OptionStyle::Call,
    ///             Positive::ZERO, // div
    ///             None,
    ///         ); // Configure your option parameters
    /// let market_price = dec!(133.5);  
    ///
    /// match options.calculate_implied_volatility(market_price) {
    ///     Ok(volatility) => info!("Implied Volatility: {}", volatility.to_dec()),
    ///     Err(e) => error!("Failed to calculate implied volatility: {:?}", e),
    /// }
    /// ```
    pub fn calculate_implied_volatility(
        &self,
        market_price: Decimal,
    ) -> Result<Positive, VolatilityError> {
        let is_short = self.is_short();
        let target_price = if is_short {
            -market_price
        } else {
            market_price
        };

        // Initialize high and low bounds for volatility
        let mut high = pos_or_panic!(5.0); // 500% max volatility
        let mut low = Positive::ZERO;

        // Binary search through volatilities until we find one that gives us our target price
        // or until we reach maximum iterations
        for _ in 0..MAX_ITERATIONS_IV {
            // Calculate midpoint volatility
            let mid_vol = (high.to_dec() + low.to_dec()) / Decimal::TWO;
            let volatility = Positive::new_decimal(mid_vol)
                .expect("mid_vol derived from Positive bounds is non-negative");

            // Calculate option price at this volatility
            let mut option_copy = self.clone();
            option_copy.implied_volatility = volatility;
            let price = option_copy.calculate_price_black_scholes()?;

            // Adjust price for short positions
            let actual_price = if is_short { -price } else { price };

            // Check if we're close enough to the target price
            if (actual_price - target_price).abs() < IV_TOLERANCE {
                return Ok(volatility);
            }

            // Update bounds based on whether this price was too high or too low
            if actual_price > target_price {
                high = volatility;
            } else {
                low = volatility;
            }

            // Check if our range is too small (meaning we've converged)
            if (high - low).to_dec() < dec!(0.0001) {
                return Ok(volatility);
            }
        }

        // If we haven't found a solution after max iterations
        Err(VolatilityError::NoConvergence {
            iterations: MAX_ITERATIONS_IV,
            last_volatility: (high + low) / Positive::TWO,
        })
    }
}

impl TryFrom<&OptionData> for Options {
    type Error = OptionsError;

    fn try_from(option_data: &OptionData) -> Result<Self, Self::Error> {
        let underlying_symbol =
            option_data
                .symbol
                .clone()
                .ok_or_else(|| OptionsError::ValidationError {
                    field: "symbol".to_string(),
                    reason: "OptionData must have a valid symbol".to_string(),
                })?;

        let expiration_date =
            option_data
                .expiration_date
                .ok_or_else(|| OptionsError::ValidationError {
                    field: "expiration_date".to_string(),
                    reason: "OptionData must have a valid expiration date".to_string(),
                })?;

        let underlying_price = option_data
            .underlying_price
            .as_ref()
            .map(|p| **p)
            .ok_or_else(|| OptionsError::ValidationError {
                field: "underlying_price".to_string(),
                reason: "OptionData must have a valid underlying price".to_string(),
            })?;

        Ok(Options {
            option_type: OptionType::European,
            side: Side::Long,
            underlying_symbol,
            strike_price: option_data.strike_price,
            expiration_date,
            implied_volatility: option_data.implied_volatility,
            quantity: Positive::ONE,
            underlying_price,
            risk_free_rate: option_data.risk_free_rate.unwrap_or(Decimal::ZERO),
            option_style: OptionStyle::Call,
            dividend_yield: option_data.dividend_yield.unwrap_or(Positive::ZERO),
            exotic_params: None,
        })
    }
}

impl Default for Options {
    fn default() -> Self {
        Options {
            option_type: OptionType::European,
            side: Side::Long,
            underlying_symbol: "".to_string(),
            strike_price: Positive::ZERO,
            expiration_date: ExpirationDate::Days(Positive::ZERO),
            implied_volatility: Positive::ZERO,
            quantity: Positive::ZERO,
            underlying_price: Positive::ZERO,
            risk_free_rate: Decimal::ZERO,
            option_style: OptionStyle::Call,
            dividend_yield: Positive::ZERO,
            exotic_params: None,
        }
    }
}

impl Greeks for Options {
    fn get_options(&self) -> Result<Vec<&Options>, GreeksError> {
        Ok(vec![self])
    }
}

impl PnLCalculator for Options {
    fn calculate_pnl(
        &self,
        market_price: &Positive,
        expiration_date: ExpirationDate,
        implied_volatility: &Positive,
    ) -> Result<PnL, PricingError> {
        // Create a copy of the current option with updated parameters
        let mut current_option = self.clone();
        current_option.underlying_price = *market_price;
        current_option.expiration_date = expiration_date;
        current_option.implied_volatility = *implied_volatility;

        // Calculate theoretical price at current market conditions
        let current_price = current_option.calculate_price_black_scholes()?;

        // Calculate initial price (when option was created)
        let initial_price = self.calculate_price_black_scholes()?;

        // Calculate initial costs (premium paid/received)
        let (initial_costs, initial_income) = match self.side {
            Side::Long => (initial_price * self.quantity, Decimal::ZERO),
            Side::Short => (Decimal::ZERO, -initial_price * self.quantity),
        };

        // Calculate unrealized PnL adjusted for position side
        let unrealized = Some((current_price - initial_price) * self.quantity);

        Ok(PnL::new(
            None, // No realized PnL yet
            unrealized,
            Positive::new_decimal(initial_costs)?,
            Positive::new_decimal(initial_income)?,
            current_option.expiration_date.get_date()?,
        ))
    }

    fn calculate_pnl_at_expiration(
        &self,
        underlying_price: &Positive,
    ) -> Result<PnL, PricingError> {
        let realized = Some(self.payoff_at_price(underlying_price)?);
        let initial_price = self.calculate_price_black_scholes()?;

        let (initial_costs, initial_income) = match self.side {
            Side::Long => (initial_price * self.quantity, Decimal::ZERO),
            Side::Short => (Decimal::ZERO, initial_price * self.quantity),
        };

        Ok(PnL::new(
            realized, // No realized PnL yet
            None,
            Positive::new_decimal(initial_costs)?,
            Positive::new_decimal(initial_income)?,
            self.expiration_date.get_date()?,
        ))
    }
}

impl Profit for Options {
    fn calculate_profit_at(&self, price: &Positive) -> Result<Decimal, PricingError> {
        Ok(self.payoff_at_price(price)?)
    }
}

impl BasicAble for Options {
    fn get_title(&self) -> String {
        format!(
            "Underlying: {} @ ${:.0} {} {} {}",
            self.underlying_symbol,
            self.strike_price,
            self.side,
            self.option_style,
            self.option_type
        )
    }
    fn get_option_basic_type(&self) -> HashSet<OptionBasicType<'_>> {
        let mut hash_set = HashSet::new();
        hash_set.insert(OptionBasicType {
            option_style: &self.option_style,
            side: &self.side,
            strike_price: &self.strike_price,
            expiration_date: &self.expiration_date,
        });
        hash_set
    }
    fn get_symbol(&self) -> &str {
        self.underlying_symbol.as_str()
    }
    fn get_strike(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        let option_basic_type = match self.get_option_basic_type().iter().next().copied() {
            Some(option_basic_type) => option_basic_type,
            None => return HashMap::new(),
        };
        HashMap::from([(option_basic_type, &self.strike_price)])
    }
    fn get_side(&self) -> HashMap<OptionBasicType<'_>, &Side> {
        let option_basic_type = match self.get_option_basic_type().iter().next().copied() {
            Some(option_basic_type) => option_basic_type,
            None => return HashMap::new(),
        };
        HashMap::from([(option_basic_type, &self.side)])
    }
    fn get_type(&self) -> &OptionType {
        &self.option_type
    }
    fn get_style(&self) -> HashMap<OptionBasicType<'_>, &OptionStyle> {
        let option_basic_type = match self.get_option_basic_type().iter().next().copied() {
            Some(option_basic_type) => option_basic_type,
            None => return HashMap::new(),
        };
        HashMap::from([(option_basic_type, &self.option_style)])
    }
    fn get_expiration(&self) -> HashMap<OptionBasicType<'_>, &ExpirationDate> {
        let option_basic_type = match self.get_option_basic_type().iter().next().copied() {
            Some(option_basic_type) => option_basic_type,
            None => return HashMap::new(),
        };
        HashMap::from([(option_basic_type, &self.expiration_date)])
    }
    fn get_implied_volatility(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        let option_basic_type = match self.get_option_basic_type().iter().next().copied() {
            Some(option_basic_type) => option_basic_type,
            None => return HashMap::new(),
        };
        HashMap::from([(option_basic_type, &self.implied_volatility)])
    }
    fn get_quantity(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        let option_basic_type = match self.get_option_basic_type().iter().next().copied() {
            Some(option_basic_type) => option_basic_type,
            None => return HashMap::new(),
        };
        HashMap::from([(option_basic_type, &self.quantity)])
    }
    fn get_underlying_price(&self) -> &Positive {
        &self.underlying_price
    }
    fn get_risk_free_rate(&self) -> HashMap<OptionBasicType<'_>, &Decimal> {
        let option_basic_type = match self.get_option_basic_type().iter().next().copied() {
            Some(option_basic_type) => option_basic_type,
            None => return HashMap::new(),
        };
        HashMap::from([(option_basic_type, &self.risk_free_rate)])
    }
    fn get_dividend_yield(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        let option_basic_type = match self.get_option_basic_type().iter().next().copied() {
            Some(option_basic_type) => option_basic_type,
            None => return HashMap::new(),
        };
        HashMap::from([(option_basic_type, &self.dividend_yield)])
    }
    fn one_option(&self) -> &Options {
        self
    }
    fn one_option_mut(&mut self) -> &mut Options {
        self
    }
    fn set_implied_volatility(&mut self, volatility: &Positive) -> Result<(), StrategyError> {
        self.implied_volatility = *volatility;
        Ok(())
    }
    fn set_underlying_price(&mut self, price: &Positive) -> Result<(), StrategyError> {
        self.underlying_price = *price;
        Ok(())
    }
    fn set_expiration_date(
        &mut self,
        expiration_date: ExpirationDate,
    ) -> Result<(), StrategyError> {
        self.expiration_date = expiration_date;
        Ok(())
    }
}

impl Graph for Options {
    fn graph_data(&self) -> GraphData {
        let range = calculate_optimal_price_range(
            self.underlying_price,
            self.strike_price,
            self.implied_volatility,
            self.expiration_date,
        )
        .unwrap_or_else(|_| {
            // Fallback to a reasonable default range based on strike price
            let lower = self.strike_price * Positive::new(0.5).unwrap_or(Positive::ONE);
            let upper = self.strike_price * Positive::new(1.5).unwrap_or(Positive::ONE);
            (lower, upper)
        });

        let mut positive_series = Series2D {
            x: vec![],
            y: vec![],
            name: "Positive Payoff".to_string(),
            mode: TraceMode::Lines,
            line_color: Some("#2ca02c".to_string()),
            line_width: Some(2.0),
        };
        let mut negative_series = Series2D {
            x: vec![],
            y: vec![],
            name: "Negative Payoff".to_string(),
            mode: TraceMode::Lines,
            line_color: Some("#FF0000".to_string()),
            line_width: Some(2.0),
        };

        for i in range.0.to_u64()..range.1.to_u64() {
            let profit = self
                .payoff_at_price(&Positive::new(i as f64).unwrap_or(Positive::ONE))
                .unwrap_or_default();
            match profit {
                p if p == Decimal::ZERO => {
                    positive_series
                        .x
                        .push(Decimal::from_u64(i).unwrap_or_default());
                    positive_series.y.push(profit);
                    negative_series
                        .x
                        .push(Decimal::from_u64(i).unwrap_or_default());
                    negative_series.y.push(profit);
                }
                p if p > Decimal::ZERO => {
                    positive_series
                        .x
                        .push(Decimal::from_u64(i).unwrap_or_default());
                    positive_series.y.push(profit);
                }
                _ => {
                    negative_series
                        .x
                        .push(Decimal::from_u64(i).unwrap_or_default());
                    negative_series.y.push(profit);
                }
            }
        }
        let multi_series_2d = vec![positive_series, negative_series];
        GraphData::MultiSeries(multi_series_2d)
    }

    fn graph_config(&self) -> GraphConfig {
        let title = self.get_title();
        let legend = Some(vec![title.clone()]);
        GraphConfig {
            title,
            width: 1600,
            height: 900,
            x_label: Some("Underlying Price".to_string()),
            y_label: Some("Profit/Loss".to_string()),
            z_label: None,
            line_style: LineStyle::Solid,
            color_scheme: ColorScheme::Default,
            legend,
            show_legend: false,
        }
    }
}

#[cfg(test)]
mod tests_options {
    use super::*;
    use crate::model::utils::create_sample_option_simplest;

    use approx::assert_relative_eq;
    use chrono::{Duration, Utc};
    use num_traits::ToPrimitive;
    use rust_decimal_macros::dec;

    #[test]
    fn test_new_option() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_eq!(option.underlying_symbol, "AAPL");
        assert_eq!(option.strike_price, 100.0);
        assert_eq!(option.implied_volatility, 0.2);
    }

    #[test]
    fn test_time_to_expiration() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_relative_eq!(
            option.time_to_expiration().unwrap().to_f64(),
            30.0 / 365.0,
            epsilon = 0.0001
        );

        let future_date = Utc::now() + Duration::days(60);
        let option_with_datetime = Options::new(
            OptionType::European,
            Side::Long,
            "AAPL".to_string(),
            Positive::HUNDRED,
            ExpirationDate::DateTime(future_date),
            pos_or_panic!(0.2),
            Positive::ONE,
            pos_or_panic!(105.0),
            dec!(0.05),
            OptionStyle::Call,
            pos_or_panic!(0.01),
            None,
        );
        assert!(option_with_datetime.time_to_expiration().unwrap() >= 59.0 / 365.0);
        assert!(option_with_datetime.time_to_expiration().unwrap() < 61.0 / 365.0);
    }

    #[test]
    fn test_is_long_and_short() {
        let long_option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert!(long_option.is_long());
        assert!(!long_option.is_short());

        let short_option = Options::new(
            OptionType::European,
            Side::Short,
            "AAPL".to_string(),
            Positive::HUNDRED,
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.2),
            Positive::ONE,
            pos_or_panic!(105.0),
            dec!(0.05),
            OptionStyle::Call,
            pos_or_panic!(0.01),
            None,
        );
        assert!(!short_option.is_long());
        assert!(short_option.is_short());
    }

    #[test]
    fn test_calculate_price_binomial() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let price = option.calculate_price_binomial(100).unwrap();
        assert!(price > Decimal::ZERO);
    }

    #[test]
    fn test_calculate_price_binomial_tree() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let (price, asset_tree, option_tree) = option.calculate_price_binomial_tree(5).unwrap();
        assert!(price > Decimal::ZERO);
        assert_eq!(asset_tree.len(), 6);
        assert_eq!(option_tree.len(), 6);
    }

    #[test]
    fn test_calculate_price_binomial_tree_short() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Short);
        let (price, asset_tree, option_tree) = option.calculate_price_binomial_tree(5).unwrap();
        assert!(price > Decimal::ZERO);
        assert_eq!(asset_tree.len(), 6);
        assert_eq!(option_tree.len(), 6);
    }

    #[test]
    fn test_calculate_price_black_scholes() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let price = option.calculate_price_black_scholes().unwrap();
        assert!(price > Decimal::ZERO);
    }

    #[test]
    fn test_payoff_european_call_long() {
        let call_option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let call_payoff = call_option.payoff().unwrap();
        assert_eq!(call_payoff, Decimal::ZERO); // max(100 - 100, 0) = 0

        let put_option = Options::new(
            OptionType::European,
            Side::Long,
            "AAPL".to_string(),
            Positive::HUNDRED,
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.2),
            Positive::ONE,
            pos_or_panic!(95.0),
            dec!(0.05),
            OptionStyle::Put,
            pos_or_panic!(0.01),
            None,
        );
        let put_payoff = put_option.payoff().unwrap();
        assert_eq!(put_payoff.to_f64().unwrap(), 5.0); // max(100 - 95, 0) = 5
    }

    #[test]
    fn test_calculate_time_value() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "AAPL".to_string(),
            Positive::HUNDRED,
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.2),
            Positive::ONE,
            pos_or_panic!(105.0),
            dec!(0.05),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );

        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value < option.calculate_price_black_scholes().unwrap());
    }
}

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

    use rust_decimal_macros::dec;

    fn create_valid_option() -> Options {
        Options {
            option_type: OptionType::European,
            side: Side::Long,
            underlying_symbol: "AAPL".to_string(),
            strike_price: Positive::HUNDRED,
            expiration_date: ExpirationDate::Days(pos_or_panic!(30.0)),
            implied_volatility: pos_or_panic!(0.2),
            quantity: Positive::ONE,
            underlying_price: pos_or_panic!(105.0),
            risk_free_rate: dec!(0.05),
            option_style: OptionStyle::Call,
            dividend_yield: pos_or_panic!(0.01),
            exotic_params: None,
        }
    }

    #[test]
    fn test_valid_option() {
        let option = create_valid_option();
        assert!(option.validate());
    }

    #[test]
    fn test_empty_underlying_symbol() {
        let mut option = create_valid_option();
        option.underlying_symbol = "".to_string();
        assert!(!option.validate());
    }

    #[test]
    fn test_zero_strike_price() {
        let mut option = create_valid_option();
        option.strike_price = Positive::ZERO;
        assert!(!option.validate());
    }

    #[test]
    fn test_zero_quantity() {
        let mut option = create_valid_option();
        option.quantity = Positive::ZERO;
        assert!(!option.validate());
    }

    #[test]
    fn test_zero_underlying_price() {
        let mut option = create_valid_option();
        option.underlying_price = Positive::ZERO;
        assert!(!option.validate());
    }
}

#[cfg(test)]
mod tests_time_value {
    use super::*;
    use crate::model::utils::create_sample_option_simplest_strike;

    use crate::assert_decimal_eq;
    use rust_decimal_macros::dec;
    use tracing::debug;

    #[test]
    fn test_calculate_time_value_long_call() {
        let option = create_sample_option_simplest_strike(
            Side::Long,
            OptionStyle::Call,
            pos_or_panic!(105.0),
        );
        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value <= option.calculate_price_black_scholes().unwrap());
    }

    #[test]
    fn test_calculate_time_value_short_call() {
        let option = create_sample_option_simplest_strike(
            Side::Short,
            OptionStyle::Call,
            pos_or_panic!(105.0),
        );
        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value <= option.calculate_price_black_scholes().unwrap().abs());
    }

    #[test]
    fn test_calculate_time_value_long_put() {
        let option =
            create_sample_option_simplest_strike(Side::Long, OptionStyle::Put, pos_or_panic!(95.0));
        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value <= option.calculate_price_black_scholes().unwrap());
    }

    #[test]
    fn test_calculate_time_value_short_put() {
        let option = create_sample_option_simplest_strike(
            Side::Short,
            OptionStyle::Put,
            pos_or_panic!(95.0),
        );
        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value <= option.calculate_price_black_scholes().unwrap().abs());
    }

    #[test]
    fn test_calculate_time_value_at_the_money() {
        let call =
            create_sample_option_simplest_strike(Side::Long, OptionStyle::Call, Positive::HUNDRED);
        let put =
            create_sample_option_simplest_strike(Side::Long, OptionStyle::Put, Positive::HUNDRED);

        let call_time_value = call.time_value().unwrap();
        let put_time_value = put.time_value().unwrap();

        assert!(call_time_value > Decimal::ZERO);
        assert!(put_time_value > Decimal::ZERO);
        assert_eq!(
            call_time_value,
            call.calculate_price_black_scholes().unwrap()
        );
        assert_eq!(put_time_value, put.calculate_price_black_scholes().unwrap());
    }

    #[test]
    fn test_calculate_time_value_deep_in_the_money() {
        let call = create_sample_option_simplest_strike(
            Side::Long,
            OptionStyle::Call,
            pos_or_panic!(150.0),
        );
        let put =
            create_sample_option_simplest_strike(Side::Long, OptionStyle::Put, pos_or_panic!(50.0));

        let call_time_value = call.time_value().unwrap();
        let put_time_value = put.time_value().unwrap();

        let call_price = call.calculate_price_black_scholes().unwrap();
        let put_price = put.calculate_price_black_scholes().unwrap();

        assert_decimal_eq!(call_time_value, call_price, dec!(0.01));
        assert_decimal_eq!(put_time_value, put_price, dec!(0.01));
        debug!("Call time value: {}", call_time_value);
        debug!("Call BS price: {}", call_price);
        debug!("Put time value: {}", put_time_value);
        debug!("Put BS price: {}", put_price);
        assert!(call_time_value <= call_price);
        assert!(put_time_value <= put_price);
    }
}

#[cfg(test)]
mod tests_options_payoffs {
    use super::*;
    use crate::model::utils::create_sample_option_simplest_strike;

    use rust_decimal_macros::dec;

    #[test]
    fn test_payoff_european_call_long() {
        let call_option = create_sample_option_simplest_strike(
            Side::Long,
            OptionStyle::Call,
            pos_or_panic!(95.0),
        );
        let call_payoff = call_option.payoff().unwrap();
        assert_eq!(call_payoff, dec!(5.0)); // max(100 - 95, 0) = 5

        let call_option_otm = create_sample_option_simplest_strike(
            Side::Long,
            OptionStyle::Call,
            pos_or_panic!(105.0),
        );
        let call_payoff_otm = call_option_otm.payoff().unwrap();
        assert_eq!(call_payoff_otm, Decimal::ZERO); // max(100 - 105, 0) = 0
    }

    #[test]
    fn test_payoff_european_call_short() {
        let call_option = create_sample_option_simplest_strike(
            Side::Short,
            OptionStyle::Call,
            pos_or_panic!(95.0),
        );
        let call_payoff = call_option.payoff().unwrap();
        assert_eq!(call_payoff, dec!(-5.0)); // -max(100 - 95, 0) = -5

        let call_option_otm = create_sample_option_simplest_strike(
            Side::Short,
            OptionStyle::Call,
            pos_or_panic!(105.0),
        );
        let call_payoff_otm = call_option_otm.payoff().unwrap();
        assert_eq!(call_payoff_otm, Decimal::ZERO); // -max(95 - 100, 0) = 0
    }

    #[test]
    fn test_payoff_european_put_long() {
        let put_option = create_sample_option_simplest_strike(
            Side::Long,
            OptionStyle::Put,
            pos_or_panic!(105.0),
        );
        let put_payoff = put_option.payoff().unwrap();
        assert_eq!(put_payoff, dec!(5.0)); // max(105 - 100, 0) = 5

        let put_option_otm =
            create_sample_option_simplest_strike(Side::Long, OptionStyle::Put, pos_or_panic!(95.0));
        let put_payoff_otm = put_option_otm.payoff().unwrap();
        assert_eq!(put_payoff_otm, Decimal::ZERO); // max(95 - 100, 0) = 0
    }

    #[test]
    fn test_payoff_european_put_short() {
        let put_option = create_sample_option_simplest_strike(
            Side::Short,
            OptionStyle::Put,
            pos_or_panic!(105.0),
        );
        let put_payoff = put_option.payoff().unwrap();
        assert_eq!(put_payoff, dec!(-5.0)); // -max(105 - 100, 0) = -5

        let put_option_otm = create_sample_option_simplest_strike(
            Side::Short,
            OptionStyle::Put,
            pos_or_panic!(95.0),
        );
        let put_payoff_otm = put_option_otm.payoff().unwrap();
        assert_eq!(put_payoff_otm, Decimal::ZERO); // -max(95 - 100, 0) = 0
    }
}

#[cfg(test)]
mod tests_options_payoff_at_price {
    use super::*;
    use crate::model::utils::create_sample_option_simplest;

    use rust_decimal_macros::dec;

    #[test]
    fn test_payoff_european_call_long() {
        let call_option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let call_payoff = call_option.payoff_at_price(&pos_or_panic!(105.0)).unwrap();
        assert_eq!(call_payoff, dec!(5.0)); // max(105 - 100, 0) = 5

        let call_option_otm = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let call_payoff_otm = call_option_otm
            .payoff_at_price(&pos_or_panic!(95.0))
            .unwrap();
        assert_eq!(call_payoff_otm, Decimal::ZERO); // max(95 - 100, 0) = 0
    }

    #[test]
    fn test_payoff_european_call_short() {
        let call_option = create_sample_option_simplest(OptionStyle::Call, Side::Short);
        let call_payoff = call_option.payoff_at_price(&pos_or_panic!(105.0)).unwrap();
        assert_eq!(call_payoff, dec!(-5.0)); // -max(105 - 100, 0) = -5

        let call_option_otm = create_sample_option_simplest(OptionStyle::Call, Side::Short);
        let call_payoff_otm = call_option_otm
            .payoff_at_price(&pos_or_panic!(95.0))
            .unwrap();
        assert_eq!(call_payoff_otm, Decimal::ZERO); // -max(95 - 100, 0) = 0
    }

    #[test]
    fn test_payoff_european_put_long() {
        let put_option = create_sample_option_simplest(OptionStyle::Put, Side::Long);
        let put_payoff = put_option.payoff_at_price(&pos_or_panic!(95.0)).unwrap();
        assert_eq!(put_payoff, dec!(5.0)); // max(100 - 95, 0) = 5

        let put_option_otm = create_sample_option_simplest(OptionStyle::Put, Side::Long);
        let put_payoff_otm = put_option_otm
            .payoff_at_price(&pos_or_panic!(105.0))
            .unwrap();
        assert_eq!(put_payoff_otm, Decimal::ZERO); // max(100 - 105, 0) = 0
    }

    #[test]
    fn test_payoff_european_put_short() {
        let put_option = create_sample_option_simplest(OptionStyle::Put, Side::Short);
        let put_payoff = put_option.payoff_at_price(&pos_or_panic!(95.0)).unwrap();
        assert_eq!(put_payoff, dec!(-5.0)); // -max(100 - 95, 0) = -5

        let put_option_otm = create_sample_option_simplest(OptionStyle::Put, Side::Short);
        let put_payoff_otm = put_option_otm
            .payoff_at_price(&pos_or_panic!(105.0))
            .unwrap();
        assert_eq!(put_payoff_otm, Decimal::ZERO); // -max(100 - 105, 0) = 0
    }
}

#[cfg(test)]
mod tests_options_payoffs_with_quantity {
    use super::*;
    use crate::model::utils::create_sample_option;

    use num_traits::ToPrimitive;
    use rust_decimal_macros::dec;

    #[test]
    fn test_payoff_call_long() {
        let option = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            pos_or_panic!(105.0),
            pos_or_panic!(10.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(option.payoff().unwrap().to_f64().unwrap(), 50.0);

        let option_otm = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            pos_or_panic!(95.0),
            pos_or_panic!(4.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(option_otm.payoff().unwrap(), Decimal::ZERO);
    }

    #[test]
    fn test_payoff_call_short() {
        let option = create_sample_option(
            OptionStyle::Call,
            Side::Short,
            pos_or_panic!(105.0),
            pos_or_panic!(3.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(option.payoff().unwrap().to_f64().unwrap(), -15.0);

        let option_otm = create_sample_option(
            OptionStyle::Call,
            Side::Short,
            pos_or_panic!(95.0),
            pos_or_panic!(7.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(option_otm.payoff().unwrap(), Decimal::ZERO);
    }

    #[test]
    fn test_payoff_put_long() {
        let option = create_sample_option(
            OptionStyle::Put,
            Side::Long,
            pos_or_panic!(95.0),
            Positive::TWO,
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(option.payoff().unwrap().to_f64().unwrap(), 10.0);

        let option_otm = create_sample_option(
            OptionStyle::Put,
            Side::Long,
            pos_or_panic!(105.0),
            pos_or_panic!(7.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(option_otm.payoff().unwrap(), Decimal::ZERO);
    }

    #[test]
    fn test_payoff_put_short() {
        let option = create_sample_option(
            OptionStyle::Put,
            Side::Short,
            pos_or_panic!(95.0),
            pos_or_panic!(3.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(option.payoff().unwrap().to_f64().unwrap(), -15.0);

        let option_otm = create_sample_option(
            OptionStyle::Put,
            Side::Short,
            pos_or_panic!(105.0),
            pos_or_panic!(3.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(option_otm.payoff().unwrap(), Decimal::ZERO);
    }

    #[test]
    fn test_payoff_with_quantity() {
        let option = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            pos_or_panic!(110.0),
            pos_or_panic!(3.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(option.payoff().unwrap().to_f64().unwrap(), 30.0); // (110 - 100) * 3
    }

    #[test]
    fn test_intrinsic_value_call_long() {
        let option = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            Positive::HUNDRED,
            pos_or_panic!(11.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(
            option.intrinsic_value(pos_or_panic!(105.0)).unwrap(),
            dec!(55.0)
        );
        assert_eq!(
            option.intrinsic_value(pos_or_panic!(95.0)).unwrap(),
            Decimal::ZERO
        );
    }

    #[test]
    fn test_intrinsic_value_call_short() {
        let option = create_sample_option(
            OptionStyle::Call,
            Side::Short,
            Positive::HUNDRED,
            pos_or_panic!(13.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(
            option.intrinsic_value(pos_or_panic!(105.0)).unwrap(),
            dec!(-65.0)
        );
        assert_eq!(
            option.intrinsic_value(pos_or_panic!(95.0)).unwrap(),
            Decimal::ZERO
        );
    }

    #[test]
    fn test_intrinsic_value_put_long() {
        let option = create_sample_option(
            OptionStyle::Put,
            Side::Long,
            Positive::HUNDRED,
            pos_or_panic!(17.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(
            option.intrinsic_value(pos_or_panic!(95.0)).unwrap(),
            dec!(85.0)
        );
        assert_eq!(
            option.intrinsic_value(pos_or_panic!(105.0)).unwrap(),
            Decimal::ZERO
        );
    }

    #[test]
    fn test_intrinsic_value_put_short() {
        let option = create_sample_option(
            OptionStyle::Put,
            Side::Short,
            Positive::HUNDRED,
            pos_or_panic!(19.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(
            option.intrinsic_value(pos_or_panic!(95.0)).unwrap(),
            dec!(-95.0)
        );
        assert_eq!(
            option.intrinsic_value(pos_or_panic!(105.0)).unwrap(),
            Decimal::ZERO
        );
    }

    #[test]
    fn test_intrinsic_value_with_quantity() {
        let option = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            Positive::HUNDRED,
            pos_or_panic!(23.0),
            Positive::HUNDRED,
            pos_or_panic!(0.02),
        );
        assert_eq!(
            option.intrinsic_value(pos_or_panic!(110.0)).unwrap(),
            dec!(230.0)
        ); // (110 - 100) * 23
    }
}

#[cfg(test)]
mod tests_in_the_money {
    use super::*;
    use crate::model::utils::create_sample_option;

    #[test]
    fn test_call_in_the_money() {
        let mut option = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            pos_or_panic!(110.0),
            Positive::ONE,
            pos_or_panic!(110.0),
            pos_or_panic!(0.02),
        );
        option.strike_price = Positive::HUNDRED;
        assert!(option.is_in_the_money());
    }

    #[test]
    fn test_call_at_the_money() {
        let mut option = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            Positive::HUNDRED,
            Positive::ONE,
            pos_or_panic!(110.0),
            pos_or_panic!(0.02),
        );
        option.strike_price = Positive::HUNDRED;
        assert!(option.is_in_the_money());
    }

    #[test]
    fn test_call_out_of_the_money() {
        let mut option = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            pos_or_panic!(90.0),
            Positive::ONE,
            pos_or_panic!(110.0),
            pos_or_panic!(0.02),
        );
        option.strike_price = Positive::HUNDRED;
        assert!(!option.is_in_the_money());
    }

    #[test]
    fn test_put_in_the_money() {
        let mut option = create_sample_option(
            OptionStyle::Put,
            Side::Long,
            pos_or_panic!(90.0),
            Positive::ONE,
            pos_or_panic!(110.0),
            pos_or_panic!(0.02),
        );
        option.strike_price = Positive::HUNDRED;
        assert!(option.is_in_the_money());
    }

    #[test]
    fn test_put_at_the_money() {
        let mut option = create_sample_option(
            OptionStyle::Put,
            Side::Long,
            Positive::HUNDRED,
            Positive::ONE,
            pos_or_panic!(110.0),
            pos_or_panic!(0.02),
        );
        option.strike_price = Positive::HUNDRED;
        assert!(option.is_in_the_money());
    }

    #[test]
    fn test_put_out_of_the_money() {
        let mut option = create_sample_option(
            OptionStyle::Put,
            Side::Long,
            pos_or_panic!(110.0),
            Positive::ONE,
            pos_or_panic!(110.0),
            pos_or_panic!(0.02),
        );
        option.strike_price = Positive::HUNDRED;
        assert!(!option.is_in_the_money());
    }
}

#[cfg(test)]
mod tests_greeks {
    use super::*;
    use crate::assert_decimal_eq;
    use crate::model::utils::create_sample_option_simplest;
    use rust_decimal_macros::dec;

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

    #[test]
    fn test_delta() {
        let delta = create_sample_option_simplest(OptionStyle::Call, Side::Long)
            .delta()
            .unwrap();
        assert_decimal_eq!(delta, dec!(0.539519922), EPSILON);
    }

    #[test]
    fn test_delta_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.delta().unwrap(), dec!(1.0790398), EPSILON);
    }

    #[test]
    fn test_gamma() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.gamma().unwrap(), dec!(0.0691707), EPSILON);
    }

    #[test]
    fn test_gamma_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.gamma().unwrap(), dec!(0.1383415), EPSILON);
    }

    #[test]
    fn test_theta() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.theta().unwrap(), dec!(-0.043510019), EPSILON);
    }

    #[test]
    fn test_theta_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.theta().unwrap(), dec!(-0.0870200), EPSILON);
    }

    #[test]
    fn test_vega() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.vega().unwrap(), dec!(0.113705366), EPSILON);
    }

    #[test]
    fn test_vega_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.vega().unwrap(), dec!(0.2274107), EPSILON);
    }

    #[test]
    fn test_rho() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.rho().unwrap(), dec!(0.0423312145), EPSILON);
    }

    #[test]
    fn test_rho_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.rho().unwrap(), dec!(0.08466242), EPSILON);
    }

    #[test]
    fn test_rho_d() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.rho_d().unwrap(), dec!(-0.04434410320), EPSILON);
    }

    #[test]
    fn test_rho_d_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.rho_d().unwrap(), dec!(-0.0886882064063), EPSILON);
    }

    #[test]
    fn test_vanna() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.vanna().unwrap(), dec!(-0.085279024623), EPSILON);
    }

    #[test]
    fn test_vanna_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.vanna().unwrap(), dec!(-0.170558049246), EPSILON);
    }

    #[test]
    fn test_vomma() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.vomma().unwrap(), dec!(0.002453232215), EPSILON);
    }

    #[test]
    fn test_vomma_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.vomma().unwrap(), dec!(0.009812928860), EPSILON);
    }

    #[test]
    fn test_veta() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.veta().unwrap(), dec!(0.000027206189), EPSILON);
    }

    #[test]
    fn test_veta_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.veta().unwrap(), dec!(0.000108824758), EPSILON);
    }

    #[test]
    fn test_charm() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.charm().unwrap(), dec!(-0.000458), EPSILON);
    }

    #[test]
    fn test_charm_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.charm().unwrap(), dec!(-0.000917), EPSILON);
    }

    #[test]
    fn test_color() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        assert_decimal_eq!(option.color().unwrap(), dec!(-0.001163), EPSILON);
    }

    #[test]
    fn test_color_size() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.quantity = Positive::TWO;
        assert_decimal_eq!(option.color().unwrap(), dec!(-0.002326), EPSILON);
    }
}

#[cfg(test)]
mod tests_greek_trait {
    use super::*;
    use crate::assert_decimal_eq;
    use crate::model::utils::create_sample_option_simplest;
    use rust_decimal_macros::dec;

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

    #[test]
    fn test_greeks_implementation() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let greeks = option.greeks().unwrap();

        assert_decimal_eq!(greeks.delta, option.delta().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.gamma, option.gamma().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.theta, option.theta().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.vega, option.vega().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.rho, option.rho().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.rho_d, option.rho_d().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.vanna, option.vanna().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.vomma, option.vomma().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.veta, option.veta().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.charm, option.charm().unwrap(), EPSILON);
        assert_decimal_eq!(greeks.color, option.color().unwrap(), EPSILON);
    }

    #[test]
    fn test_greeks_consistency() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let greeks = option.greeks().unwrap();

        assert!(
            greeks.delta >= Decimal::NEGATIVE_ONE && greeks.delta <= Decimal::ONE,
            "Delta should be between -1 and 1"
        );
        assert!(
            greeks.gamma >= Decimal::ZERO,
            "Gamma should be non-negative"
        );
        assert!(greeks.vega >= Decimal::ZERO, "Vega should be non-negative");
    }

    #[test]
    fn test_greeks_for_different_options() {
        let call_option = Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            pos_or_panic!(5790.0), // strike
            ExpirationDate::Days(pos_or_panic!(18.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(5781.88), // underlying
            dec!(0.05),             // rate
            OptionStyle::Call,
            Positive::ZERO, // div
            None,
        );
        let mut put_option = call_option.clone();
        put_option.option_style = OptionStyle::Put;

        let call_greeks = call_option.greeks().unwrap();
        let put_greeks = put_option.greeks().unwrap();

        assert_decimal_eq!(
            call_greeks.delta + put_greeks.delta.abs(),
            Decimal::ONE,
            EPSILON
        );
        assert_decimal_eq!(call_greeks.gamma, put_greeks.gamma, EPSILON);
        assert_decimal_eq!(call_greeks.vega, put_greeks.vega, EPSILON);
    }
}

#[cfg(test)]
mod tests_calculate_price_binomial {
    use super::*;
    use crate::model::utils::{
        create_sample_option, create_sample_option_simplest, create_sample_option_with_date,
    };

    use chrono::Utc;
    use rust_decimal_macros::dec;
    use std::str::FromStr;

    #[test]
    fn test_european_call_option_basic() {
        // Test a basic European call option with standard parameters
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let result = option.calculate_price_binomial(100);
        assert!(result.is_ok());
        let price = result.unwrap();
        // Price should be positive for a long call at-the-money
        assert!(price > Decimal::ZERO);
    }

    #[test]
    fn test_american_put_option() {
        // Test American put option which should have early exercise value
        let option = Options::new(
            OptionType::American,
            Side::Long,
            "TEST".to_string(),
            Positive::HUNDRED,
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.2),  // volatility
            Positive::ONE,       // quantity
            pos_or_panic!(95.0), // underlying price (slightly ITM for put)
            dec!(0.05),          // risk-free rate
            OptionStyle::Put,
            Positive::ZERO, // dividend yield
            None,
        );

        let result = option.calculate_price_binomial(100);
        assert!(result.is_ok());
        let price = result.unwrap();
        // Price should be positive and reflect early exercise premium
        assert!(price > Decimal::ZERO);
    }

    #[test]
    fn test_zero_volatility() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.implied_volatility = Positive::ZERO;
        let result = option.calculate_price_binomial(100);
        assert!(result.is_ok());
        // With zero volatility, price should equal discounted intrinsic value
    }

    #[test]
    fn test_zero_time_to_expiry() {
        // Test option at expiration
        let now = Utc::now().naive_utc();
        let option = create_sample_option_with_date(
            OptionStyle::Call,
            Side::Long,
            Positive::HUNDRED,
            Positive::ONE,
            pos_or_panic!(95.0),
            pos_or_panic!(0.2),
            now,
        );

        let result = option.calculate_price_binomial(100);
        assert!(result.is_ok());
        let price = result.unwrap();
        // At expiry, price should equal intrinsic value
        assert_eq!(price, Decimal::from(5));
    }

    #[test]
    fn test_invalid_steps() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let result = option.calculate_price_binomial(0);
        assert!(result.is_err());
    }

    #[test]
    fn test_deep_itm_call() {
        let option = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            pos_or_panic!(150.0), // Underlying price much higher than strike
            Positive::ONE,
            Positive::HUNDRED,
            pos_or_panic!(0.2),
        );

        let result = option.calculate_price_binomial(100);
        assert!(result.is_ok());
        let price = result.unwrap();
        // Price should be close to intrinsic value for deep ITM
        assert!(price > Decimal::from(45)); // At least intrinsic - some time value
    }

    #[test]
    fn test_deep_otm_put() {
        let option = create_sample_option(
            OptionStyle::Put,
            Side::Long,
            pos_or_panic!(150.0), // Underlying price much higher than strike
            Positive::ONE,
            Positive::HUNDRED,
            pos_or_panic!(0.2),
        );

        let result = option.calculate_price_binomial(100);
        assert!(result.is_ok());
        let price = result.unwrap();
        // Price should be very small for deep OTM
        assert!(price < Decimal::from(1));
    }

    #[test]
    fn test_convergence() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);

        // Test that increasing steps leads to convergence
        let price_100 = option.calculate_price_binomial(100).unwrap();
        let price_1000 = option.calculate_price_binomial(1000).unwrap();

        // Prices should be close to each other
        let diff = (price_1000 - price_100).abs();
        assert!(diff < Decimal::from_str("0.1").unwrap());
    }

    #[test]
    fn test_short_position() {
        let long_call_option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let mut short_call_option = long_call_option.clone();
        short_call_option.side = Side::Short;
        let mut short_put_option = short_call_option.clone();
        short_put_option.option_style = OptionStyle::Put;
        let mut long_put_option = short_put_option.clone();
        long_put_option.side = Side::Long;

        let long_call_price = long_call_option.calculate_price_binomial(100).unwrap();
        let short_call_price = short_call_option.calculate_price_binomial(100).unwrap();
        let long_put_price = long_put_option.calculate_price_binomial(100).unwrap();
        let short_put_price = short_put_option.calculate_price_binomial(100).unwrap();

        // Short position should be negative of long position
        assert_eq!(long_call_price, -short_call_price);
        assert_eq!(long_put_price, -short_put_price);
    }
}

#[cfg(test)]
mod tests_options_black_scholes {
    use super::*;
    use crate::assert_decimal_eq;
    use rust_decimal_macros::dec;

    #[test]
    fn test_new_option_call() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "SP500".to_string(),
            pos_or_panic!(5790.0),
            ExpirationDate::Days(pos_or_panic!(18.0)),
            pos_or_panic!(0.1117),
            Positive::ONE,
            pos_or_panic!(5781.88),
            dec!(0.05),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            pos_or_panic!(60.306_765_882_668_3),
            dec!(1e-8)
        );
    }

    #[test]
    fn test_new_option_call_bis() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "SP500".to_string(),
            pos_or_panic!(6050.0),
            ExpirationDate::Days(pos_or_panic!(61.2)),
            pos_or_panic!(0.12594),
            Positive::ONE,
            pos_or_panic!(6032.18),
            dec!(0.0),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            pos_or_panic!(115.56),
            dec!(1e-2)
        );
    }

    #[test]
    fn test_new_option_put() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "SP500".to_string(),
            pos_or_panic!(6050.0),
            ExpirationDate::Days(pos_or_panic!(61.2)),
            pos_or_panic!(0.1258),
            Positive::ONE,
            pos_or_panic!(6032.18),
            dec!(0.0),
            OptionStyle::Put,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            pos_or_panic!(133.25),
            dec!(1e-2)
        );
    }

    #[test]
    fn test_new_option_call_short() {
        let option = Options::new(
            OptionType::European,
            Side::Short,
            "SP500".to_string(),
            pos_or_panic!(6050.0),
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.12594),
            Positive::ONE,
            pos_or_panic!(6032.18),
            dec!(0.0),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            dec!(-114.34),
            dec!(1e-2)
        );
    }

    #[test]
    fn test_new_option_put_short() {
        let option = Options::new(
            OptionType::European,
            Side::Short,
            "SP500".to_string(),
            pos_or_panic!(6050.0),
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.12594),
            Positive::ONE,
            pos_or_panic!(6032.18),
            dec!(0.0),
            OptionStyle::Put,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            dec!(-132.16),
            dec!(1e-2)
        );
    }
}

#[cfg(test)]
mod tests_calculate_implied_volatility {
    use super::*;
    use crate::error::VolatilityError;
    use positive::assert_pos_relative_eq;
    use rust_decimal_macros::dec;

    #[test]
    fn test_implied_volatility_call() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            pos_or_panic!(5790.0), // strike
            ExpirationDate::Days(pos_or_panic!(18.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(5781.88), // underlying
            dec!(0.05),             // rate
            OptionStyle::Call,
            Positive::ZERO, // div
            None,
        );

        let market_price = dec!(60.30);
        let iv = option.calculate_implied_volatility(market_price).unwrap();

        assert_pos_relative_eq!(
            iv,
            pos_or_panic!(0.111618041),
            Positive::new_decimal(IV_TOLERANCE).unwrap()
        );
    }

    #[test]
    fn test_implied_volatility_put() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            pos_or_panic!(6050.0), // strike
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(6032.18), // underlying
            dec!(0.0),              // rate
            OptionStyle::Put,
            Positive::ZERO, // div
            None,
        );

        let market_price = dec!(132.16);
        let iv = option.calculate_implied_volatility(market_price).unwrap();
        assert_pos_relative_eq!(
            iv,
            pos_or_panic!(0.125961),
            Positive::new_decimal(IV_TOLERANCE).unwrap()
        );
    }

    #[test]
    fn test_implied_volatility_call_short() {
        let option = Options::new(
            OptionType::European,
            Side::Short,
            "TEST".to_string(),
            pos_or_panic!(6050.0), // strike
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(6032.18), // underlying
            dec!(0.0),              // rate
            OptionStyle::Call,
            Positive::ZERO, // div
            None,
        );

        let market_price = dec!(-114.16);
        let iv = option.calculate_implied_volatility(market_price).unwrap();

        assert_pos_relative_eq!(
            iv,
            pos_or_panic!(0.1258087),
            Positive::new_decimal(IV_TOLERANCE).unwrap()
        );
    }

    #[test]
    fn test_implied_volatility_put_short() {
        let option = Options::new(
            OptionType::European,
            Side::Short,
            "TEST".to_string(),
            pos_or_panic!(6050.0), // strike
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(6032.18), // underlying
            dec!(0.0),              // rate
            OptionStyle::Put,
            Positive::ZERO, // div
            None,
        );

        let market_price = dec!(-132.27);
        let iv = option.calculate_implied_volatility(market_price).unwrap();
        assert_pos_relative_eq!(
            iv,
            pos_or_panic!(0.12611389),
            Positive::new_decimal(IV_TOLERANCE).unwrap()
        );
    }

    #[test]
    fn test_invalid_market_price() {
        let option = Options::default();
        let result = option.calculate_implied_volatility(Decimal::ZERO);
        assert!(matches!(result, Err(VolatilityError::Options(_))));
    }

    #[test]
    fn test_expired_option() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            Positive::HUNDRED,
            ExpirationDate::Days(Positive::ZERO),
            pos_or_panic!(0.2),
            Positive::ONE,
            Positive::HUNDRED,
            dec!(0.05),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );

        let result = option.calculate_implied_volatility(dec!(2.5));
        assert!(matches!(result, Err(VolatilityError::Options(_))));
    }

    #[test]
    fn test_convergence_edge_cases() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            pos_or_panic!(5790.0), // strike
            ExpirationDate::Days(pos_or_panic!(18.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(5781.88), // underlying
            dec!(0.05),             // rate
            OptionStyle::Call,
            Positive::ZERO, // div
            None,
        );

        // Test with small initial vol
        let iv = option.calculate_implied_volatility(dec!(60.30)).unwrap();
        assert_pos_relative_eq!(iv, pos_or_panic!(0.111328125), pos_or_panic!(0.01));

        // Test with large initial vol
        let iv = option.calculate_implied_volatility(dec!(60.30)).unwrap();
        assert_pos_relative_eq!(iv, pos_or_panic!(0.111328125), pos_or_panic!(0.01));
    }
}

#[cfg(test)]
mod tests_serialize_deserialize {
    use super::*;
    use crate::model::utils::create_sample_option_simplest_strike;

    #[test]
    fn test_serialize_deserialize_options() {
        let options = create_sample_option_simplest_strike(
            Side::Long,
            OptionStyle::Call,
            pos_or_panic!(95.0),
        );
        let serialized = serde_json::to_string(&options).expect("Failed to serialize");
        let deserialized: Options =
            serde_json::from_str(&serialized).expect("Failed to deserialize");
        assert_eq!(options, deserialized);
    }
}