Skip to main content

optionstratlib/
lib.rs

1#![allow(unknown_lints)]
2#![allow(clippy::literal_string_with_formatting_args)]
3
4//! # OptionStratLib v0.15.1: Financial Options Library
5//!
6//! ## Table of Contents
7//! 1. [Introduction](#introduction)
8//! 2. [Features](#features)
9//! 3. [Core Modules](#core-modules)
10//! 4. [Trading Strategies](#trading-strategies)
11//! 5. [Setup Instructions](#setup-instructions)
12//! 6. [Library Usage](#library-usage)
13//! 7. [Usage Examples](#usage-examples)
14//! 8. [Testing](#testing)
15//! 9. [Contribution and Contact](#contribution-and-contact)
16//!
17//! ## Introduction
18//!
19//! OptionStratLib is a comprehensive Rust library for options trading and strategy development across multiple asset classes.
20//! This versatile toolkit enables traders, quants, and developers to model, analyze, and visualize options strategies with a
21//! robust, type-safe approach. The library focuses on precision with decimal-based calculations, extensive test coverage,
22//! and a modular architecture built on modern Rust 2024 edition.
23//!
24//! ## Features
25//!
26//! ### 1. **Pricing Models**
27//! - **Black-Scholes Model**: European options pricing with full Greeks support
28//! - **Binomial Tree Model**: American and European options with early exercise capability
29//! - **Monte Carlo Simulations**: Complex pricing scenarios and path-dependent options
30//! - **Telegraph Process Model**: Advanced stochastic modeling for jump-diffusion processes
31//! - **American Options**: Barone-Adesi-Whaley approximation for early exercise
32//! - **Exotic Options**: Complete support for 14 exotic option types (see below)
33//!
34//! ### 2. **Greeks Calculation**
35//! - Complete Greeks suite: Delta, Gamma, Theta, Vega, Rho, Vanna, Vomma, Veta,
36//!   Charm, Color
37//! - Real-time sensitivity analysis
38//! - Greeks visualization and risk profiling
39//! - Custom Greeks implementations with adjustable parameters
40//!
41//! ### 3. **Volatility Models**
42//! - Implied volatility calculation using Newton-Raphson method
43//! - Volatility surface construction and interpolation
44//! - Historical volatility estimation
45//! - Advanced volatility modeling tools
46//!
47//! ### 4. **Option Chain Management**
48//! - Complete option chain construction and analysis
49//! - Strike price generation algorithms
50//! - Chain data import/export (CSV/JSON formats)
51//! - Advanced filtering and selection tools
52//! - Option data grouping and organization
53//!
54//! ### 5. **Trading Strategies (25+ Strategies)**
55//! - **Single Leg**: Long/Short Calls and Puts
56//! - **Spreads**: Bull/Bear Call/Put Spreads
57//! - **Butterflies**: Long/Short Butterfly Spreads, Call Butterfly
58//! - **Complex**: Iron Condor, Iron Butterfly
59//! - **Volatility**: Long/Short Straddles and Strangles
60//! - **Income**: Covered Calls (with spot leg support), Poor Man's Covered Call
61//! - **Protection**: Protective Puts, Collars
62//! - **Custom**: Flexible custom strategy framework
63//! - **Multi-Asset**: Strategies combining options with spot, futures, or perpetuals
64//!
65//! ### 6. **Risk Management & Analysis**
66//! - Position tracking and management
67//! - Break-even analysis with multiple break-even points
68//! - Profit/Loss calculations at various price points
69//! - Risk profiles and comprehensive visualizations
70//! - Delta neutrality analysis and adjustment
71//! - Probability analysis for strategy outcomes
72//!
73//! ### 7. **Backtesting Framework**
74//! - Comprehensive backtesting engine
75//! - Performance metrics calculation
76//! - Strategy optimization tools
77//! - Historical analysis capabilities
78//!
79//! ### 8. **Simulation Tools**
80//! - Monte Carlo simulations for strategy testing
81//! - Telegraph process implementation
82//! - Random walk simulations
83//! - Custom simulation frameworks
84//! - Parametrized simulations with adjustable inputs
85//!
86//! ### 9. **Visualization & Plotting**
87//! - Strategy payoff diagrams
88//! - Greeks visualization
89//! - 3D volatility surfaces
90//! - Risk profiles and P&L charts
91//! - Interactive charts (powered by `plotly.rs`)
92//! - Binomial tree visualization
93//! - Comprehensive plotting utilities
94//!
95//! ### 10. **Data Management**
96//! - Efficient decimal-based calculations using `rust_decimal`
97//! - CSV/JSON import/export functionality
98//! - Time series data handling
99//! - Price series management and manipulation
100//! - Robust data validation and error handling
101//!
102//! ### 11. **Mathematical Tools**
103//! - Curve interpolation techniques
104//! - Surface construction and analysis
105//! - Geometric operations for financial modeling
106//! - Advanced mathematical utilities for options pricing
107//!
108//! ### 12. **Exotic Option Pricing**
109//! Complete pricing support for all exotic option types:
110//! - **Asian**: Arithmetic and geometric average price options
111//! - **Barrier**: Up/Down, In/Out barrier options with rebates
112//! - **Binary**: Cash-or-nothing and asset-or-nothing options
113//! - **Lookback**: Fixed and floating strike lookback options
114//! - **Compound**: Options on options
115//! - **Chooser**: Options to choose call or put at future date
116//! - **Cliquet**: Forward-starting options with local caps/floors
117//! - **Rainbow**: Multi-asset best-of/worst-of options
118//! - **Spread**: Kirk's approximation for price differentials
119//! - **Quanto**: Currency-protected options
120//! - **Exchange**: Margrabe's formula for asset exchange
121//! - **Power**: Non-linear payoff options
122//!
123//!
124//! ## Core Modules
125//!
126//! The library is organized into the following key modules:
127//!
128//! ### **Model** (`model/`)
129//! Core data structures and types for options trading:
130//! - `option.rs`: Complete option structures with pricing and Greeks
131//! - `position.rs`: Position management and P&L tracking
132//! - `expiration.rs`: Flexible expiration date handling (Days/DateTime)
133//! - `positive.rs`: Type-safe positive number implementation
134//! - `types.rs`: Common enums (OptionType, Side, OptionStyle)
135//! - `trade.rs`: Trade execution and management
136//! - `format.rs`: Data formatting utilities
137//! - **`leg/`**: Multi-instrument leg support for strategies
138//!   - `traits.rs`: Common leg traits (`LegAble`, `Marginable`, `Fundable`, `Expirable`)
139//!   - `spot.rs`: `SpotPosition` for underlying asset positions
140//!   - `perpetual.rs`: `PerpetualPosition` for crypto perpetual swaps
141//!   - `future.rs`: `FuturePosition` for exchange-traded futures
142//!   - `leg_enum.rs`: `Leg` enum unifying all position types
143//!
144//! ### **Pricing Models** (`pricing/`)
145//! Advanced pricing engines for options valuation:
146//! - `black_scholes_model.rs`: European options pricing with Greeks
147//! - `binomial_model.rs`: American/European options with early exercise
148//! - `monte_carlo.rs`: Path-dependent and exotic options pricing
149//! - `telegraph.rs`: Jump-diffusion process modeling
150//! - `payoff.rs`: Payoff function implementations
151//! - `american.rs`: Barone-Adesi-Whaley approximation
152//! - **Exotic Options**:
153//!   - `asian.rs`: Asian option pricing
154//!   - `barrier.rs`: Barrier option pricing
155//!   - `binary.rs`: Binary/Digital option pricing
156//!   - `lookback.rs`: Lookback option pricing
157//!   - `compound.rs`: Compound option pricing
158//!   - `chooser.rs`: Chooser option pricing
159//!   - `cliquet.rs`: Cliquet option pricing
160//!   - `rainbow.rs`: Rainbow option pricing
161//!   - `spread.rs`: Spread option pricing
162//!   - `quanto.rs`: Quanto option pricing
163//!   - `exchange.rs`: Exchange option pricing
164//!   - `power.rs`: Power option pricing
165//!
166//! ### **Strategies** (`strategies/`)
167//! Comprehensive trading strategy implementations:
168//! - `base.rs`: Core traits (Strategable, BasicAble, Positionable, etc.)
169//! - **Single Leg**: `long_call.rs`, `short_call.rs`, `long_put.rs`, `short_put.rs`
170//! - **Spreads**: `bull_call_spread.rs`, `bear_call_spread.rs`, `bull_put_spread.rs`, `bear_put_spread.rs`
171//! - **Butterflies**: `long_butterfly_spread.rs`, `short_butterfly_spread.rs`, `call_butterfly.rs`
172//! - **Complex**: `iron_condor.rs`, `iron_butterfly.rs`
173//! - **Volatility**: `long_straddle.rs`, `short_straddle.rs`, `long_strangle.rs`, `short_strangle.rs`
174//! - **Income**: `covered_call.rs`, `poor_mans_covered_call.rs`
175//! - **Protection**: `protective_put.rs`, `collar.rs`
176//! - `custom.rs`: Flexible custom strategy framework
177//! - `probabilities/`: Probability analysis for strategy outcomes
178//! - `delta_neutral/`: Delta neutrality analysis and adjustment
179//!
180//! ### **Volatility** (`volatility/`)
181//! Volatility modeling and analysis:
182//! - `utils.rs`: Implied volatility calculation (Newton-Raphson method)
183//! - `traits.rs`: Volatility model interfaces
184//! - Advanced volatility surface construction
185//!
186//! ### **Greeks** (`greeks/`)
187//! Complete Greeks calculation suite:
188//! - Delta, Gamma, Theta, Vega, Rho, Vanna, Vomma, Veta, Charm, Color calculations
189//! - Real-time sensitivity analysis
190//! - Greeks-based risk management
191//!
192//! ### **Chains** (`chains/`)
193//! Option chain management and analysis:
194//! - `chain.rs`: Option chain construction and manipulation
195//! - `utils.rs`: Chain analysis and filtering tools
196//! - CSV/JSON import/export functionality
197//! - Strike price generation algorithms
198//!
199//! ### **Backtesting** (`backtesting/`)
200//! Strategy performance analysis:
201//! - `metrics.rs`: Performance metrics calculation
202//! - `results.rs`: Backtesting results management
203//! - `types.rs`: Backtesting data structures
204//!
205//! ### **Simulation** (`simulation/`)
206//! Monte Carlo and stochastic simulations:
207//! - Random walk implementations
208//! - Telegraph process modeling
209//! - Custom simulation frameworks
210//! - Parametrized simulation tools
211//!
212//! ### **Visualization** (`visualization/`)
213//! Comprehensive plotting and charting:
214//! - `plotly.rs`: Interactive charts with Plotly integration
215//! - Strategy payoff diagrams
216//! - Greeks visualization
217//! - 3D volatility surfaces
218//! - Risk profile charts
219//!
220//! ### **Metrics** (`metrics/`)
221//! Performance, risk, and liquidity metrics analysis:
222//! - **Price Metrics**: Volatility skew curves
223//! - **Risk Metrics**:
224//!   - Implied Volatility curves (by strike) and surfaces (strike vs time)
225//!   - Risk Reversal curves (by strike)
226//!   - Dollar Gamma curves (by strike)
227//! - **Composite Metrics**:
228//!   - Vanna-Volga Hedge surfaces (price vs volatility)
229//!   - Delta-Gamma Profile curves (by strike) and surfaces (price vs time)
230//!   - Smile Dynamics curves (by strike) and surfaces (strike vs time)
231//! - **Liquidity Metrics**:
232//!   - Bid-Ask Spread curves (by strike)
233//!   - Volume Profile curves (by strike) and surfaces (strike vs time)
234//!   - Open Interest Distribution curves (by strike)
235//! - **Stress Metrics**:
236//!   - Volatility Sensitivity curves (by strike) and surfaces (price vs volatility)
237//!   - Time Decay Profile curves (by strike) and surfaces (price vs time)
238//!   - Price Shock Impact curves (by strike) and surfaces (price vs volatility)
239//! - **Temporal Metrics**:
240//!   - Theta curves (by strike) and surfaces (price vs time)
241//!   - Charm (Delta Decay) curves (by strike) and surfaces (price vs time)
242//!   - Color (Gamma Decay) curves (by strike) and surfaces (price vs time)
243//!
244//! ### **Risk Management** (`risk/`)
245//! Risk analysis and management tools:
246//! - Position risk metrics
247//! - Break-even analysis
248//! - Risk profile generation
249//!
250//! ### **P&L** (`pnl/`)
251//! Profit and loss calculation:
252//! - Real-time P&L tracking
253//! - Historical P&L analysis
254//! - Performance attribution
255//!
256//! ### **Curves & Surfaces** (`curves/`, `surfaces/`)
257//! Mathematical tools for financial modeling:
258//! - Curve interpolation techniques
259//! - Surface construction and analysis
260//! - 3D visualization capabilities
261//!
262//! ### **Error Handling** (`error/`)
263//! Robust error management:
264//! - Comprehensive error types for each module
265//! - Type-safe error propagation
266//! - Detailed error reporting
267//!
268//! ## Core Components
269//!
270//! ```mermaid
271//! classDiagram
272//! class Options {
273//! +option_type: OptionType
274//! +side: Side
275//! +underlying_symbol: String
276//! +strike_price: Positive
277//! +expiration_date: ExpirationDate
278//! +implied_volatility: Positive
279//! +quantity: Positive
280//! +underlying_price: Positive
281//! +risk_free_rate: Decimal
282//! +option_style: OptionStyle
283//! +dividend_yield: Positive
284//! +exotic_params: Option~ExoticParams~
285//! +calculate_price_black_scholes()
286//! +calculate_price_binomial()
287//! +time_to_expiration()
288//! +is_long()
289//! +is_short()
290//! +validate()
291//! +to_plot()
292//! +calculate_implied_volatility()
293//! +delta()
294//! +gamma()
295//! +theta()
296//! +vega()
297//! +rho()
298//! +vanna()
299//! +vomma()
300//! +veta()
301//! +charm()
302//! +color()
303//! }
304//!
305//! class Position {
306//! +option: Options
307//! +position_cost: Positive
308//! +entry_date: DateTime<Utc>
309//! +open_fee: Positive
310//! +close_fee: Positive
311//! +net_cost()
312//! +net_premium_received()
313//! +unrealized_pnl()
314//! +pnl_at_expiration()
315//! +validate()
316//! }
317//!
318//! class Leg {
319//! <<enumeration>>
320//! Option(Position)
321//! Spot(SpotPosition)
322//! Future(FuturePosition)
323//! Perpetual(PerpetualPosition)
324//! +is_option()
325//! +is_spot()
326//! +is_linear()
327//! +delta()
328//! +pnl_at_price()
329//! }
330//!
331//! class SpotPosition {
332//! +symbol: String
333//! +quantity: Positive
334//! +cost_basis: Positive
335//! +side: Side
336//! +date: DateTime<Utc>
337//! +open_fee: Positive
338//! +close_fee: Positive
339//! +pnl_at_price()
340//! +delta()
341//! +market_value()
342//! +break_even_price()
343//! }
344//!
345//! class ExpirationDate {
346//! +Days(Positive)
347//! +Date(NaiveDate)
348//! +get_years()
349//! +get_date()
350//! +get_date_string()
351//! +from_string()
352//! }
353//!
354//! class Positive {
355//! +value: Decimal
356//! +ZERO: Positive
357//! +ONE: Positive
358//! +format_fixed_places()
359//! +round_to_nice_number()
360//! +is_positive()
361//! }
362//!
363//! class OptionStyle {
364//! <<enumeration>>
365//! Call
366//! Put
367//! }
368//!
369//! class OptionType {
370//! <<enumeration>>
371//! European
372//! American
373//! Bermuda
374//! Asian
375//! Barrier
376//! Binary
377//! Lookback
378//! Compound
379//! Chooser
380//! Cliquet
381//! Rainbow
382//! Spread
383//! Quanto
384//! Exchange
385//! Power
386//! }
387//!
388//! class Side {
389//! <<enumeration>>
390//! Long
391//! Short
392//! }
393//!
394//! class Graph {
395//! <<interface>>
396//! +graph_data()
397//! +graph_config()
398//! +to_plot()
399//! +write_html()
400//! +write_png()
401//! +write_svg()
402//! +write_jpeg()
403//! }
404//!
405//! class Greeks {
406//! <<interface>>
407//! +delta()
408//! +gamma()
409//! +theta()
410//! +vega()
411//! +rho()
412//! +calculate_all_greeks()
413//! }
414//!
415//! Options --|> Greeks : implements
416//! Options --|> Graph : implements
417//! Position o-- Options : contains
418//! Leg o-- Position : Option variant
419//! Leg o-- SpotPosition : Spot variant
420//! SpotPosition *-- Side : has
421//! SpotPosition *-- Positive : uses
422//! Options *-- OptionStyle : has
423//! Options *-- OptionType : has
424//! Options *-- Side : has
425//! Options *-- ExpirationDate : has
426//! Options *-- Positive : uses
427//! ```
428//!
429//! ## Pricing Models Architecture
430//!
431//! ```mermaid
432//! flowchart TB
433//!     subgraph Standard["Standard Options"]
434//!         EU[European]
435//!         AM[American]
436//!         BE[Bermuda]
437//!     end
438//!
439//!     subgraph PathDependent["Path-Dependent"]
440//!         AS[Asian]
441//!         LB[Lookback]
442//!         BA[Barrier]
443//!         CL[Cliquet]
444//!     end
445//!
446//!     subgraph MultiAsset["Multi-Asset"]
447//!         RB[Rainbow]
448//!         SP[Spread]
449//!         EX[Exchange]
450//!     end
451//!
452//!     subgraph Special["Special Payoffs"]
453//!         BI[Binary]
454//!         PW[Power]
455//!         QU[Quanto]
456//!         CO[Compound]
457//!         CH[Chooser]
458//!     end
459//!
460//!     BS[black_scholes] --> EU
461//!     BS --> PathDependent
462//!     BS --> MultiAsset
463//!     BS --> Special
464//!     BAW[barone_adesi_whaley] --> AM
465//!     BIN[binomial_model] --> AM
466//!     BIN --> BE
467//!     MC[monte_carlo] --> PathDependent
468//! ```
469//!
470//! ## Strategy Traits System
471//!
472//! ```mermaid
473//! classDiagram
474//!     class Strategable {
475//!         <<trait>>
476//!         Master trait combining all capabilities
477//!     }
478//!
479//!     class BasicAble {
480//!         <<trait>>
481//!         +get_underlying_price()
482//!         +get_underlying_symbol()
483//!         +get_expiration()
484//!         +get_title()
485//!     }
486//!
487//!     class Positionable {
488//!         <<trait>>
489//!         +get_positions()
490//!         +add_position()
491//!         +modify_position()
492//!     }
493//!
494//!     class Strategies {
495//!         <<trait>>
496//!         +get_net_premium_received()
497//!         +get_max_profit()
498//!         +get_max_loss()
499//!         +get_total_cost()
500//!     }
501//!
502//!     class BreakEvenable {
503//!         <<trait>>
504//!         +get_break_even_points()
505//!         +calculate_break_even()
506//!     }
507//!
508//!     class Profit {
509//!         <<trait>>
510//!         +get_point_at_price()
511//!         +calculate_profit_at()
512//!     }
513//!
514//!     class Greeks {
515//!         <<trait>>
516//!         +delta()
517//!         +gamma()
518//!         +theta()
519//!         +vega()
520//!     }
521//!
522//!     class DeltaNeutrality {
523//!         <<trait>>
524//!         +get_delta()
525//!         +suggest_delta_adjustments()
526//!     }
527//!
528//!     class Graph {
529//!         <<trait>>
530//!         +to_plot()
531//!         +write_html()
532//!         +write_png()
533//!     }
534//!
535//!     Strategable --|> BasicAble
536//!     Strategable --|> Positionable
537//!     Strategable --|> Strategies
538//!     Strategable --|> BreakEvenable
539//!     Strategable --|> Profit
540//!     Strategable --|> Greeks
541//!     Strategable --|> DeltaNeutrality
542//!     Strategable --|> Graph
543//! ```
544//!
545//! ## Metrics Framework
546//!
547//! ```mermaid
548//! flowchart LR
549//!     subgraph OptionChain
550//!         OC[OptionChain]
551//!     end
552//!
553//!     subgraph Curves["Curve Metrics"]
554//!         IV_C[IV Curve]
555//!         RR_C[Risk Reversal]
556//!         DG_C[Dollar Gamma]
557//!         TH_C[Theta Curve]
558//!         VA_C[Vanna Curve]
559//!         SK_C[Skew Curve]
560//!     end
561//!
562//!     subgraph Surfaces["Surface Metrics"]
563//!         IV_S[IV Surface]
564//!         TH_S[Theta Surface]
565//!         CH_S[Charm Surface]
566//!         VS_S[Vol Sensitivity]
567//!         TD_S[Time Decay]
568//!     end
569//!
570//!     OC --> Curves
571//!     OC --> Surfaces
572//!     Curves --> |"2D Analysis"| Analysis[Risk Analysis]
573//!     Surfaces --> |"3D Analysis"| Analysis
574//! ```
575//!
576//! ## Trading Strategies
577//!
578//! OptionStratLib provides 25+ comprehensive trading strategies organized by complexity and market outlook:
579//!
580//! ### **Single Leg Strategies**
581//! Basic directional strategies for beginners:
582//! - **Long Call**: Bullish strategy with unlimited upside potential
583//! - **Short Call**: Bearish strategy collecting premium with limited profit
584//! - **Long Put**: Bearish strategy with high profit potential
585//! - **Short Put**: Bullish strategy collecting premium with assignment risk
586//!
587//! ### **Spread Strategies**
588//! Defined risk strategies with limited profit/loss:
589//! - **Bull Call Spread**: Moderately bullish with limited risk and reward
590//! - **Bear Call Spread**: Moderately bearish credit spread
591//! - **Bull Put Spread**: Moderately bullish credit spread
592//! - **Bear Put Spread**: Moderately bearish debit spread
593//!
594//! ### **Butterfly Strategies**
595//! Market neutral strategies profiting from low volatility:
596//! - **Long Butterfly Spread**: Profits from price staying near middle strike
597//! - **Short Butterfly Spread**: Profits from price moving away from middle strike
598//! - **Call Butterfly**: Butterfly using only call options
599//!
600//! ### **Complex Multi-Leg Strategies**
601//! Advanced strategies for experienced traders:
602//! - **Iron Condor**: Market neutral strategy with wide profit zone
603//! - **Iron Butterfly**: Market neutral strategy with narrow profit zone
604//!
605//! ### **Volatility Strategies**
606//! Strategies that profit from volatility changes:
607//! - **Long Straddle**: Profits from high volatility in either direction
608//! - **Short Straddle**: Profits from low volatility (range-bound market)
609//! - **Long Strangle**: Similar to straddle but with different strikes
610//! - **Short Strangle**: Credit strategy profiting from low volatility
611//!
612//! ### **Income Generation Strategies**
613//! Strategies focused on generating regular income:
614//! - **Covered Call**: Stock/spot ownership with call selling for income (now with full spot leg support)
615//! - **Poor Man's Covered Call**: LEAPS-based covered call alternative
616//!
617//! ### **Protection Strategies**
618//! Risk management and hedging strategies:
619//! - **Protective Put**: Downside protection for stock positions
620//! - **Collar**: Combination of covered call and protective put
621//!
622//! ### **Custom Strategy Framework**
623//! - **Custom Strategy**: Flexible framework for creating any multi-leg strategy
624//! - Supports unlimited number of legs
625//! - Full integration with all analysis tools
626//! - Complete trait implementation for consistency
627//!
628//! ### **Strategy Analysis Features**
629//! All strategies include comprehensive analysis capabilities:
630//! - **Profit/Loss Analysis**: P&L at any price point and time
631//! - **Break-Even Points**: Multiple break-even calculations
632//! - **Greeks Analysis**: Real-time risk metrics
633//! - **Probability Analysis**: Success probability calculations
634//! - **Delta Neutrality**: Delta-neutral position analysis
635//! - **Visualization**: Interactive payoff diagrams and risk profiles
636//! - **Optimization**: Find optimal strikes and expirations
637//!
638//! ### **Strategy Traits System**
639//! All strategies implement a comprehensive trait system:
640//!
641//! - **Strategable**: Master trait combining all strategy capabilities
642//! - **BasicAble**: Basic strategy information (symbol, price, etc.)
643//! - **Positionable**: Position management and modification
644//! - **Strategies**: Core strategy calculations (P&L, break-even, etc.)
645//! - **Validable**: Strategy validation and error checking
646//! - **BreakEvenable**: Break-even point calculations
647//! - **Profit**: Profit/loss analysis at various price points
648//! - **Greeks**: Greeks calculations for risk management
649//! - **DeltaNeutrality**: Delta-neutral analysis and adjustments
650//! - **ProbabilityAnalysis**: Outcome probability calculations
651//! - **Graph**: Visualization and plotting capabilities
652//!
653//! ## Setup Instructions
654//!
655//! ### Prerequisites
656//!
657//! - Rust 1.80 or higher (2024 edition)
658//! - Cargo package manager
659//!
660//! ### Installation
661//!
662//! Add OptionStratLib to your `Cargo.toml`:
663//!
664//! ```toml
665//! [dependencies]
666//! optionstratlib = "0.15.1"
667//! ```
668//!
669//! Or use cargo to add it to your project:
670//!
671//! ```bash
672//! cargo add optionstratlib
673//! ```
674//!
675//! ### Optional Features
676//!
677//! The library includes optional features for enhanced functionality:
678//!
679//! ```toml
680//! [dependencies]
681//! optionstratlib = { version = "0.15.1", features = ["plotly"] }
682//! ```
683//!
684//! - `plotly`: Enables interactive visualization using plotly.rs
685//! - `async`: Enables asynchronous I/O operations for OptionChain and OHLCV data
686//!
687//! ### Building from Source
688//!
689//! Clone the repository and build using Cargo:
690//!
691//! ```bash
692//! git clone https://github.com/joaquinbejar/OptionStratLib.git
693//! cd OptionStratLib
694//! cargo build --release
695//! ```
696//!
697//! Run comprehensive test suite:
698//!
699//! ```bash
700//! cargo test --all-features
701//! ```
702//!
703//! Generate documentation:
704//!
705//! ```bash
706//! cargo doc --open --all-features
707//! ```
708//!
709//! Run benchmarks:
710//!
711//! ```bash
712//! cargo bench
713//! ```
714//!
715//! ## Library Usage
716//!
717//! ### Basic Option Creation and Pricing
718//!
719//! ```rust
720//! use optionstratlib::{Options, OptionStyle, OptionType, Side, ExpirationDate};
721//! use positive::{pos_or_panic,Positive};
722//! use rust_decimal_macros::dec;
723//! use optionstratlib::greeks::Greeks;
724//!
725//! // Create a European call option
726//! let option = Options::new(
727//!     OptionType::European,
728//!     Side::Long,
729//!     "AAPL".to_string(),
730//!     pos_or_panic!(150.0),            // strike_price
731//!     ExpirationDate::Days(pos_or_panic!(30.0)),
732//!     pos_or_panic!(0.25),             // implied_volatility
733//!     Positive::ONE,              // quantity
734//!     pos_or_panic!(155.0),            // underlying_price
735//!     dec!(0.05),             // risk_free_rate
736//!     OptionStyle::Call,
737//!     pos_or_panic!(0.02),             // dividend_yield
738//!     None,                   // exotic_params
739//! );
740//!
741//! // Calculate option price using Black-Scholes
742//! let price = option.calculate_price_black_scholes().unwrap();
743//! tracing::info!("Option price: ${:.2}", price);
744//!
745//! // Calculate Greeks for risk management
746//! let delta = option.delta().unwrap();
747//! let gamma = option.gamma().unwrap();
748//! let theta = option.theta().unwrap();
749//! let vega = option.vega().unwrap();
750//! let vanna = option.vanna().unwrap();
751//! let vomma = option.vomma().unwrap();
752//! let veta = option.veta().unwrap();
753//! let charm = option.charm().unwrap();
754//! let color = option.color().unwrap();
755//! tracing::info!("Greeks - Delta: {:.4}, Gamma: {:.4}, Theta: {:.4},
756//!     Vega: {:.4}, Vanna: {:.4}, Vomma: {:.4}, Veta: {:.4}
757//!     Charm: {:.4}, Color: {:.4}",
758//!     delta, gamma, theta, vega, vanna, vomma, veta, charm, color);
759//! ```
760//!
761//! ### Working with Trading Strategies
762//!
763//! ```rust
764//! use positive::{Positive, pos_or_panic};
765//! use optionstratlib::ExpirationDate;
766//! use optionstratlib::strategies::Strategies;
767//! use optionstratlib::strategies::bull_call_spread::BullCallSpread;
768//! use optionstratlib::strategies::base::{BreakEvenable, BasicAble};
769//! use optionstratlib::visualization::Graph;
770//! use rust_decimal_macros::dec;
771//! use std::error::Error;
772//!
773//! fn main() -> Result<(), Box<dyn Error>> {
774//!     use optionstratlib::pricing::Profit;
775//! let underlying_price = Positive::HUNDRED;
776//!
777//!     // Create a Bull Call Spread strategy
778//!     let strategy = BullCallSpread::new(
779//!         "AAPL".to_string(),
780//!         underlying_price,
781//!         pos_or_panic!(95.0),   // long_strike
782//!         pos_or_panic!(105.0),  // short_strike  
783//!         ExpirationDate::Days(pos_or_panic!(30.0)),
784//!         pos_or_panic!(0.25),   // implied_volatility
785//!         dec!(0.05),   // risk_free_rate
786//!         pos_or_panic!(2.50),   // long_call_premium
787//!         pos_or_panic!(2.50),   // long_call_open_fee
788//!         pos_or_panic!(1.20),   // short_call_premium
789//!         pos_or_panic!(1.20),   // short_call_close_fee
790//!         Default::default(), Default::default(),
791//!         Default::default(), Default::default()
792//!     );
793//!
794//!     // Analyze the strategy
795//!     tracing::info!("Strategy: {}", strategy.get_title());
796//!     tracing::info!("Break-even points: {:?}", strategy.get_break_even_points()?);
797//!     tracing::info!("Max profit: ${:.2}", strategy.get_max_profit().unwrap_or(Positive::ZERO));
798//!     tracing::info!("Max loss: ${:.2}", strategy.get_max_loss().unwrap_or(Positive::ZERO));
799//!     tracing::info!("Net premium: ${:.2}", strategy.get_net_premium_received()?);
800//!
801//!     // Calculate P&L at different price points
802//!     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)];
803//!     for price in prices {
804//!         let pnl = strategy.get_point_at_price(&price)?;
805//!         tracing::info!("P&L at ${}: ${:.2}", price, pnl.0);
806//!     }
807//!
808//!     // Generate visualization
809//!     #[cfg(feature = "plotly")]
810//!     {
811//!         strategy.write_html("Draws/Visualization/bull_call_spread.html".as_ref())?;
812//!     }
813//!
814//!     Ok(())
815//! }
816//! ```
817//!
818//! ### Advanced Features: Volatility Analysis
819//!
820//! ```rust
821//! use optionstratlib::prelude::*;
822//!
823//! fn main() -> Result<(), Box<dyn std::error::Error>> {
824//!     // Create an option for implied volatility calculation
825//!     let mut option = Options::new(
826//!         OptionType::European,
827//!         Side::Long,
828//!         "AAPL".to_string(),
829//!         pos_or_panic!(105.0), // strike
830//!         ExpirationDate::Days(pos_or_panic!(90.0)),
831//!         pos_or_panic!(0.20), // initial IV guess
832//!         Positive::ONE, // quantity
833//!         Positive::HUNDRED, // underlying price
834//!         dec!(0.05), // risk free rate
835//!         OptionStyle::Call,
836//!         pos_or_panic!(0.02), // dividend yield
837//!         None,
838//!     );
839//!
840//!     let market_price = pos_or_panic!(5.50);
841//!     let iv = implied_volatility(market_price, &mut option, 100)?;
842//!
843//!     tracing::info!("Implied volatility: {:.2}%", iv.to_f64() * 100.0);
844//!     Ok(())
845//! }
846//! ```
847//!
848//! ### Custom Strategy Creation
849//!
850//! ```rust
851//! use optionstratlib::prelude::*;
852//!
853//! // Define common parameters
854//! let underlying_symbol = "DAX".to_string();
855//! let underlying_price = pos_or_panic!(24000.0);
856//! let expiration = ExpirationDate::Days(pos_or_panic!(30.0));
857//! let implied_volatility = pos_or_panic!(0.25);
858//! let risk_free_rate = dec!(0.05);
859//! let dividend_yield = pos_or_panic!(0.02);
860//! let fee = Positive::TWO;
861//!
862//! // Create a long put option
863//! let long_put_option = Options::new(
864//!     OptionType::European,
865//!     Side::Long,
866//!     underlying_symbol.clone(),
867//!     pos_or_panic!(24070.0), // strike
868//!     expiration.clone(),
869//!     implied_volatility,
870//!     Positive::ONE, // quantity
871//!     underlying_price,
872//!     risk_free_rate,
873//!     OptionStyle::Put,
874//!     dividend_yield,
875//!     None,
876//! );
877//! let long_put = Position::new(
878//!     long_put_option,
879//!     pos_or_panic!(150.0), // premium
880//!     Utc::now(),
881//!     fee,
882//!     fee,
883//!     None,
884//!     None,
885//! );
886//!
887//! // Create a long call option  
888//! let long_call_option = Options::new(
889//!     OptionType::European,
890//!     Side::Long,
891//!     underlying_symbol.clone(),
892//!     pos_or_panic!(24030.0), // strike
893//!     expiration.clone(),
894//!     implied_volatility,
895//!     Positive::ONE, // quantity
896//!     underlying_price,
897//!     risk_free_rate,
898//!     OptionStyle::Call,
899//!     dividend_yield,
900//!     None,
901//! );
902//! let long_call = Position::new(
903//!     long_call_option,
904//!     pos_or_panic!(120.0), // premium
905//!     Utc::now(),
906//!     fee,
907//!     fee,
908//!     None,
909//!     None,
910//! );
911//!
912//! // Create CustomStrategy with the positions
913//! let positions = vec![long_call, long_put];
914//! let strategy = CustomStrategy::new(
915//!     "DAX Straddle Strategy".to_string(),
916//!     underlying_symbol,
917//!     "A DAX long straddle strategy".to_string(),
918//!     underlying_price,
919//!     positions,
920//!     Positive::ONE,
921//!     30,
922//!     implied_volatility,
923//! );
924//!
925//! tracing::info!("Strategy created: {}", strategy.get_title());
926//! ```
927//!
928//! ## Testing
929//!
930//! OptionStratLib includes a comprehensive test suite with over 3800 unit and integration tests:
931//!
932//! ### **Running Tests**
933//!
934//! Run all tests:
935//! ```bash
936//! cargo test --all-features
937//! ```
938//!
939//! Run tests for specific modules:
940//! ```bash
941//! cargo test strategies::bull_call_spread
942//! cargo test pricing::black_scholes
943//! cargo test volatility::utils
944//! ```
945//!
946//! Run tests with output:
947//! ```bash
948//! cargo test -- --nocapture
949//! ```
950//!
951//! ### **Test Categories**
952//!
953//! - **Unit Tests**: Individual function and method testing
954//! - **Integration Tests**: Cross-module functionality testing
955//! - **Strategy Tests**: Comprehensive strategy validation
956//! - **Pricing Model Tests**: Accuracy and performance testing
957//! - **Greeks Tests**: Mathematical precision validation
958//! - **Visualization Tests**: Chart generation and export testing
959//! - **Property-Based Tests**: Mathematical invariant testing with `proptest`
960//! - **Exotic Options Tests**: Complete coverage for all 14 exotic option types
961//!
962//! ### **Benchmarking**
963//!
964//! Run performance benchmarks:
965//! ```bash
966//! cargo bench
967//! ```
968//!
969//! Generate test coverage report:
970//! ```bash
971//! cargo tarpaulin --all-features --out Html
972//! ```
973//!
974//! ## Examples
975//!
976//! The library includes extensive examples organized by functionality:
977//!
978//! - **`examples/examples_strategies/`**: Complete strategy examples (25+ strategies)
979//! - **`examples/examples_chains/`**: Option chain analysis examples
980//! - **`examples/examples_pricing/`**: Pricing model demonstrations
981//! - **`examples/examples_visualization/`**: Interactive chart examples
982//! - **`examples/examples_volatility/`**: Volatility analysis examples
983//! - **`examples/examples_simulation/`**: Monte Carlo and simulation examples
984//! - **`examples/examples_exotics/`**: Exotic option pricing examples
985//!
986//! Run examples:
987//! ```bash
988//! cargo run --example bull_call_spread --features plotly
989//! cargo run --example black_scholes_pricing
990//! cargo run --example volatility_surface
991//! ```
992//!
993//! ## Contribution and Contact
994//!
995//! ### **Contributing**
996//!
997//! Contributions are welcome! Please follow these guidelines:
998//!
999//! 1. **Fork** the repository
1000//! 2. **Create** a feature branch: `git checkout -b feature/amazing-feature`
1001//! 3. **Commit** your changes: `git commit -m 'Add amazing feature'`
1002//! 4. **Push** to the branch: `git push origin feature/amazing-feature`
1003//! 5. **Open** a Pull Request
1004//!
1005//! ### **Development Setup**
1006//!
1007//! ```bash
1008//! git clone https://github.com/joaquinbejar/OptionStratLib.git
1009//! cd OptionStratLib
1010//! cargo build --all-features
1011//! cargo test --all-features
1012//! ```
1013//!
1014//! ### **Code Quality**
1015//!
1016//! - All code must pass `cargo clippy` without warnings
1017//! - Format code with `cargo fmt`
1018//! - Add tests for new functionality
1019//! - Update documentation for API changes
1020//! - Follow Rust 2024 edition best practices
1021//!
1022//!
1023//! ### **Support**
1024//!
1025//! - **Issues**: Report bugs and request features on GitHub
1026//! - **Discussions**: Join community discussions on GitHub Discussions
1027//! - **Documentation**: Comprehensive docs available at docs.rs
1028//!
1029//! ---
1030//!
1031//! **OptionStratLib v0.15.1** - Built with ❤️ in Rust for the financial community
1032//!
1033
1034/// # OptionsStratLib: Financial Options Trading Library
1035///
1036/// A comprehensive library for options trading analytics, modeling, and strategy development.
1037/// Provides tools for pricing, risk assessment, strategy building, and performance analysis
1038/// of financial options across various market conditions.
1039///
1040/// ## Core Modules
1041extern crate core;
1042
1043/// * `model` - Core data structures and models for options and derivatives.
1044///
1045/// Defines the fundamental data types and structures used throughout the library,
1046/// including option contract representations, position tracking, and market data models.
1047/// Serves as the foundation for all other modules.
1048/// NOTE: This module must be declared first to ensure macros (pos!, spos!) are available
1049/// to other modules.
1050pub mod model;
1051
1052/// * `backtesting` - Tools for historical performance evaluation of options strategies.
1053///
1054/// Provides framework and utilities to simulate and analyze how option strategies
1055/// would have performed using historical market data. Supports various performance
1056/// metrics, drawdown analysis, and strategy comparison.
1057pub mod backtesting;
1058
1059/// * `chains` - Functionality for working with options chains and series data.
1060///
1061/// Tools for parsing, manipulating, and analyzing options chain data. Includes
1062/// methods to filter chains by expiration, strike price, and other criteria,
1063/// as well as utilities for chain visualization and analysis.
1064pub mod chains;
1065
1066/// * `constants` - Library-wide mathematical and financial constants.
1067///
1068/// Defines fundamental constants used throughout the library including mathematical
1069/// constants (π, epsilon values), market standards (trading days per year),
1070/// calculation parameters, and visualization color schemes.
1071pub mod constants;
1072
1073/// * `curves` - Tools for yield curves, term structures, and other financial curves.
1074///
1075/// Implementations of various interest rate curves, forward curves, and term structures
1076/// used in options pricing and risk management. Includes interpolation methods and
1077/// curve fitting algorithms.
1078pub mod curves;
1079
1080/// * `error` - Error types and handling functionality for the library.
1081///
1082/// Defines the error hierarchy used throughout the library, providing detailed
1083/// error types for different categories of failures including validation errors,
1084/// calculation errors, and input/output errors.
1085pub mod error;
1086
1087/// * `geometrics` - Mathematical utilities for geometric calculations relevant to options.
1088///
1089/// Provides specialized geometric functions and algorithms for options pricing and modeling,
1090/// including path-dependent calculations and spatial transformations for volatility surfaces.
1091pub mod geometrics;
1092
1093/// * `greeks` - Calculation and management of option sensitivity metrics (Delta, Gamma, etc.).
1094///
1095/// Comprehensive implementation of options Greeks (sensitivity measures) including
1096/// Delta, Gamma, Theta, Vega, Rho, Vanna, Vomma, Veta, Charm and Color. Includes analytical
1097/// formulas, numerical approximations, and visualization tools for risk analysis.
1098pub mod greeks;
1099
1100/// * `metrics` - Performance and risk metrics analysis for options.
1101///
1102/// Comprehensive tools for performance and risk analysis including:
1103/// - **Price Metrics**: Volatility skew analysis
1104/// - **Risk Metrics**: Implied volatility curves/surfaces, risk reversal curves, dollar gamma curves
1105///
1106/// ## Risk Metrics
1107///
1108/// The risk metrics module provides key tools for assessing market risk, sentiment, and exposure:
1109///
1110/// | Metric | Curve (by strike) | Surface (strike vs time) |
1111/// |--------|-------------------|--------------------------|
1112/// | Implied Volatility | `iv_curve()` | `iv_surface(days)` |
1113/// | Risk Reversal | `risk_reversal_curve()` | - |
1114/// | Dollar Gamma | `dollar_gamma_curve(style)` | - |
1115///
1116/// ### Implied Volatility
1117/// Shows how IV varies across strikes and time horizons. Essential for understanding
1118/// market expectations and pricing options.
1119///
1120/// ### Risk Reversal
1121/// Measures the difference between call and put implied volatilities, indicating
1122/// market sentiment (bullish vs bearish bias).
1123///
1124/// ### Dollar Gamma
1125/// Gamma exposure in monetary terms: `Dollar Gamma = Gamma × Spot² × 0.01`
1126/// Shows how much delta changes for a 1% move in the underlying.
1127pub mod metrics;
1128
1129/// * `pnl` - Profit and loss analysis tools for options positions.
1130///
1131/// Utilities for calculating, projecting, and visualizing profit and loss (P&L) profiles
1132/// for individual options and complex strategies. Includes time-based P&L evolution and
1133/// scenario analysis.
1134pub mod pnl;
1135
1136/// * `pricing` - Option pricing models including Black-Scholes and numerical methods.
1137///
1138/// Implementations of various option pricing models including Black-Scholes-Merton,
1139/// binomial trees, Monte Carlo simulation, and finite difference methods. Supports
1140/// European, American, and exotic options.
1141pub mod pricing;
1142
1143/// * `risk` - Risk assessment and management tools for options portfolios.
1144///
1145/// Tools for analyzing and quantifying risk in options positions and portfolios,
1146/// including Value at Risk (VaR), stress testing, scenario analysis, and
1147/// portfolio optimization algorithms.
1148pub mod risk;
1149
1150/// * `simulation` - Simulation techniques for scenario analysis.
1151///
1152/// Framework for Monte Carlo and other simulation methods to model potential
1153/// market scenarios and their impact on options strategies. Includes path generation
1154/// algorithms and statistical analysis of simulation results.
1155pub mod simulation;
1156
1157/// * `strategies` - Pre-defined option strategy templates and building blocks.
1158///
1159/// Library of common option strategies (spreads, straddles, condors, etc.) with
1160/// implementation helpers, parameter optimization, and analysis tools. Supports
1161/// strategy composition and customization.
1162pub mod strategies;
1163
1164/// * `surfaces` - Volatility surface and other 3D financial data modeling.
1165///
1166/// Tools for constructing, manipulating, and analyzing volatility surfaces and
1167/// other three-dimensional financial data structures. Includes interpolation methods,
1168/// fitting algorithms, and visualization utilities.
1169pub mod surfaces;
1170
1171/// * `utils` - General utility functions for data manipulation and calculations.
1172///
1173/// Collection of helper functions and utilities used across the library for
1174/// data manipulation, mathematical operations, date handling, and other
1175/// common tasks in financial calculations.
1176pub mod utils;
1177
1178/// * `visualization` - Tools for plotting and visual representation of options data.
1179///
1180/// Graphics and visualization utilities for creating charts, graphs, and interactive
1181/// plots of options data, strategies, and analytics. Supports various plot types
1182/// optimized for different aspects of options analysis.
1183pub mod visualization;
1184
1185/// * `volatility` - Volatility modeling, forecasting, and analysis utilities.
1186///
1187/// Comprehensive tools for volatility analysis including historical volatility calculation,
1188/// implied volatility determination, volatility forecasting models (GARCH, EWMA), and
1189/// volatility skew/smile analysis.
1190pub mod volatility;
1191
1192/// * `series` - Functionality for working with collections of option chains across expirations.
1193///
1194/// Provides tools to manage, filter, and analyze multiple option chains grouped by expiration dates.
1195/// Includes utilities for constructing series data, navigating expirations, and performing
1196/// cross-expiration analysis and visualization.
1197pub mod series;
1198
1199/// * `prelude` - Convenient re-exports of commonly used types and traits.
1200///
1201/// The prelude module provides a single import point for the most frequently used
1202/// types, traits, and functions from the OptionStratLib library. This reduces the
1203/// amount of boilerplate imports needed when working with the library.
1204pub mod prelude;
1205
1206pub use model::ExpirationDate;
1207pub use model::Options;
1208pub use model::types::{OptionStyle, OptionType, RainbowType, Side};
1209
1210/// Library version
1211pub const VERSION: &str = env!("CARGO_PKG_VERSION");
1212
1213/// Returns the library version
1214pub fn version() -> &'static str {
1215    VERSION
1216}