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
// Per rules/global_rules.md §Error Handling, unchecked `[]` / slicing is
// banned in production code. Enforced crate-wide; individual modules that
// need a transitional escape hatch carry a scoped `#![allow(..)]` with a
// migration note (tracked as follow-ups to #341).
// Unit and integration tests routinely index into `Vec`s they just pushed
// into, so the lint is silenced in `#[cfg(test)]` only.
//! # OptionStratLib v0.17.0: Financial Options Library
//!
//! ## Table of Contents
//! 1. [Introduction](#introduction)
//! 2. [Features](#features)
//! 3. [Core Modules](#core-modules)
//! 4. [Trading Strategies](#trading-strategies)
//! 5. [Setup Instructions](#setup-instructions)
//! 6. [Library Usage](#library-usage)
//! 7. [Usage Examples](#usage-examples)
//! 8. [Testing](#testing)
//! 9. [Contribution and Contact](#contribution-and-contact)
//!
//! ## Introduction
//!
//! OptionStratLib is a comprehensive Rust library for options trading and strategy development across multiple asset classes.
//! This versatile toolkit enables traders, quants, and developers to model, analyze, and visualize options strategies with a
//! robust, type-safe approach. The library focuses on precision with decimal-based calculations, extensive test coverage,
//! and a modular architecture built on modern Rust 2024 edition.
//!
//! ## Features
//!
//! ### 1. **Pricing Models**
//! - **Black-Scholes Model**: European options pricing with full Greeks support
//! - **Binomial Tree Model**: American and European options with early exercise capability
//! - **Monte Carlo Simulations**: Complex pricing scenarios and path-dependent options
//! - **Telegraph Process Model**: Advanced stochastic modeling for jump-diffusion processes
//! - **American Options**: Barone-Adesi-Whaley approximation for early exercise
//! - **Exotic Options**: Complete support for 14 exotic option types (see below)
//!
//! ### 2. **Greeks Calculation**
//! - Complete Greeks suite: Delta, Gamma, Theta, Vega, Rho, Vanna, Vomma, Veta,
//! Charm, Color
//! - Real-time sensitivity analysis
//! - Greeks visualization and risk profiling
//! - Custom Greeks implementations with adjustable parameters
//!
//! ### 3. **Volatility Models**
//! - Implied volatility calculation using Newton-Raphson method
//! - Volatility surface construction and interpolation
//! - Historical volatility estimation
//! - Advanced volatility modeling tools
//!
//! ### 4. **Option Chain Management**
//! - Complete option chain construction and analysis
//! - Strike price generation algorithms
//! - Chain data import/export (CSV/JSON formats)
//! - Advanced filtering and selection tools
//! - Option data grouping and organization
//!
//! ### 5. **Trading Strategies (25+ Strategies)**
//! - **Single Leg**: Long/Short Calls and Puts
//! - **Spreads**: Bull/Bear Call/Put Spreads
//! - **Butterflies**: Long/Short Butterfly Spreads, Call Butterfly
//! - **Complex**: Iron Condor, Iron Butterfly
//! - **Volatility**: Long/Short Straddles and Strangles
//! - **Income**: Covered Calls (with spot leg support), Poor Man's Covered Call
//! - **Protection**: Protective Puts, Collars
//! - **Custom**: Flexible custom strategy framework
//! - **Multi-Asset**: Strategies combining options with spot, futures, or perpetuals
//!
//! ### 6. **Risk Management & Analysis**
//! - Position tracking and management
//! - Break-even analysis with multiple break-even points
//! - Profit/Loss calculations at various price points
//! - Risk profiles and comprehensive visualizations
//! - Delta neutrality analysis and adjustment
//! - Probability analysis for strategy outcomes
//!
//! ### 7. **Backtesting Framework**
//! - Comprehensive backtesting engine
//! - Performance metrics calculation
//! - Strategy optimization tools
//! - Historical analysis capabilities
//!
//! ### 8. **Simulation Tools**
//! - Monte Carlo simulations for strategy testing
//! - Telegraph process implementation
//! - Random walk simulations
//! - Custom simulation frameworks
//! - Parametrized simulations with adjustable inputs
//!
//! ### 9. **Visualization & Plotting**
//! - Strategy payoff diagrams
//! - Greeks visualization
//! - 3D volatility surfaces
//! - Risk profiles and P&L charts
//! - Interactive charts (powered by `plotly.rs`)
//! - Binomial tree visualization
//! - Comprehensive plotting utilities
//!
//! ### 10. **Data Management**
//! - Efficient decimal-based calculations using `rust_decimal`
//! - CSV/JSON import/export functionality
//! - Time series data handling
//! - Price series management and manipulation
//! - Robust data validation and error handling
//!
//! ### 11. **Mathematical Tools**
//! - Curve interpolation techniques
//! - Surface construction and analysis
//! - Geometric operations for financial modeling
//! - Advanced mathematical utilities for options pricing
//!
//! ### 12. **Exotic Option Pricing**
//! Complete pricing support for all exotic option types:
//! - **Asian**: Arithmetic and geometric average price options
//! - **Barrier**: Up/Down, In/Out barrier options with rebates
//! - **Binary**: Cash-or-nothing and asset-or-nothing options
//! - **Lookback**: Fixed and floating strike lookback options
//! - **Compound**: Options on options
//! - **Chooser**: Options to choose call or put at future date
//! - **Cliquet**: Forward-starting options with local caps/floors
//! - **Rainbow**: Multi-asset best-of/worst-of options
//! - **Spread**: Kirk's approximation for price differentials
//! - **Quanto**: Currency-protected options
//! - **Exchange**: Margrabe's formula for asset exchange
//! - **Power**: Non-linear payoff options
//!
//! ## Quality & Discipline (0.16.x)
//!
//! The 0.16 line is a quality-hardening release. Every change below is
//! enforced crate-wide and documented in `CHANGELOG.md`:
//!
//! - **Checked `Decimal` arithmetic.** Every monetary-path kernel routes
//! through `d_add` / `d_sub` / `d_mul` / `d_div` / `d_sum` /
//! `d_sum_iter` in `model::decimal`. Overflow on any monetary
//! expression surfaces `DecimalError::Overflow { operation, lhs, rhs }`
//! tagged with a static call-site string; no silent wraparound.
//! - **Non-finite `f64` guards.** Every `f64 → Decimal` boundary inside
//! pricing, Greeks, volatility, and simulation is wrapped with
//! `finite_decimal(..)` and surfaces a domain-specific
//! `NonFinite { context, value }` variant
//! (`PricingError`, `GreeksError`, `VolatilityError`,
//! `SimulationError`) instead of collapsing silently to
//! `Decimal::ZERO`.
//! - **`NonZeroUsize` step counts.** `price_binomial`,
//! `monte_carlo_option_pricing`, `telegraph` and related kernels take
//! `std::num::NonZeroUsize` for `steps` / `simulations`; zero is
//! structurally invalid at the type level. Use the `nz!(N)` macro
//! at literal call sites.
//! - **`Positive` at every public boundary.** Monetary values,
//! strikes, quantities, volatilities are `Positive` (newtype around
//! `Decimal`). Strategy-level P&L goes through
//! `Positive::new_decimal(..)` at every point where a signed
//! `Decimal` would otherwise be clamped to `Positive`, so inverted
//! strikes or out-of-range optimizer candidates return typed
//! `StrategyError` rather than panicking.
//! - **Zero unchecked indexing in production code.**
//! `#![deny(clippy::indexing_slicing)]` is enforced crate-wide with
//! scoped, documented escapes per module. Tests stay permissive via
//! `#![cfg_attr(test, allow(..))]`. Production paths use
//! `.get(..).ok_or_else(..)` with typed errors.
//! - **Doc coverage floor.** `#![deny(missing_docs,
//! rustdoc::broken_intra_doc_links)]`. Every `pub` item has a `///`
//! summary; every `Result` returner documents its `# Errors`
//! contract.
//! - **Structured tracing.** `#[tracing::instrument]` on the public
//! hot paths: `pricing::black_scholes`,
//! `pricing::monte_carlo_option_pricing`,
//! `pricing::price_binomial`, `volatility::implied_volatility`,
//! and the strategy optimizer entry points
//! `get_best_ratio` / `get_best_area`. No `println!` / `eprintln!`
//! / `dbg!` / `log::` anywhere in `src/`.
//! - **Compiler-attribute discipline.** `#[must_use]` on every pure
//! function and builder, `#[inline]` on small hot-path helpers,
//! `#[cold] #[inline(never)]` on every error constructor,
//! `#[repr(u8)]` on small stable enums, canonical `#[derive]`
//! ordering.
//! - **Deterministic simulation tests.** `utils::deterministic_rng(seed)`
//! provides a canonical seeded `StdRng` for Monte-Carlo / simulation
//! tests, so precision shifts in upstream arithmetic cannot flip
//! assertions by luck.
//! - **Pricing-identity regression tests.** `tests/unit/pricing/identities_test.rs`
//! locks put-call parity on a grid, CRR binomial convergence to
//! Black-Scholes, and the Greek sanity identities
//! (`Γ_c = Γ_p`, `Vega_c = Vega_p`, `Δ_c − Δ_p ≈ e^{-qT}`).
//!
//! ### Arithmetic-Error Cascade
//!
//! ```mermaid
//! flowchart LR
//! subgraph Kernels["Numeric kernels (model / pricing / greeks / volatility / simulation)"]
//! DADD["d_add / d_sub / d_mul / d_div"]
//! DSUM["d_sum / d_sum_iter"]
//! FD["finite_decimal(f64)"]
//! end
//!
//! subgraph Errors["Typed errors (error/*)"]
//! DOV["DecimalError::Overflow { operation, lhs, rhs }"]
//! PNF["PricingError::NonFinite { context, value }"]
//! GNF["GreeksError::NonFinite"]
//! VNF["VolatilityError::NonFinite"]
//! SNF["SimulationError::NonFinite"]
//! end
//!
//! DADD -- "checked_*" --> DOV
//! DSUM -- "checked_*" --> DOV
//! FD -- "NaN / ±∞ guard" --> PNF
//! FD --> GNF
//! FD --> VNF
//! FD --> SNF
//!
//! DOV -- "#[from]" --> PNF
//! DOV -- "#[from]" --> GNF
//! DOV -- "#[from]" --> VNF
//! DOV -- "#[from]" --> SNF
//! ```
//!
//!
//! ## Core Modules
//!
//! The library is organized into the following key modules:
//!
//! ### **Model** (`model/`)
//! Core data structures and types for options trading:
//! - `option.rs`: Complete option structures with pricing and Greeks
//! - `position.rs`: Position management and P&L tracking
//! - `expiration.rs`: Flexible expiration date handling (Days/DateTime)
//! - `positive.rs`: Type-safe positive number implementation
//! - `types.rs`: Common enums (OptionType, Side, OptionStyle)
//! - `trade.rs`: Trade execution and management
//! - `format.rs`: Data formatting utilities
//! - **`leg/`**: Multi-instrument leg support for strategies
//! - `traits.rs`: Common leg traits (`LegAble`, `Marginable`, `Fundable`, `Expirable`)
//! - `spot.rs`: `SpotPosition` for underlying asset positions
//! - `perpetual.rs`: `PerpetualPosition` for crypto perpetual swaps
//! - `future.rs`: `FuturePosition` for exchange-traded futures
//! - `leg_enum.rs`: `Leg` enum unifying all position types
//!
//! ### **Pricing Models** (`pricing/`)
//! Advanced pricing engines for options valuation:
//! - `black_scholes_model.rs`: European options pricing with Greeks
//! - `black_76.rs`: European options on futures/forwards (Black 1976)
//! - `garman_kohlhagen.rs`: European FX options (Garman-Kohlhagen 1983)
//! - `binomial_model.rs`: American/European options with early exercise
//! - `monte_carlo.rs`: Path-dependent and exotic options pricing
//! - `telegraph.rs`: Jump-diffusion process modeling
//! - `payoff.rs`: Payoff function implementations
//! - `american.rs`: Barone-Adesi-Whaley approximation
//! - **Exotic Options**:
//! - `asian.rs`: Asian option pricing
//! - `barrier.rs`: Barrier option pricing
//! - `binary.rs`: Binary/Digital option pricing
//! - `lookback.rs`: Lookback option pricing
//! - `compound.rs`: Compound option pricing
//! - `chooser.rs`: Chooser option pricing
//! - `cliquet.rs`: Cliquet option pricing
//! - `rainbow.rs`: Rainbow option pricing
//! - `spread.rs`: Spread option pricing
//! - `quanto.rs`: Quanto option pricing
//! - `exchange.rs`: Exchange option pricing
//! - `power.rs`: Power option pricing
//!
//! ### **Strategies** (`strategies/`)
//! Comprehensive trading strategy implementations:
//! - `base.rs`: Core traits (Strategable, BasicAble, Positionable, etc.)
//! - **Single Leg**: `long_call.rs`, `short_call.rs`, `long_put.rs`, `short_put.rs`
//! - **Spreads**: `bull_call_spread.rs`, `bear_call_spread.rs`, `bull_put_spread.rs`, `bear_put_spread.rs`
//! - **Butterflies**: `long_butterfly_spread.rs`, `short_butterfly_spread.rs`, `call_butterfly.rs`
//! - **Complex**: `iron_condor.rs`, `iron_butterfly.rs`
//! - **Volatility**: `long_straddle.rs`, `short_straddle.rs`, `long_strangle.rs`, `short_strangle.rs`
//! - **Income**: `covered_call.rs`, `poor_mans_covered_call.rs`
//! - **Protection**: `protective_put.rs`, `collar.rs`
//! - `custom.rs`: Flexible custom strategy framework
//! - `probabilities/`: Probability analysis for strategy outcomes
//! - `delta_neutral/`: Delta neutrality analysis and adjustment
//!
//! ### **Volatility** (`volatility/`)
//! Volatility modeling and analysis:
//! - `utils.rs`: Implied volatility calculation (Newton-Raphson method)
//! - `traits.rs`: Volatility model interfaces
//! - Advanced volatility surface construction
//!
//! ### **Greeks** (`greeks/`)
//! Complete Greeks calculation suite:
//! - Delta, Gamma, Theta, Vega, Rho, Vanna, Vomma, Veta, Charm, Color calculations
//! - Real-time sensitivity analysis
//! - Greeks-based risk management
//!
//! ### **Chains** (`chains/`)
//! Option chain management and analysis:
//! - `chain.rs`: Option chain construction and manipulation
//! - `utils.rs`: Chain analysis and filtering tools
//! - CSV/JSON import/export functionality
//! - Strike price generation algorithms
//!
//! ### **Backtesting** (`backtesting/`)
//! Strategy performance analysis:
//! - `metrics.rs`: Performance metrics calculation
//! - `results.rs`: Backtesting results management
//! - `types.rs`: Backtesting data structures
//!
//! ### **Simulation** (`simulation/`)
//! Monte Carlo and stochastic simulations:
//! - Random walk implementations
//! - Telegraph process modeling
//! - Custom simulation frameworks
//! - Parametrized simulation tools
//!
//! ### **Visualization** (`visualization/`)
//! Comprehensive plotting and charting:
//! - `plotly.rs`: Interactive charts with Plotly integration
//! - Strategy payoff diagrams
//! - Greeks visualization
//! - 3D volatility surfaces
//! - Risk profile charts
//!
//! ### **Metrics** (`metrics/`)
//! Performance, risk, and liquidity metrics analysis:
//! - **Price Metrics**: Volatility skew curves
//! - **Risk Metrics**:
//! - Implied Volatility curves (by strike) and surfaces (strike vs time)
//! - Risk Reversal curves (by strike)
//! - Dollar Gamma curves (by strike)
//! - **Composite Metrics**:
//! - Vanna-Volga Hedge surfaces (price vs volatility)
//! - Delta-Gamma Profile curves (by strike) and surfaces (price vs time)
//! - Smile Dynamics curves (by strike) and surfaces (strike vs time)
//! - **Liquidity Metrics**:
//! - Bid-Ask Spread curves (by strike)
//! - Volume Profile curves (by strike) and surfaces (strike vs time)
//! - Open Interest Distribution curves (by strike)
//! - **Stress Metrics**:
//! - Volatility Sensitivity curves (by strike) and surfaces (price vs volatility)
//! - Time Decay Profile curves (by strike) and surfaces (price vs time)
//! - Price Shock Impact curves (by strike) and surfaces (price vs volatility)
//! - **Temporal Metrics**:
//! - Theta curves (by strike) and surfaces (price vs time)
//! - Charm (Delta Decay) curves (by strike) and surfaces (price vs time)
//! - Color (Gamma Decay) curves (by strike) and surfaces (price vs time)
//!
//! ### **Risk Management** (`risk/`)
//! Risk analysis and management tools:
//! - Position risk metrics
//! - Break-even analysis
//! - Risk profile generation
//!
//! ### **P&L** (`pnl/`)
//! Profit and loss calculation:
//! - Real-time P&L tracking
//! - Historical P&L analysis
//! - Performance attribution
//!
//! ### **Curves & Surfaces** (`curves/`, `surfaces/`)
//! Mathematical tools for financial modeling:
//! - Curve interpolation techniques
//! - Surface construction and analysis
//! - 3D visualization capabilities
//!
//! ### **Error Handling** (`error/`)
//! Robust error management:
//! - Comprehensive error types for each module
//! - Type-safe error propagation
//! - Detailed error reporting
//!
//! ## Core Components
//!
//! ```mermaid
//! classDiagram
//! class Options {
//! +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~
//! +calculate_price_black_scholes()
//! +calculate_price_binomial()
//! +time_to_expiration()
//! +is_long()
//! +is_short()
//! +validate()
//! +to_plot()
//! +calculate_implied_volatility()
//! +delta()
//! +gamma()
//! +theta()
//! +vega()
//! +rho()
//! +vanna()
//! +vomma()
//! +veta()
//! +charm()
//! +color()
//! }
//!
//! class Position {
//! +option: Options
//! +position_cost: Positive
//! +entry_date: DateTime<Utc>
//! +open_fee: Positive
//! +close_fee: Positive
//! +net_cost()
//! +net_premium_received()
//! +unrealized_pnl()
//! +pnl_at_expiration()
//! +validate()
//! }
//!
//! class Leg {
//! <<enumeration>>
//! Option(Position)
//! Spot(SpotPosition)
//! Future(FuturePosition)
//! Perpetual(PerpetualPosition)
//! +is_option()
//! +is_spot()
//! +is_linear()
//! +delta()
//! +pnl_at_price()
//! }
//!
//! class SpotPosition {
//! +symbol: String
//! +quantity: Positive
//! +cost_basis: Positive
//! +side: Side
//! +date: DateTime<Utc>
//! +open_fee: Positive
//! +close_fee: Positive
//! +pnl_at_price()
//! +delta()
//! +market_value()
//! +break_even_price()
//! }
//!
//! class ExpirationDate {
//! +Days(Positive)
//! +Date(NaiveDate)
//! +get_years()
//! +get_date()
//! +get_date_string()
//! +from_string()
//! }
//!
//! class Positive {
//! +value: Decimal
//! +ZERO: Positive
//! +ONE: Positive
//! +format_fixed_places()
//! +round_to_nice_number()
//! +is_positive()
//! }
//!
//! class OptionStyle {
//! <<enumeration>>
//! Call
//! Put
//! }
//!
//! class OptionType {
//! <<enumeration>>
//! European
//! American
//! Bermuda
//! Asian
//! Barrier
//! Binary
//! Lookback
//! Compound
//! Chooser
//! Cliquet
//! Rainbow
//! Spread
//! Quanto
//! Exchange
//! Power
//! }
//!
//! class Side {
//! <<enumeration>>
//! Long
//! Short
//! }
//!
//! class Graph {
//! <<interface>>
//! +graph_data()
//! +graph_config()
//! +to_plot()
//! +write_html()
//! +write_png()
//! +write_svg()
//! +write_jpeg()
//! }
//!
//! class Greeks {
//! <<interface>>
//! +delta()
//! +gamma()
//! +theta()
//! +vega()
//! +rho()
//! +calculate_all_greeks()
//! }
//!
//! Options --|> Greeks : implements
//! Options --|> Graph : implements
//! Position o-- Options : contains
//! Leg o-- Position : Option variant
//! Leg o-- SpotPosition : Spot variant
//! SpotPosition *-- Side : has
//! SpotPosition *-- Positive : uses
//! Options *-- OptionStyle : has
//! Options *-- OptionType : has
//! Options *-- Side : has
//! Options *-- ExpirationDate : has
//! Options *-- Positive : uses
//! ```
//!
//! ## Pricing Models Architecture
//!
//! ```mermaid
//! flowchart TB
//! subgraph Standard["Standard Options"]
//! EU[European]
//! AM[American]
//! BE[Bermuda]
//! end
//!
//! subgraph PathDependent["Path-Dependent"]
//! AS[Asian]
//! LB[Lookback]
//! BA[Barrier]
//! CL[Cliquet]
//! end
//!
//! subgraph MultiAsset["Multi-Asset"]
//! RB[Rainbow]
//! SP[Spread]
//! EX[Exchange]
//! end
//!
//! subgraph Special["Special Payoffs"]
//! BI[Binary]
//! PW[Power]
//! QU[Quanto]
//! CO[Compound]
//! CH[Chooser]
//! end
//!
//! subgraph Forward["Forward-Priced"]
//! FUT[Future]
//! FWD[Forward]
//! end
//!
//! subgraph FX["FX / Currency"]
//! FX_S[FX Spot]
//! end
//!
//! BS[black_scholes] --> EU
//! BS --> PathDependent
//! BS --> MultiAsset
//! BS --> Special
//! B76[black_76] --> Forward
//! GK[garman_kohlhagen] --> FX
//! BAW[barone_adesi_whaley] --> AM
//! BIN[binomial_model] --> AM
//! BIN --> BE
//! MC[monte_carlo] --> PathDependent
//! ```
//!
//! ## Strategy Traits System
//!
//! ```mermaid
//! classDiagram
//! class Strategable {
//! <<trait>>
//! Master trait combining all capabilities
//! }
//!
//! class BasicAble {
//! <<trait>>
//! +get_underlying_price()
//! +get_underlying_symbol()
//! +get_expiration()
//! +get_title()
//! }
//!
//! class Positionable {
//! <<trait>>
//! +get_positions()
//! +add_position()
//! +modify_position()
//! }
//!
//! class Strategies {
//! <<trait>>
//! +get_net_premium_received()
//! +get_max_profit()
//! +get_max_loss()
//! +get_total_cost()
//! }
//!
//! class BreakEvenable {
//! <<trait>>
//! +get_break_even_points()
//! +calculate_break_even()
//! }
//!
//! class Profit {
//! <<trait>>
//! +get_point_at_price()
//! +calculate_profit_at()
//! }
//!
//! class Greeks {
//! <<trait>>
//! +delta()
//! +gamma()
//! +theta()
//! +vega()
//! }
//!
//! class DeltaNeutrality {
//! <<trait>>
//! +get_delta()
//! +suggest_delta_adjustments()
//! }
//!
//! class Graph {
//! <<trait>>
//! +to_plot()
//! +write_html()
//! +write_png()
//! }
//!
//! Strategable --|> BasicAble
//! Strategable --|> Positionable
//! Strategable --|> Strategies
//! Strategable --|> BreakEvenable
//! Strategable --|> Profit
//! Strategable --|> Greeks
//! Strategable --|> DeltaNeutrality
//! Strategable --|> Graph
//! ```
//!
//! ## Metrics Framework
//!
//! ```mermaid
//! flowchart LR
//! subgraph OptionChain
//! OC[OptionChain]
//! end
//!
//! subgraph Curves["Curve Metrics"]
//! IV_C[IV Curve]
//! RR_C[Risk Reversal]
//! DG_C[Dollar Gamma]
//! TH_C[Theta Curve]
//! VA_C[Vanna Curve]
//! SK_C[Skew Curve]
//! end
//!
//! subgraph Surfaces["Surface Metrics"]
//! IV_S[IV Surface]
//! TH_S[Theta Surface]
//! CH_S[Charm Surface]
//! VS_S[Vol Sensitivity]
//! TD_S[Time Decay]
//! end
//!
//! OC --> Curves
//! OC --> Surfaces
//! Curves --> |"2D Analysis"| Analysis[Risk Analysis]
//! Surfaces --> |"3D Analysis"| Analysis
//! ```
//!
//! ## Observability
//!
//! Public hot paths are annotated with `#[tracing::instrument]`.
//! Enable a subscriber in the consumer crate (the library itself never
//! installs one) to surface structured spans:
//!
//! ```mermaid
//! flowchart LR
//! APP[Consumer application] -- "installs" --> SUB["tracing_subscriber"]
//!
//! subgraph Spans["Instrumented public fns"]
//! BS["pricing::black_scholes\n(strike, style, side)"]
//! MC["pricing::monte_carlo_option_pricing\n(steps, simulations, strike, style, side)"]
//! BI["pricing::price_binomial\n(strike, asset, steps, style, side)"]
//! IV["volatility::implied_volatility\n(market_price, strike, max_iterations)"]
//! OPT["Optimizable::get_best_ratio/area\n(side, criteria)"]
//! end
//!
//! BS --> SUB
//! MC --> SUB
//! BI --> SUB
//! IV --> SUB
//! OPT --> SUB
//! ```
//!
//! ## Trading Strategies
//!
//! OptionStratLib provides 25+ comprehensive trading strategies organized by complexity and market outlook:
//!
//! ### **Single Leg Strategies**
//! Basic directional strategies for beginners:
//! - **Long Call**: Bullish strategy with unlimited upside potential
//! - **Short Call**: Bearish strategy collecting premium with limited profit
//! - **Long Put**: Bearish strategy with high profit potential
//! - **Short Put**: Bullish strategy collecting premium with assignment risk
//!
//! ### **Spread Strategies**
//! Defined risk strategies with limited profit/loss:
//! - **Bull Call Spread**: Moderately bullish with limited risk and reward
//! - **Bear Call Spread**: Moderately bearish credit spread
//! - **Bull Put Spread**: Moderately bullish credit spread
//! - **Bear Put Spread**: Moderately bearish debit spread
//!
//! ### **Butterfly Strategies**
//! Market neutral strategies profiting from low volatility:
//! - **Long Butterfly Spread**: Profits from price staying near middle strike
//! - **Short Butterfly Spread**: Profits from price moving away from middle strike
//! - **Call Butterfly**: Butterfly using only call options
//!
//! ### **Complex Multi-Leg Strategies**
//! Advanced strategies for experienced traders:
//! - **Iron Condor**: Market neutral strategy with wide profit zone
//! - **Iron Butterfly**: Market neutral strategy with narrow profit zone
//!
//! ### **Volatility Strategies**
//! Strategies that profit from volatility changes:
//! - **Long Straddle**: Profits from high volatility in either direction
//! - **Short Straddle**: Profits from low volatility (range-bound market)
//! - **Long Strangle**: Similar to straddle but with different strikes
//! - **Short Strangle**: Credit strategy profiting from low volatility
//!
//! ### **Income Generation Strategies**
//! Strategies focused on generating regular income:
//! - **Covered Call**: Stock/spot ownership with call selling for income (now with full spot leg support)
//! - **Poor Man's Covered Call**: LEAPS-based covered call alternative
//!
//! ### **Protection Strategies**
//! Risk management and hedging strategies:
//! - **Protective Put**: Downside protection for stock positions
//! - **Collar**: Combination of covered call and protective put
//!
//! ### **Custom Strategy Framework**
//! - **Custom Strategy**: Flexible framework for creating any multi-leg strategy
//! - Supports unlimited number of legs
//! - Full integration with all analysis tools
//! - Complete trait implementation for consistency
//!
//! ### **Strategy Analysis Features**
//! All strategies include comprehensive analysis capabilities:
//! - **Profit/Loss Analysis**: P&L at any price point and time
//! - **Break-Even Points**: Multiple break-even calculations
//! - **Greeks Analysis**: Real-time risk metrics
//! - **Probability Analysis**: Success probability calculations
//! - **Delta Neutrality**: Delta-neutral position analysis
//! - **Visualization**: Interactive payoff diagrams and risk profiles
//! - **Optimization**: Find optimal strikes and expirations
//!
//! ### **Strategy Traits System**
//! All strategies implement a comprehensive trait system:
//!
//! - **Strategable**: Master trait combining all strategy capabilities
//! - **BasicAble**: Basic strategy information (symbol, price, etc.)
//! - **Positionable**: Position management and modification
//! - **Strategies**: Core strategy calculations (P&L, break-even, etc.)
//! - **Validable**: Strategy validation and error checking
//! - **BreakEvenable**: Break-even point calculations
//! - **Profit**: Profit/loss analysis at various price points
//! - **Greeks**: Greeks calculations for risk management
//! - **DeltaNeutrality**: Delta-neutral analysis and adjustments
//! - **ProbabilityAnalysis**: Outcome probability calculations
//! - **Graph**: Visualization and plotting capabilities
//!
//! ## Setup Instructions
//!
//! ### Prerequisites
//!
//! - Rust 1.85 or higher (Rust 2024 edition)
//! - Cargo package manager
//!
//! ### Installation
//!
//! Add OptionStratLib to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! optionstratlib = "0.17.1"
//! ```
//!
//! Or use cargo to add it to your project:
//!
//! ```bash
//! cargo add optionstratlib
//! ```
//!
//! ### Optional Features
//!
//! The library includes optional features for enhanced functionality:
//!
//! ```toml
//! [dependencies]
//! optionstratlib = { version = "0.17.1", features = ["plotly"] }
//! ```
//!
//! - `plotly`: Enables interactive visualization using plotly.rs
//! - `static_export`: PNG / SVG export via `plotly_static` (pulls in async runtime)
//! - `async`: Enables asynchronous I/O operations for OptionChain and OHLCV data (tokio + reqwest + futures)
//!
//! ### Building from Source
//!
//! Clone the repository and build using Cargo:
//!
//! ```bash
//! git clone https://github.com/joaquinbejar/OptionStratLib.git
//! cd OptionStratLib
//! cargo build --release
//! ```
//!
//! Run comprehensive test suite:
//!
//! ```bash
//! cargo test --all-features
//! ```
//!
//! Generate documentation:
//!
//! ```bash
//! cargo doc --open --all-features
//! ```
//!
//! Run benchmarks:
//!
//! ```bash
//! cargo bench
//! ```
//!
//! ## Library Usage
//!
//! ### Basic Option Creation and Pricing
//!
//! ```rust
//! use optionstratlib::{Options, OptionStyle, OptionType, Side, ExpirationDate};
//! use positive::{pos_or_panic,Positive};
//! use rust_decimal_macros::dec;
//! use optionstratlib::greeks::Greeks;
//!
//! fn main() -> Result<(), optionstratlib::error::Error> {
//! // Create a European call option
//! let option = Options::new(
//! OptionType::European,
//! Side::Long,
//! "AAPL".to_string(),
//! pos_or_panic!(150.0), // strike_price
//! ExpirationDate::Days(pos_or_panic!(30.0)),
//! pos_or_panic!(0.25), // implied_volatility
//! Positive::ONE, // quantity
//! pos_or_panic!(155.0), // underlying_price
//! dec!(0.05), // risk_free_rate
//! OptionStyle::Call,
//! pos_or_panic!(0.02), // dividend_yield
//! None, // exotic_params
//! );
//!
//! // Calculate option price using Black-Scholes
//! let price = option.calculate_price_black_scholes()?;
//! tracing::info!("Option price: ${:.2}", price);
//!
//! // Calculate Greeks for risk management
//! let delta = option.delta()?;
//! let gamma = option.gamma()?;
//! let theta = option.theta()?;
//! let vega = option.vega()?;
//! let vanna = option.vanna()?;
//! let vomma = option.vomma()?;
//! let veta = option.veta()?;
//! let charm = option.charm()?;
//! let color = option.color()?;
//! tracing::info!("Greeks - Delta: {:.4}, Gamma: {:.4}, Theta: {:.4},
//! Vega: {:.4}, Vanna: {:.4}, Vomma: {:.4}, Veta: {:.4}
//! Charm: {:.4}, Color: {:.4}",
//! delta, gamma, theta, vega, vanna, vomma, veta, charm, color);
//! Ok(())
//! }
//! ```
//!
//! ### Working with Trading Strategies
//!
//! ```rust
//! use positive::{Positive, pos_or_panic};
//! use optionstratlib::ExpirationDate;
//! use optionstratlib::strategies::Strategies;
//! use optionstratlib::strategies::bull_call_spread::BullCallSpread;
//! use optionstratlib::strategies::base::{BreakEvenable, BasicAble};
//! use optionstratlib::visualization::Graph;
//! use rust_decimal_macros::dec;
//! use std::error::Error;
//!
//! fn main() -> Result<(), optionstratlib::error::Error> {
//! use optionstratlib::pricing::Profit;
//! let underlying_price = Positive::HUNDRED;
//!
//! // Create a Bull Call Spread strategy
//! let strategy = BullCallSpread::new(
//! "AAPL".to_string(),
//! underlying_price,
//! pos_or_panic!(95.0), // long_strike
//! pos_or_panic!(105.0), // short_strike
//! ExpirationDate::Days(pos_or_panic!(30.0)),
//! pos_or_panic!(0.25), // implied_volatility
//! dec!(0.05), // risk_free_rate
//! pos_or_panic!(2.50), // long_call_premium
//! pos_or_panic!(2.50), // long_call_open_fee
//! pos_or_panic!(1.20), // short_call_premium
//! pos_or_panic!(1.20), // short_call_close_fee
//! Default::default(), Default::default(),
//! Default::default(), Default::default()
//! )?;
//!
//! // Analyze the strategy
//! tracing::info!("Strategy: {}", strategy.get_title());
//! tracing::info!("Break-even points: {:?}", strategy.get_break_even_points()?);
//! tracing::info!("Max profit: ${:.2}", strategy.get_max_profit().unwrap_or(Positive::ZERO));
//! tracing::info!("Max loss: ${:.2}", strategy.get_max_loss().unwrap_or(Positive::ZERO));
//! tracing::info!("Net premium: ${:.2}", strategy.get_net_premium_received()?);
//!
//! // Calculate P&L at different price points
//! let prices = vec![pos_or_panic!(90.0), pos_or_panic!(95.0), Positive::HUNDRED, pos_or_panic!(105.0), pos_or_panic!(110.0)];
//! for price in prices {
//! let pnl = strategy.get_point_at_price(&price)?;
//! tracing::info!("P&L at ${}: ${:.2}", price, pnl.0);
//! }
//!
//! // Generate visualization
//! #[cfg(feature = "plotly")]
//! {
//! strategy.write_html("Draws/Visualization/bull_call_spread.html".as_ref())?;
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ### Advanced Features: Volatility Analysis
//!
//! ```rust
//! use optionstratlib::prelude::*;
//!
//! fn main() -> Result<(), optionstratlib::error::Error> {
//! // Create an option for implied volatility calculation
//! let mut option = Options::new(
//! OptionType::European,
//! Side::Long,
//! "AAPL".to_string(),
//! pos_or_panic!(105.0), // strike
//! ExpirationDate::Days(pos_or_panic!(90.0)),
//! pos_or_panic!(0.20), // initial IV guess
//! Positive::ONE, // quantity
//! Positive::HUNDRED, // underlying price
//! dec!(0.05), // risk free rate
//! OptionStyle::Call,
//! pos_or_panic!(0.02), // dividend yield
//! None,
//! );
//!
//! let market_price = pos_or_panic!(5.50);
//! let iv = implied_volatility(market_price, &mut option, 100)?;
//!
//! tracing::info!("Implied volatility: {:.2}%", iv.to_f64() * 100.0);
//! Ok(())
//! }
//! ```
//!
//! ### Custom Strategy Creation
//!
//! ```rust
//! use optionstratlib::prelude::*;
//!
//! fn main() -> Result<(), optionstratlib::error::Error> {
//! // Define common parameters
//! let underlying_symbol = "DAX".to_string();
//! let underlying_price = pos_or_panic!(24000.0);
//! let expiration = ExpirationDate::Days(pos_or_panic!(30.0));
//! let implied_volatility = pos_or_panic!(0.25);
//! let risk_free_rate = dec!(0.05);
//! let dividend_yield = pos_or_panic!(0.02);
//! let fee = Positive::TWO;
//!
//! // Create a long put option
//! let long_put_option = Options::new(
//! OptionType::European,
//! Side::Long,
//! underlying_symbol.clone(),
//! pos_or_panic!(24070.0), // strike
//! expiration.clone(),
//! implied_volatility,
//! Positive::ONE, // quantity
//! underlying_price,
//! risk_free_rate,
//! OptionStyle::Put,
//! dividend_yield,
//! None,
//! );
//! let long_put = Position::new(
//! long_put_option,
//! pos_or_panic!(150.0), // premium
//! Utc::now(),
//! fee,
//! fee,
//! None,
//! None,
//! );
//!
//! // Create a long call option
//! let long_call_option = Options::new(
//! OptionType::European,
//! Side::Long,
//! underlying_symbol.clone(),
//! pos_or_panic!(24030.0), // strike
//! expiration.clone(),
//! implied_volatility,
//! Positive::ONE, // quantity
//! underlying_price,
//! risk_free_rate,
//! OptionStyle::Call,
//! dividend_yield,
//! None,
//! );
//! let long_call = Position::new(
//! long_call_option,
//! pos_or_panic!(120.0), // premium
//! Utc::now(),
//! fee,
//! fee,
//! None,
//! None,
//! );
//!
//! // Create CustomStrategy with the positions
//! let positions = vec![long_call, long_put];
//! let strategy = CustomStrategy::new(
//! "DAX Straddle Strategy".to_string(),
//! underlying_symbol,
//! "A DAX long straddle strategy".to_string(),
//! underlying_price,
//! positions,
//! Positive::ONE,
//! 30,
//! implied_volatility,
//! )?;
//!
//! tracing::info!("Strategy created: {}", strategy.get_title());
//! Ok(())
//! }
//! ```
//!
//! ## Testing
//!
//! OptionStratLib ships with a large, fully deterministic test suite
//! (3760 unit / integration tests + 205 doctests + property- and
//! identity-based regressions):
//!
//! ### **Running Tests**
//!
//! Run all tests:
//! ```bash
//! cargo test --all-features
//! ```
//!
//! Run tests for specific modules:
//! ```bash
//! cargo test strategies::bull_call_spread
//! cargo test pricing::black_scholes
//! cargo test volatility::utils
//! ```
//!
//! Run tests with output:
//! ```bash
//! cargo test -- --nocapture
//! ```
//!
//! ### **Test Categories**
//!
//! - **Unit Tests**: Individual function and method testing
//! - **Integration Tests**: Cross-module functionality under `tests/`
//! - **Strategy Tests**: Comprehensive strategy validation
//! - **Pricing Model Tests**: Accuracy and performance testing
//! - **Greeks Tests**: Mathematical precision validation
//! - **Visualization Tests**: Chart generation and export testing
//! - **Property-Based Tests**: Mathematical invariant testing with `proptest`
//! (`tests/property/put_call_parity_test.rs`, `greeks_bounds_test.rs`)
//! - **Identity Regression Tests**: `tests/unit/pricing/identities_test.rs`
//! locks put-call parity, CRR → Black-Scholes convergence, and
//! Greek sanity (`Γ_c = Γ_p`, `Vega_c = Vega_p`,
//! `Δ_c − Δ_p ≈ e^{-qT}`).
//! - **Deterministic Monte-Carlo Tests**: Seeded via
//! [`utils::deterministic_rng`] so arithmetic-precision shifts can't
//! flip assertions.
//! - **Exotic Options Tests**: Complete coverage for all 14 exotic
//! option types.
//!
//! ### **Benchmarking**
//!
//! Run performance benchmarks:
//! ```bash
//! cargo bench
//! ```
//!
//! Generate test coverage report:
//! ```bash
//! cargo tarpaulin --all-features --out Html
//! ```
//!
//! ## Examples
//!
//! Examples live in self-contained sub-crates under `examples/`, each
//! with its own `Cargo.toml`:
//!
//! - **`examples_strategies/`**: 25+ strategy demos
//! - **`examples_strategies_best/`**: Optimizer entry points
//! (`get_best_area` / `get_best_ratio`) per strategy
//! - **`examples_strategies_delta/`**: Delta-neutrality workflows
//! - **`examples_chain/`**: Option chain construction, import/export,
//! and async I/O
//! - **`examples_curves/`**: Greek curves (`charm`, `color`, `d1`, `d2`,
//! `delta`, `gamma`, `rho`, `theta`, …) and vector curves
//! - **`examples_surfaces/`**: 3-D volatility surfaces
//! - **`examples_metrics/`**: Price / risk / liquidity / stress /
//! temporal / composite metric curves and surfaces
//! - **`examples_volatility/`**: Implied-volatility solver walkthroughs
//! - **`examples_simulation/`**: Monte-Carlo random-walk demos for
//! `LongCall`, `ShortPut`, position / strategy simulators, and
//! random-walk-of-chain
//! - **`examples_exotics/`**: Exotic option pricing (barrier,
//! cliquet, …)
//! - **`examples_visualization/`**: Interactive chart wiring
//!
//! Run any binary with the usual cargo invocation (from the repo
//! root, so relative data-fixture paths resolve correctly):
//!
//! ```bash
//! cargo run --manifest-path=examples/examples_strategies/Cargo.toml \
//! --bin strategy_bull_call_spread
//! cargo run --manifest-path=examples/examples_simulation/Cargo.toml \
//! --bin long_call_strategy_simulation --features plotly
//! cargo run --manifest-path=examples/examples_metrics/Cargo.toml \
//! --bin implied_volatility_surface
//! ```
//!
//! Simulation-heavy demos (`*_strategy_simulation`, `position_simulator`,
//! `strategy_simulator`, `random_walk_chain`) use a demo-friendly
//! hourly grid so `cargo run` finishes in a few seconds in debug mode;
//! bump `n_steps` / `n_simulations` inside the binary if you want a
//! finer sample.
//!
//! ## Contribution and Contact
//!
//! ### **Contributing**
//!
//! Contributions are welcome! Please follow these guidelines:
//!
//! 1. **Fork** the repository
//! 2. **Create** a feature branch: `git checkout -b feature/amazing-feature`
//! 3. **Commit** your changes: `git commit -m 'Add amazing feature'`
//! 4. **Push** to the branch: `git push origin feature/amazing-feature`
//! 5. **Open** a Pull Request
//!
//! ### **Development Setup**
//!
//! ```bash
//! git clone https://github.com/joaquinbejar/OptionStratLib.git
//! cd OptionStratLib
//! cargo build --all-features
//! cargo test --all-features
//! ```
//!
//! ### **Code Quality**
//!
//! - All code must pass `cargo clippy` without warnings
//! - Format code with `cargo fmt`
//! - Add tests for new functionality
//! - Update documentation for API changes
//! - Follow Rust 2024 edition best practices
//!
//!
//! ### **Support**
//!
//! - **Issues**: Report bugs and request features on GitHub
//! - **Discussions**: Join community discussions on GitHub Discussions
//! - **Documentation**: Comprehensive docs available at docs.rs
//!
//! ---
//!
//! **OptionStratLib v0.17.1** - Built with ❤️ in Rust for the financial community
//!
/// # OptionsStratLib: Financial Options Trading Library
///
/// A comprehensive library for options trading analytics, modeling, and strategy development.
/// Provides tools for pricing, risk assessment, strategy building, and performance analysis
/// of financial options across various market conditions.
///
/// ## Core Modules
extern crate core;
/// * `model` - Core data structures and models for options and derivatives.
///
/// Defines the fundamental data types and structures used throughout the library,
/// including option contract representations, position tracking, and market data models.
/// Serves as the foundation for all other modules.
/// NOTE: This module must be declared first to ensure macros (pos!, spos!) are available
/// to other modules.
/// * `backtesting` - Tools for historical performance evaluation of options strategies.
///
/// Provides framework and utilities to simulate and analyze how option strategies
/// would have performed using historical market data. Supports various performance
/// metrics, drawdown analysis, and strategy comparison.
/// * `chains` - Functionality for working with options chains and series data.
///
/// Tools for parsing, manipulating, and analyzing options chain data. Includes
/// methods to filter chains by expiration, strike price, and other criteria,
/// as well as utilities for chain visualization and analysis.
/// * `constants` - Library-wide mathematical and financial constants.
///
/// Defines fundamental constants used throughout the library including mathematical
/// constants (π, epsilon values), market standards (trading days per year),
/// calculation parameters, and visualization color schemes.
/// * `curves` - Tools for yield curves, term structures, and other financial curves.
///
/// Implementations of various interest rate curves, forward curves, and term structures
/// used in options pricing and risk management. Includes interpolation methods and
/// curve fitting algorithms.
/// * `error` - Error types and handling functionality for the library.
///
/// Defines the error hierarchy used throughout the library, providing detailed
/// error types for different categories of failures including validation errors,
/// calculation errors, and input/output errors.
/// * `geometrics` - Mathematical utilities for geometric calculations relevant to options.
///
/// Provides specialized geometric functions and algorithms for options pricing and modeling,
/// including path-dependent calculations and spatial transformations for volatility surfaces.
/// * `greeks` - Calculation and management of option sensitivity metrics (Delta, Gamma, etc.).
///
/// Comprehensive implementation of options Greeks (sensitivity measures) including
/// Delta, Gamma, Theta, Vega, Rho, Vanna, Vomma, Veta, Charm and Color. Includes analytical
/// formulas, numerical approximations, and visualization tools for risk analysis.
/// * `metrics` - Performance and risk metrics analysis for options.
///
/// Comprehensive tools for performance and risk analysis including:
/// - **Price Metrics**: Volatility skew analysis
/// - **Risk Metrics**: Implied volatility curves/surfaces, risk reversal curves, dollar gamma curves
///
/// ## Risk Metrics
///
/// The risk metrics module provides key tools for assessing market risk, sentiment, and exposure:
///
/// | Metric | Curve (by strike) | Surface (strike vs time) |
/// |--------|-------------------|--------------------------|
/// | Implied Volatility | `iv_curve()` | `iv_surface(days)` |
/// | Risk Reversal | `risk_reversal_curve()` | - |
/// | Dollar Gamma | `dollar_gamma_curve(style)` | - |
///
/// ### Implied Volatility
/// Shows how IV varies across strikes and time horizons. Essential for understanding
/// market expectations and pricing options.
///
/// ### Risk Reversal
/// Measures the difference between call and put implied volatilities, indicating
/// market sentiment (bullish vs bearish bias).
///
/// ### Dollar Gamma
/// Gamma exposure in monetary terms: `Dollar Gamma = Gamma × Spot² × 0.01`
/// Shows how much delta changes for a 1% move in the underlying.
/// * `pnl` - Profit and loss analysis tools for options positions.
///
/// Utilities for calculating, projecting, and visualizing profit and loss (P&L) profiles
/// for individual options and complex strategies. Includes time-based P&L evolution and
/// scenario analysis.
/// * `pricing` - Option pricing models including Black-Scholes and numerical methods.
///
/// Implementations of various option pricing models including Black-Scholes-Merton,
/// binomial trees, Monte Carlo simulation, and finite difference methods. Supports
/// European, American, and exotic options.
/// * `risk` - Risk assessment and management tools for options portfolios.
///
/// Tools for analyzing and quantifying risk in options positions and portfolios,
/// including Value at Risk (VaR), stress testing, scenario analysis, and
/// portfolio optimization algorithms.
/// * `simulation` - Simulation techniques for scenario analysis.
///
/// Framework for Monte Carlo and other simulation methods to model potential
/// market scenarios and their impact on options strategies. Includes path generation
/// algorithms and statistical analysis of simulation results.
/// * `strategies` - Pre-defined option strategy templates and building blocks.
///
/// Library of common option strategies (spreads, straddles, condors, etc.) with
/// implementation helpers, parameter optimization, and analysis tools. Supports
/// strategy composition and customization.
/// * `surfaces` - Volatility surface and other 3D financial data modeling.
///
/// Tools for constructing, manipulating, and analyzing volatility surfaces and
/// other three-dimensional financial data structures. Includes interpolation methods,
/// fitting algorithms, and visualization utilities.
/// * `utils` - General utility functions for data manipulation and calculations.
///
/// Collection of helper functions and utilities used across the library for
/// data manipulation, mathematical operations, date handling, and other
/// common tasks in financial calculations.
/// * `visualization` - Tools for plotting and visual representation of options data.
///
/// Graphics and visualization utilities for creating charts, graphs, and interactive
/// plots of options data, strategies, and analytics. Supports various plot types
/// optimized for different aspects of options analysis.
/// * `volatility` - Volatility modeling, forecasting, and analysis utilities.
///
/// Comprehensive tools for volatility analysis including historical volatility calculation,
/// implied volatility determination, volatility forecasting models (GARCH, EWMA), and
/// volatility skew/smile analysis.
/// * `series` - Functionality for working with collections of option chains across expirations.
///
/// Provides tools to manage, filter, and analyze multiple option chains grouped by expiration dates.
/// Includes utilities for constructing series data, navigating expirations, and performing
/// cross-expiration analysis and visualization.
/// * `prelude` - Convenient re-exports of commonly used types and traits.
///
/// The prelude module provides a single import point for the most frequently used
/// types, traits, and functions from the OptionStratLib library. This reduces the
/// amount of boilerplate imports needed when working with the library.
pub use ExpirationDate;
pub use Options;
pub use ;
/// Library version
pub const VERSION: &str = env!;
/// Returns the library version