optionstratlib/lib.rs
1#![allow(unknown_lints)]
2#![allow(clippy::literal_string_with_formatting_args)]
3
4//! # OptionStratLib v0.10.0: 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//!
32//! ### 2. **Greeks Calculation**
33//! - Complete Greeks suite: Delta, Gamma, Theta, Vega, Rho
34//! - Real-time sensitivity analysis
35//! - Greeks visualization and risk profiling
36//! - Custom Greeks implementations with adjustable parameters
37//!
38//! ### 3. **Volatility Models**
39//! - Implied volatility calculation using Newton-Raphson method
40//! - Volatility surface construction and interpolation
41//! - Historical volatility estimation
42//! - Advanced volatility modeling tools
43//!
44//! ### 4. **Option Chain Management**
45//! - Complete option chain construction and analysis
46//! - Strike price generation algorithms
47//! - Chain data import/export (CSV/JSON formats)
48//! - Advanced filtering and selection tools
49//! - Option data grouping and organization
50//!
51//! ### 5. **Trading Strategies (25+ Strategies)**
52//! - **Single Leg**: Long/Short Calls and Puts
53//! - **Spreads**: Bull/Bear Call/Put Spreads
54//! - **Butterflies**: Long/Short Butterfly Spreads, Call Butterfly
55//! - **Complex**: Iron Condor, Iron Butterfly
56//! - **Volatility**: Long/Short Straddles and Strangles
57//! - **Income**: Covered Calls, Poor Man's Covered Call
58//! - **Protection**: Protective Puts, Collars
59//! - **Custom**: Flexible custom strategy framework
60//!
61//! ### 6. **Risk Management & Analysis**
62//! - Position tracking and management
63//! - Break-even analysis with multiple break-even points
64//! - Profit/Loss calculations at various price points
65//! - Risk profiles and comprehensive visualizations
66//! - Delta neutrality analysis and adjustment
67//! - Probability analysis for strategy outcomes
68//!
69//! ### 7. **Backtesting Framework**
70//! - Comprehensive backtesting engine
71//! - Performance metrics calculation
72//! - Strategy optimization tools
73//! - Historical analysis capabilities
74//!
75//! ### 8. **Simulation Tools**
76//! - Monte Carlo simulations for strategy testing
77//! - Telegraph process implementation
78//! - Random walk simulations
79//! - Custom simulation frameworks
80//! - Parametrized simulations with adjustable inputs
81//!
82//! ### 9. **Visualization & Plotting**
83//! - Strategy payoff diagrams
84//! - Greeks visualization
85//! - 3D volatility surfaces
86//! - Risk profiles and P&L charts
87//! - Interactive charts (powered by `plotly.rs`)
88//! - Binomial tree visualization
89//! - Comprehensive plotting utilities
90//!
91//! ### 10. **Data Management**
92//! - Efficient decimal-based calculations using `rust_decimal`
93//! - CSV/JSON import/export functionality
94//! - Time series data handling
95//! - Price series management and manipulation
96//! - Robust data validation and error handling
97//!
98//! ### 11. **Mathematical Tools**
99//! - Curve interpolation techniques
100//! - Surface construction and analysis
101//! - Geometric operations for financial modeling
102//! - Advanced mathematical utilities for options pricing
103//!
104//!
105//! ## Core Modules
106//!
107//! The library is organized into the following key modules:
108//!
109//! ### **Model** (`model/`)
110//! Core data structures and types for options trading:
111//! - `option.rs`: Complete option structures with pricing and Greeks
112//! - `position.rs`: Position management and P&L tracking
113//! - `expiration.rs`: Flexible expiration date handling (Days/DateTime)
114//! - `positive.rs`: Type-safe positive number implementation
115//! - `types.rs`: Common enums (OptionType, Side, OptionStyle)
116//! - `trade.rs`: Trade execution and management
117//! - `format.rs`: Data formatting utilities
118//!
119//! ### **Pricing Models** (`pricing/`)
120//! Advanced pricing engines for options valuation:
121//! - `black_scholes_model.rs`: European options pricing with Greeks
122//! - `binomial_model.rs`: American/European options with early exercise
123//! - `monte_carlo.rs`: Path-dependent and exotic options pricing
124//! - `telegraph.rs`: Jump-diffusion process modeling
125//! - `payoff.rs`: Payoff function implementations
126//!
127//! ### **Strategies** (`strategies/`)
128//! Comprehensive trading strategy implementations:
129//! - `base.rs`: Core traits (Strategable, BasicAble, Positionable, etc.)
130//! - **Single Leg**: `long_call.rs`, `short_call.rs`, `long_put.rs`, `short_put.rs`
131//! - **Spreads**: `bull_call_spread.rs`, `bear_call_spread.rs`, `bull_put_spread.rs`, `bear_put_spread.rs`
132//! - **Butterflies**: `long_butterfly_spread.rs`, `short_butterfly_spread.rs`, `call_butterfly.rs`
133//! - **Complex**: `iron_condor.rs`, `iron_butterfly.rs`
134//! - **Volatility**: `long_straddle.rs`, `short_straddle.rs`, `long_strangle.rs`, `short_strangle.rs`
135//! - **Income**: `covered_call.rs`, `poor_mans_covered_call.rs`
136//! - **Protection**: `protective_put.rs`, `collar.rs`
137//! - `custom.rs`: Flexible custom strategy framework
138//! - `probabilities/`: Probability analysis for strategy outcomes
139//! - `delta_neutral/`: Delta neutrality analysis and adjustment
140//!
141//! ### **Volatility** (`volatility/`)
142//! Volatility modeling and analysis:
143//! - `utils.rs`: Implied volatility calculation (Newton-Raphson method)
144//! - `traits.rs`: Volatility model interfaces
145//! - Advanced volatility surface construction
146//!
147//! ### **Greeks** (`greeks/`)
148//! Complete Greeks calculation suite:
149//! - Delta, Gamma, Theta, Vega, Rho calculations
150//! - Real-time sensitivity analysis
151//! - Greeks-based risk management
152//!
153//! ### **Chains** (`chains/`)
154//! Option chain management and analysis:
155//! - `chain.rs`: Option chain construction and manipulation
156//! - `utils.rs`: Chain analysis and filtering tools
157//! - CSV/JSON import/export functionality
158//! - Strike price generation algorithms
159//!
160//! ### **Backtesting** (`backtesting/`)
161//! Strategy performance analysis:
162//! - `metrics.rs`: Performance metrics calculation
163//! - `results.rs`: Backtesting results management
164//! - `types.rs`: Backtesting data structures
165//!
166//! ### **Simulation** (`simulation/`)
167//! Monte Carlo and stochastic simulations:
168//! - Random walk implementations
169//! - Telegraph process modeling
170//! - Custom simulation frameworks
171//! - Parametrized simulation tools
172//!
173//! ### **Visualization** (`visualization/`)
174//! Comprehensive plotting and charting:
175//! - `plotly.rs`: Interactive charts with Plotly integration
176//! - Strategy payoff diagrams
177//! - Greeks visualization
178//! - 3D volatility surfaces
179//! - Risk profile charts
180//!
181//! ### **Risk Management** (`risk/`)
182//! Risk analysis and management tools:
183//! - Position risk metrics
184//! - Break-even analysis
185//! - Risk profile generation
186//!
187//! ### **P&L** (`pnl/`)
188//! Profit and loss calculation:
189//! - Real-time P&L tracking
190//! - Historical P&L analysis
191//! - Performance attribution
192//!
193//! ### **Curves & Surfaces** (`curves/`, `surfaces/`)
194//! Mathematical tools for financial modeling:
195//! - Curve interpolation techniques
196//! - Surface construction and analysis
197//! - 3D visualization capabilities
198//!
199//! ### **Error Handling** (`error/`)
200//! Robust error management:
201//! - Comprehensive error types for each module
202//! - Type-safe error propagation
203//! - Detailed error reporting
204//!
205//! ## Core Components
206//!
207//! ```mermaid
208//! classDiagram
209//! class Options {
210//! +option_type: OptionType
211//! +side: Side
212//! +underlying_symbol: String
213//! +strike_price: Positive
214//! +expiration_date: ExpirationDate
215//! +implied_volatility: Positive
216//! +quantity: Positive
217//! +underlying_price: Positive
218//! +risk_free_rate: Decimal
219//! +option_style: OptionStyle
220//! +dividend_yield: Positive
221//! +exotic_params: Option~ExoticParams~
222//! +calculate_price_black_scholes()
223//! +calculate_price_binomial()
224//! +time_to_expiration()
225//! +is_long()
226//! +is_short()
227//! +validate()
228//! +to_plot()
229//! +calculate_implied_volatility()
230//! +delta()
231//! +gamma()
232//! +theta()
233//! +vega()
234//! +rho()
235//! }
236//!
237//! class Position {
238//! +option: Options
239//! +position_cost: Positive
240//! +entry_date: DateTime<Utc>
241//! +open_fee: Positive
242//! +close_fee: Positive
243//! +net_cost()
244//! +net_premium_received()
245//! +unrealized_pnl()
246//! +pnl_at_expiration()
247//! +validate()
248//! }
249//!
250//! class ExpirationDate {
251//! +Days(Positive)
252//! +Date(NaiveDate)
253//! +get_years()
254//! +get_date()
255//! +get_date_string()
256//! +from_string()
257//! }
258//!
259//! class Positive {
260//! +value: Decimal
261//! +ZERO: Positive
262//! +ONE: Positive
263//! +format_fixed_places()
264//! +round_to_nice_number()
265//! +is_positive()
266//! }
267//!
268//! class OptionStyle {
269//! <<enumeration>>
270//! Call
271//! Put
272//! }
273//!
274//! class OptionType {
275//! <<enumeration>>
276//! European
277//! American
278//! }
279//!
280//! class Side {
281//! <<enumeration>>
282//! Long
283//! Short
284//! }
285//!
286//! class Graph {
287//! <<interface>>
288//! +graph_data()
289//! +graph_config()
290//! +to_plot()
291//! +write_html()
292//! +write_png()
293//! +write_svg()
294//! +write_jpeg()
295//! }
296//!
297//! class Greeks {
298//! <<interface>>
299//! +delta()
300//! +gamma()
301//! +theta()
302//! +vega()
303//! +rho()
304//! +calculate_all_greeks()
305//! }
306//!
307//! Options --|> Greeks : implements
308//! Options --|> Graph : implements
309//! Position o-- Options : contains
310//! Options *-- OptionStyle : has
311//! Options *-- OptionType : has
312//! Options *-- Side : has
313//! Options *-- ExpirationDate : has
314//! Options *-- Positive : uses
315//! ```
316//!
317//! ## Trading Strategies
318//!
319//! OptionStratLib provides 25+ comprehensive trading strategies organized by complexity and market outlook:
320//!
321//! ### **Single Leg Strategies**
322//! Basic directional strategies for beginners:
323//! - **Long Call**: Bullish strategy with unlimited upside potential
324//! - **Short Call**: Bearish strategy collecting premium with limited profit
325//! - **Long Put**: Bearish strategy with high profit potential
326//! - **Short Put**: Bullish strategy collecting premium with assignment risk
327//!
328//! ### **Spread Strategies**
329//! Defined risk strategies with limited profit/loss:
330//! - **Bull Call Spread**: Moderately bullish with limited risk and reward
331//! - **Bear Call Spread**: Moderately bearish credit spread
332//! - **Bull Put Spread**: Moderately bullish credit spread
333//! - **Bear Put Spread**: Moderately bearish debit spread
334//!
335//! ### **Butterfly Strategies**
336//! Market neutral strategies profiting from low volatility:
337//! - **Long Butterfly Spread**: Profits from price staying near middle strike
338//! - **Short Butterfly Spread**: Profits from price moving away from middle strike
339//! - **Call Butterfly**: Butterfly using only call options
340//!
341//! ### **Complex Multi-Leg Strategies**
342//! Advanced strategies for experienced traders:
343//! - **Iron Condor**: Market neutral strategy with wide profit zone
344//! - **Iron Butterfly**: Market neutral strategy with narrow profit zone
345//!
346//! ### **Volatility Strategies**
347//! Strategies that profit from volatility changes:
348//! - **Long Straddle**: Profits from high volatility in either direction
349//! - **Short Straddle**: Profits from low volatility (range-bound market)
350//! - **Long Strangle**: Similar to straddle but with different strikes
351//! - **Short Strangle**: Credit strategy profiting from low volatility
352//!
353//! ### **Income Generation Strategies**
354//! Strategies focused on generating regular income:
355//! - **Covered Call**: Stock ownership with call selling for income
356//! - **Poor Man's Covered Call**: LEAPS-based covered call alternative
357//!
358//! ### **Protection Strategies**
359//! Risk management and hedging strategies:
360//! - **Protective Put**: Downside protection for stock positions
361//! - **Collar**: Combination of covered call and protective put
362//!
363//! ### **Custom Strategy Framework**
364//! - **Custom Strategy**: Flexible framework for creating any multi-leg strategy
365//! - Supports unlimited number of legs
366//! - Full integration with all analysis tools
367//! - Complete trait implementation for consistency
368//!
369//! ### **Strategy Analysis Features**
370//! All strategies include comprehensive analysis capabilities:
371//! - **Profit/Loss Analysis**: P&L at any price point and time
372//! - **Break-Even Points**: Multiple break-even calculations
373//! - **Greeks Analysis**: Real-time risk metrics
374//! - **Probability Analysis**: Success probability calculations
375//! - **Delta Neutrality**: Delta-neutral position analysis
376//! - **Visualization**: Interactive payoff diagrams and risk profiles
377//! - **Optimization**: Find optimal strikes and expirations
378//!
379//! ### **Strategy Traits System**
380//! All strategies implement a comprehensive trait system:
381//!
382//! - **Strategable**: Master trait combining all strategy capabilities
383//! - **BasicAble**: Basic strategy information (symbol, price, etc.)
384//! - **Positionable**: Position management and modification
385//! - **Strategies**: Core strategy calculations (P&L, break-even, etc.)
386//! - **Validable**: Strategy validation and error checking
387//! - **BreakEvenable**: Break-even point calculations
388//! - **Profit**: Profit/loss analysis at various price points
389//! - **Greeks**: Greeks calculations for risk management
390//! - **DeltaNeutrality**: Delta-neutral analysis and adjustments
391//! - **ProbabilityAnalysis**: Outcome probability calculations
392//! - **Graph**: Visualization and plotting capabilities
393//!
394//! ## Setup Instructions
395//!
396//! ### Prerequisites
397//!
398//! - Rust 1.80 or higher (2024 edition)
399//! - Cargo package manager
400//!
401//! ### Installation
402//!
403//! Add OptionStratLib to your `Cargo.toml`:
404//!
405//! ```toml
406//! [dependencies]
407//! optionstratlib = "0.6.1"
408//! ```
409//!
410//! Or use cargo to add it to your project:
411//!
412//! ```bash
413//! cargo add optionstratlib
414//! ```
415//!
416//! ### Optional Features
417//!
418//! The library includes optional features for enhanced functionality:
419//!
420//! ```toml
421//! [dependencies]
422//! optionstratlib = { version = "0.6.1", features = ["plotly"] }
423//! ```
424//!
425//! - `plotly`: Enables interactive visualization using plotly.rs
426//!
427//! ### Building from Source
428//!
429//! Clone the repository and build using Cargo:
430//!
431//! ```bash
432//! git clone https://github.com/joaquinbejar/OptionStratLib.git
433//! cd OptionStratLib
434//! cargo build --release
435//! ```
436//!
437//! Run comprehensive test suite:
438//!
439//! ```bash
440//! cargo test --all-features
441//! ```
442//!
443//! Generate documentation:
444//!
445//! ```bash
446//! cargo doc --open --all-features
447//! ```
448//!
449//! Run benchmarks:
450//!
451//! ```bash
452//! cargo bench
453//! ```
454//!
455//! ## Library Usage
456//!
457//! ### Basic Option Creation and Pricing
458//!
459//! ```rust
460//! use optionstratlib::{Options, OptionStyle, OptionType, Side, ExpirationDate};
461//! use optionstratlib::pos;
462//! use rust_decimal_macros::dec;
463//! use optionstratlib::greeks::Greeks;
464//!
465//! // Create a European call option
466//! let option = Options::new(
467//! OptionType::European,
468//! Side::Long,
469//! "AAPL".to_string(),
470//! pos!(150.0), // strike_price
471//! ExpirationDate::Days(pos!(30.0)),
472//! pos!(0.25), // implied_volatility
473//! pos!(1.0), // quantity
474//! pos!(155.0), // underlying_price
475//! dec!(0.05), // risk_free_rate
476//! OptionStyle::Call,
477//! pos!(0.02), // dividend_yield
478//! None, // exotic_params
479//! );
480//!
481//! // Calculate option price using Black-Scholes
482//! let price = option.calculate_price_black_scholes().unwrap();
483//! tracing::info!("Option price: ${:.2}", price);
484//!
485//! // Calculate Greeks for risk management
486//! let delta = option.delta().unwrap();
487//! let gamma = option.gamma().unwrap();
488//! let theta = option.theta().unwrap();
489//! let vega = option.vega().unwrap();
490//! tracing::info!("Greeks - Delta: {:.4}, Gamma: {:.4}, Theta: {:.4}, Vega: {:.4}",
491//! delta, gamma, theta, vega);
492//! ```
493//!
494//! ### Working with Trading Strategies
495//!
496//! ```rust
497//! use optionstratlib::{Positive, ExpirationDate, pos};
498//! use optionstratlib::strategies::Strategies;
499//! use optionstratlib::strategies::bull_call_spread::BullCallSpread;
500//! use optionstratlib::strategies::base::{BreakEvenable, BasicAble};
501//! use optionstratlib::visualization::Graph;
502//! use rust_decimal_macros::dec;
503//! use std::error::Error;
504//!
505//! fn main() -> Result<(), Box<dyn Error>> {
506//! use optionstratlib::pricing::Profit;
507//! let underlying_price = pos!(100.0);
508//!
509//! // Create a Bull Call Spread strategy
510//! let strategy = BullCallSpread::new(
511//! "AAPL".to_string(),
512//! underlying_price,
513//! pos!(95.0), // long_strike
514//! pos!(105.0), // short_strike
515//! ExpirationDate::Days(pos!(30.0)),
516//! pos!(0.25), // implied_volatility
517//! dec!(0.05), // risk_free_rate
518//! pos!(2.50), // long_call_premium
519//! pos!(2.50), // long_call_open_fee
520//! pos!(1.20), // short_call_premium
521//! pos!(1.20), // short_call_close_fee
522//! Default::default(), Default::default(),
523//! Default::default(), Default::default()
524//! );
525//!
526//! // Analyze the strategy
527//! tracing::info!("Strategy: {}", strategy.get_title());
528//! tracing::info!("Break-even points: {:?}", strategy.get_break_even_points()?);
529//! tracing::info!("Max profit: ${:.2}", strategy.get_max_profit().unwrap_or(Positive::ZERO));
530//! tracing::info!("Max loss: ${:.2}", strategy.get_max_loss().unwrap_or(Positive::ZERO));
531//! tracing::info!("Net premium: ${:.2}", strategy.get_net_premium_received()?);
532//!
533//! // Calculate P&L at different price points
534//! let prices = vec![pos!(90.0), pos!(95.0), pos!(100.0), pos!(105.0), pos!(110.0)];
535//! for price in prices {
536//! let pnl = strategy.get_point_at_price(&price)?;
537//! tracing::info!("P&L at ${}: ${:.2}", price, pnl.0);
538//! }
539//!
540//! // Generate visualization
541//! #[cfg(feature = "plotly")]
542//! {
543//! strategy.write_html("Draws/Visualization/bull_call_spread.html".as_ref())?;
544//! }
545//!
546//! Ok(())
547//! }
548//! ```
549//!
550//! ### Advanced Features: Volatility Analysis
551//!
552//! ```rust
553//! use optionstratlib::prelude::*;
554//!
555//! fn main() -> Result<(), Box<dyn std::error::Error>> {
556//! // Create an option for implied volatility calculation
557//! let mut option = Options::new(
558//! OptionType::European,
559//! Side::Long,
560//! "AAPL".to_string(),
561//! pos!(105.0), // strike
562//! ExpirationDate::Days(pos!(90.0)),
563//! pos!(0.20), // initial IV guess
564//! pos!(1.0), // quantity
565//! pos!(100.0), // underlying price
566//! dec!(0.05), // risk free rate
567//! OptionStyle::Call,
568//! pos!(0.02), // dividend yield
569//! None,
570//! );
571//!
572//! let market_price = pos!(5.50);
573//! let iv = implied_volatility(market_price, &mut option, 100)?;
574//!
575//! tracing::info!("Implied volatility: {:.2}%", iv.to_f64() * 100.0);
576//! Ok(())
577//! }
578//! ```
579//!
580//! ### Custom Strategy Creation
581//!
582//! ```rust
583//! use optionstratlib::prelude::*;
584//!
585//! // Define common parameters
586//! let underlying_symbol = "DAX".to_string();
587//! let underlying_price = pos!(24000.0);
588//! let expiration = ExpirationDate::Days(pos!(30.0));
589//! let implied_volatility = pos!(0.25);
590//! let risk_free_rate = dec!(0.05);
591//! let dividend_yield = pos!(0.02);
592//! let fee = pos!(2.0);
593//!
594//! // Create a long put option
595//! let long_put_option = Options::new(
596//! OptionType::European,
597//! Side::Long,
598//! underlying_symbol.clone(),
599//! pos!(24070.0), // strike
600//! expiration.clone(),
601//! implied_volatility,
602//! pos!(1.0), // quantity
603//! underlying_price,
604//! risk_free_rate,
605//! OptionStyle::Put,
606//! dividend_yield,
607//! None,
608//! );
609//! let long_put = Position::new(
610//! long_put_option,
611//! pos!(150.0), // premium
612//! Utc::now(),
613//! fee,
614//! fee,
615//! None,
616//! None,
617//! );
618//!
619//! // Create a long call option
620//! let long_call_option = Options::new(
621//! OptionType::European,
622//! Side::Long,
623//! underlying_symbol.clone(),
624//! pos!(24030.0), // strike
625//! expiration.clone(),
626//! implied_volatility,
627//! pos!(1.0), // quantity
628//! underlying_price,
629//! risk_free_rate,
630//! OptionStyle::Call,
631//! dividend_yield,
632//! None,
633//! );
634//! let long_call = Position::new(
635//! long_call_option,
636//! pos!(120.0), // premium
637//! Utc::now(),
638//! fee,
639//! fee,
640//! None,
641//! None,
642//! );
643//!
644//! // Create CustomStrategy with the positions
645//! let positions = vec![long_call, long_put];
646//! let strategy = CustomStrategy::new(
647//! "DAX Straddle Strategy".to_string(),
648//! underlying_symbol,
649//! "A DAX long straddle strategy".to_string(),
650//! underlying_price,
651//! positions,
652//! pos!(1.0),
653//! 30,
654//! implied_volatility,
655//! );
656//!
657//! tracing::info!("Strategy created: {}", strategy.get_title());
658//! ```
659//!
660//! ## Testing
661//!
662//! OptionStratLib includes a comprehensive test suite with over 1000 unit and integration tests:
663//!
664//! ### **Running Tests**
665//!
666//! Run all tests:
667//! ```bash
668//! cargo test --all-features
669//! ```
670//!
671//! Run tests for specific modules:
672//! ```bash
673//! cargo test strategies::bull_call_spread
674//! cargo test pricing::black_scholes
675//! cargo test volatility::utils
676//! ```
677//!
678//! Run tests with output:
679//! ```bash
680//! cargo test -- --nocapture
681//! ```
682//!
683//! ### **Test Categories**
684//!
685//! - **Unit Tests**: Individual function and method testing
686//! - **Integration Tests**: Cross-module functionality testing
687//! - **Strategy Tests**: Comprehensive strategy validation
688//! - **Pricing Model Tests**: Accuracy and performance testing
689//! - **Greeks Tests**: Mathematical precision validation
690//! - **Visualization Tests**: Chart generation and export testing
691//!
692//! ### **Benchmarking**
693//!
694//! Run performance benchmarks:
695//! ```bash
696//! cargo bench
697//! ```
698//!
699//! Generate test coverage report:
700//! ```bash
701//! cargo tarpaulin --all-features --out Html
702//! ```
703//!
704//! ## Examples
705//!
706//! The library includes extensive examples organized by functionality:
707//!
708//! - **`examples/examples_strategies/`**: Complete strategy examples (25+ strategies)
709//! - **`examples/examples_chains/`**: Option chain analysis examples
710//! - **`examples/examples_pricing/`**: Pricing model demonstrations
711//! - **`examples/examples_visualization/`**: Interactive chart examples
712//! - **`examples/examples_volatility/`**: Volatility analysis examples
713//! - **`examples/examples_simulation/`**: Monte Carlo and simulation examples
714//!
715//! Run examples:
716//! ```bash
717//! cargo run --example bull_call_spread --features plotly
718//! cargo run --example black_scholes_pricing
719//! cargo run --example volatility_surface
720//! ```
721//!
722//! ## Contribution and Contact
723//!
724//! ### **Contributing**
725//!
726//! Contributions are welcome! Please follow these guidelines:
727//!
728//! 1. **Fork** the repository
729//! 2. **Create** a feature branch: `git checkout -b feature/amazing-feature`
730//! 3. **Commit** your changes: `git commit -m 'Add amazing feature'`
731//! 4. **Push** to the branch: `git push origin feature/amazing-feature`
732//! 5. **Open** a Pull Request
733//!
734//! ### **Development Setup**
735//!
736//! ```bash
737//! git clone https://github.com/joaquinbejar/OptionStratLib.git
738//! cd OptionStratLib
739//! cargo build --all-features
740//! cargo test --all-features
741//! ```
742//!
743//! ### **Code Quality**
744//!
745//! - All code must pass `cargo clippy` without warnings
746//! - Format code with `cargo fmt`
747//! - Add tests for new functionality
748//! - Update documentation for API changes
749//! - Follow Rust 2024 edition best practices
750//!
751//!
752//! ### **Support**
753//!
754//! - **Issues**: Report bugs and request features on GitHub
755//! - **Discussions**: Join community discussions on GitHub Discussions
756//! - **Documentation**: Comprehensive docs available at docs.rs
757//!
758//! ---
759//!
760//! **OptionStratLib v0.7.0** - Built with ❤️ in Rust for the financial community
761//!
762
763/// # OptionsStratLib: Financial Options Trading Library
764///
765/// A comprehensive library for options trading analytics, modeling, and strategy development.
766/// Provides tools for pricing, risk assessment, strategy building, and performance analysis
767/// of financial options across various market conditions.
768///
769/// ## Core Modules
770extern crate core;
771
772/// * `backtesting` - Tools for historical performance evaluation of options strategies.
773///
774/// Provides framework and utilities to simulate and analyze how option strategies
775/// would have performed using historical market data. Supports various performance
776/// metrics, drawdown analysis, and strategy comparison.
777pub mod backtesting;
778
779/// * `chains` - Functionality for working with options chains and series data.
780///
781/// Tools for parsing, manipulating, and analyzing options chain data. Includes
782/// methods to filter chains by expiration, strike price, and other criteria,
783/// as well as utilities for chain visualization and analysis.
784pub mod chains;
785
786/// * `constants` - Library-wide mathematical and financial constants.
787///
788/// Defines fundamental constants used throughout the library including mathematical
789/// constants (π, epsilon values), market standards (trading days per year),
790/// calculation parameters, and visualization color schemes.
791pub mod constants;
792
793/// * `curves` - Tools for yield curves, term structures, and other financial curves.
794///
795/// Implementations of various interest rate curves, forward curves, and term structures
796/// used in options pricing and risk management. Includes interpolation methods and
797/// curve fitting algorithms.
798pub mod curves;
799
800/// * `error` - Error types and handling functionality for the library.
801///
802/// Defines the error hierarchy used throughout the library, providing detailed
803/// error types for different categories of failures including validation errors,
804/// calculation errors, and input/output errors.
805pub mod error;
806
807/// * `geometrics` - Mathematical utilities for geometric calculations relevant to options.
808///
809/// Provides specialized geometric functions and algorithms for options pricing and modeling,
810/// including path-dependent calculations and spatial transformations for volatility surfaces.
811pub mod geometrics;
812
813/// * `greeks` - Calculation and management of option sensitivity metrics (Delta, Gamma, etc.).
814///
815/// Comprehensive implementation of options Greeks (sensitivity measures) including
816/// Delta, Gamma, Theta, Vega, and Rho. Includes analytical formulas, numerical
817/// approximations, and visualization tools for risk analysis.
818pub mod greeks;
819
820/// * `model` - Core data structures and models for options and derivatives.
821///
822/// Defines the fundamental data types and structures used throughout the library,
823/// including option contract representations, position tracking, and market data models.
824/// Serves as the foundation for all other modules.
825pub mod model;
826
827/// * `pnl` - Profit and loss analysis tools for options positions.
828///
829/// Utilities for calculating, projecting, and visualizing profit and loss (P&L) profiles
830/// for individual options and complex strategies. Includes time-based P&L evolution and
831/// scenario analysis.
832pub mod pnl;
833
834/// * `pricing` - Option pricing models including Black-Scholes and numerical methods.
835///
836/// Implementations of various option pricing models including Black-Scholes-Merton,
837/// binomial trees, Monte Carlo simulation, and finite difference methods. Supports
838/// European, American, and exotic options.
839pub mod pricing;
840
841/// * `risk` - Risk assessment and management tools for options portfolios.
842///
843/// Tools for analyzing and quantifying risk in options positions and portfolios,
844/// including Value at Risk (VaR), stress testing, scenario analysis, and
845/// portfolio optimization algorithms.
846pub mod risk;
847
848/// * `simulation` - Simulation techniques for scenario analysis.
849///
850/// Framework for Monte Carlo and other simulation methods to model potential
851/// market scenarios and their impact on options strategies. Includes path generation
852/// algorithms and statistical analysis of simulation results.
853pub mod simulation;
854
855/// * `strategies` - Pre-defined option strategy templates and building blocks.
856///
857/// Library of common option strategies (spreads, straddles, condors, etc.) with
858/// implementation helpers, parameter optimization, and analysis tools. Supports
859/// strategy composition and customization.
860pub mod strategies;
861
862/// * `surfaces` - Volatility surface and other 3D financial data modeling.
863///
864/// Tools for constructing, manipulating, and analyzing volatility surfaces and
865/// other three-dimensional financial data structures. Includes interpolation methods,
866/// fitting algorithms, and visualization utilities.
867pub mod surfaces;
868
869/// * `utils` - General utility functions for data manipulation and calculations.
870///
871/// Collection of helper functions and utilities used across the library for
872/// data manipulation, mathematical operations, date handling, and other
873/// common tasks in financial calculations.
874pub mod utils;
875
876/// * `visualization` - Tools for plotting and visual representation of options data.
877///
878/// Graphics and visualization utilities for creating charts, graphs, and interactive
879/// plots of options data, strategies, and analytics. Supports various plot types
880/// optimized for different aspects of options analysis.
881pub mod visualization;
882
883/// * `volatility` - Volatility modeling, forecasting, and analysis utilities.
884///
885/// Comprehensive tools for volatility analysis including historical volatility calculation,
886/// implied volatility determination, volatility forecasting models (GARCH, EWMA), and
887/// volatility skew/smile analysis.
888pub mod volatility;
889
890/// * `series` - Functionality for working with collections of option chains across expirations.
891///
892/// Provides tools to manage, filter, and analyze multiple option chains grouped by expiration dates.
893/// Includes utilities for constructing series data, navigating expirations, and performing
894/// cross-expiration analysis and visualization.
895pub mod series;
896
897/// * `prelude` - Convenient re-exports of commonly used types and traits.
898///
899/// The prelude module provides a single import point for the most frequently used
900/// types, traits, and functions from the OptionStratLib library. This reduces the
901/// amount of boilerplate imports needed when working with the library.
902pub mod prelude;
903
904pub use model::ExpirationDate;
905pub use model::Options;
906pub use model::positive::Positive;
907pub use model::types::{OptionStyle, OptionType, Side};
908
909/// Library version
910pub const VERSION: &str = env!("CARGO_PKG_VERSION");
911
912/// Returns the library version
913pub fn version() -> &'static str {
914 VERSION
915}