optionstratlib 0.16.2

OptionStratLib is a comprehensive Rust library for options trading and strategy development across multiple asset classes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use crate::chains::chain::OptionChain;
use crate::curves::Curve;
use crate::error::VolatilityError;
use positive::Positive;

/// A trait defining a volatility smile representation.
///
/// The `VolatilitySmile` trait is designed to encapsulate the concept of a
/// volatility smile, a key phenomenon in derivatives pricing and financial
/// modeling. A volatility smile occurs when implied volatility varies as a
/// function of strike price, often depicted as a curved graph resembling a
/// smile. This trait establishes the foundation for representing and
/// retrieving these smiles in the form of a mathematical curve.
///
/// # Overview
/// Implementors of this trait are required to provide the `smile` method, which
/// computes and returns a `Curve` object representing the volatility smile.
/// The `Curve` struct is a mathematical representation of the smile, where the
/// x-axis typically corresponds to strike prices (or some other independent variable),
/// and the y-axis corresponds to implied volatility.
///
/// # Usage
/// This trait serves as the basis for constructing and analyzing volatility smiles
/// in applications such as:
/// - Financial derivatives modeling
/// - Options pricing engines
/// - Quantitative analysis of market data
///
/// # Required Methods
/// - **`smile(&self) -> Curve`**
///   - Computes and returns the volatility smile as a `Curve`.
///   - The returned `Curve` can be used for graphical representation, numerical analysis,
///     or further mathematical operations, such as interpolation or transformations.
///
/// # Integration with Other Modules
/// The `VolatilitySmile` trait makes use of the `Curve` struct, defined in the
/// `crate::curves` module. The `Curve` provides the mathematical framework
/// necessary for representing and manipulating the smile data. High-quality
/// precision (via the use of `Decimal` and ordered points) ensures that the output
/// from the `smile` method is reliable and suitable for scientific or financial
/// applications.
///
/// # See Also
/// - [`crate::curves::Curve`]: The fundamental mathematical representation of the volatility smile.
/// - [`crate::curves::Point2D`]: The structure representing individual points in the `Curve`.
///
/// # Examples
/// To define a custom volatility model, users can implement this trait and provide
/// their specific logic for generating a `Curve` corresponding to the smile.
///
/// ```rust
/// use std::collections::BTreeSet;
/// use rust_decimal::Decimal;
/// use optionstratlib::curves::Curve;
/// use optionstratlib::error::greeks::CalculationErrorKind::DecimalError;
/// use optionstratlib::volatility::VolatilitySmile;
///
/// struct MySmile;
///
/// impl VolatilitySmile for MySmile {
///     fn smile(&self) -> Curve {
///         // Custom logic to build and return a Curve representing the smile
///         Curve { points: BTreeSet::new(), x_range: (Decimal::ZERO, Decimal::ZERO) }
///     }
/// }
/// ```
///
/// This enables integration of user-defined volatility models with the broader
/// ecosystem of mathematical and financial tools that utilize the `Curve` data type.
pub trait VolatilitySmile {
    /// Computes and returns a curve representing the volatility smile.
    ///
    /// # Returns
    /// - A [`Curve`] object that models the volatility smile. The x-axis typically
    ///   represents strike prices (or another independent variable), while the y-axis
    ///   represents implied volatility.
    ///   
    /// # Note
    /// - The `Curve` returned should ideally conform to the constraints and
    ///   ordering requirements specified in the `Curve` documentation.
    fn smile(&self) -> Curve;
}

/// Trait for providing at-the-money implied volatility.
///
/// This trait defines a method to retrieve the at-the-money (ATM) implied volatility.
/// Implementations should return a `Positive` value representing the ATM IV, or an error
/// if the value cannot be determined.
pub trait AtmIvProvider {
    /// Get the at-the-money implied volatility.
    ///
    /// # Returns
    ///
    /// * `Ok(&Positive)` - a reference to the ATM implied volatility
    ///   maintained by the implementor.
    /// * `Err(VolatilityError)` - when the implementor cannot supply
    ///   an ATM IV for the current observation.
    ///
    /// # Errors
    ///
    /// Returns `VolatilityError::AtmIvUnavailable` with a wrapped
    /// `VolatilityError::Chain` source when the underlying container
    /// (typically an option chain) cannot resolve an ATM implied
    /// volatility for the current observation.
    fn atm_iv(&self) -> Result<&Positive, VolatilityError>;
}

impl AtmIvProvider for Positive {
    fn atm_iv(&self) -> Result<&Positive, VolatilityError> {
        Ok(self)
    }
}

impl AtmIvProvider for OptionChain {
    fn atm_iv(&self) -> Result<&Positive, VolatilityError> {
        match self.get_atm_implied_volatility() {
            Ok(iv) => Ok(iv),
            Err(e) => Err(VolatilityError::AtmIvUnavailable {
                source: Box::new(VolatilityError::from(e)),
            }),
        }
    }
}

#[cfg(test)]
mod tests_volatility_traits {
    use super::*;
    use crate::curves::{Curve, Point2D};
    use crate::error::CurveError;
    use crate::metrics::VolatilitySkewCurve;

    use positive::pos_or_panic;
    use rust_decimal::Decimal;
    use rust_decimal_macros::dec;
    use std::collections::BTreeSet;

    struct TestSmile;

    impl VolatilitySmile for TestSmile {
        fn smile(&self) -> Curve {
            create_sample_curve()
        }
    }

    struct TestIvProvider {
        iv: Positive,
    }

    impl AtmIvProvider for TestIvProvider {
        fn atm_iv(&self) -> Result<&Positive, VolatilityError> {
            Ok(&self.iv)
        }
    }

    fn create_sample_curve() -> Curve {
        let mut points = BTreeSet::new();
        points.insert(Point2D::new(dec!(90.0), dec!(0.25)));
        points.insert(Point2D::new(dec!(95.0), dec!(0.22)));
        points.insert(Point2D::new(dec!(100.0), dec!(0.20)));
        points.insert(Point2D::new(dec!(105.0), dec!(0.22)));
        points.insert(Point2D::new(dec!(110.0), dec!(0.25)));

        Curve {
            points,
            x_range: (dec!(90.0), dec!(110.0)),
        }
    }

    #[test]
    fn test_volatility_smile_implementation() {
        let smile = TestSmile;
        let curve = smile.smile();

        // Verify the curve has expected properties
        assert_eq!(curve.points.len(), 5);
        assert_eq!(curve.x_range, (dec!(90.0), dec!(110.0)));

        // Check specific points
        let points: Vec<&Point2D> = curve.points.iter().collect();
        assert_eq!(points[0].x, dec!(90.0));
        assert_eq!(points[0].y, dec!(0.25));
        assert_eq!(points[2].x, dec!(100.0));
        assert_eq!(points[2].y, dec!(0.20));
        assert_eq!(points[4].x, dec!(110.0));
        assert_eq!(points[4].y, dec!(0.25));
    }

    #[test]
    fn test_volatility_smile() {
        let smile = TestSmile;
        let curve = smile.smile();

        assert_eq!(curve.points.len(), 5);
        assert_eq!(curve.x_range, (dec!(90.0), dec!(110.0)));

        let points: Vec<&Point2D> = curve.points.iter().collect();
        assert_eq!(points[0].x, dec!(90.0));
        assert_eq!(points[0].y, dec!(0.25));
        assert_eq!(points[2].x, dec!(100.0));
        assert_eq!(points[2].y, dec!(0.20));
        assert_eq!(points[4].x, dec!(110.0));
        assert_eq!(points[4].y, dec!(0.25));
    }

    #[test]
    fn test_volatility_smile_with_empty_curve() {
        struct EmptySmile;

        impl VolatilitySmile for EmptySmile {
            fn smile(&self) -> Curve {
                Curve {
                    points: BTreeSet::new(),
                    x_range: (Decimal::ZERO, Decimal::ZERO),
                }
            }
        }

        let smile = EmptySmile;
        let curve = smile.smile();

        assert!(curve.points.is_empty());
        assert_eq!(curve.x_range, (Decimal::ZERO, Decimal::ZERO));
    }

    #[test]
    fn test_atm_iv_provider_for_positive() {
        let value = pos_or_panic!(0.2);

        // Test AtmIvProvider implementation for Positive
        let result = value.atm_iv();

        assert!(result.is_ok());
    }

    #[test]
    fn test_atm_iv_provider_some() {
        let provider = TestIvProvider {
            iv: pos_or_panic!(0.25),
        };

        let result = provider.atm_iv();
        assert!(result.is_ok());
    }

    #[test]
    fn test_atm_iv_provider_error() {
        struct ErrorIvProvider;

        impl AtmIvProvider for ErrorIvProvider {
            fn atm_iv(&self) -> Result<&Positive, VolatilityError> {
                Err(VolatilityError::AtmIvUnavailable {
                    source: Box::new(VolatilityError::IvNotFound),
                })
            }
        }

        let provider = ErrorIvProvider;
        let result = provider.atm_iv();

        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(
            error
                .to_string()
                .contains("ATM implied volatility is not available")
        );
    }

    #[test]
    fn test_combined_traits_usage() {
        // Create an implementation that provides both traits
        struct CombinedProvider {
            iv_value: Positive,
        }

        impl VolatilitySmile for CombinedProvider {
            fn smile(&self) -> Curve {
                create_sample_curve()
            }
        }

        impl AtmIvProvider for CombinedProvider {
            fn atm_iv(&self) -> Result<&Positive, VolatilityError> {
                Ok(&self.iv_value)
            }
        }

        // Test with Some value
        let provider_with_iv = CombinedProvider {
            iv_value: pos_or_panic!(0.2),
        };

        // As VolatilitySmile
        let curve = provider_with_iv.smile();
        assert_eq!(curve.points.len(), 5);

        // As AtmIvProvider
        let iv_result = provider_with_iv.atm_iv();
        assert!(iv_result.is_ok());
    }

    #[test]
    fn test_atm_iv_provider_for_option_chain_success() {
        use crate::chains::chain::OptionChain;

        let mut chain = OptionChain::new(
            "TEST",
            Positive::HUNDRED,
            "2025-12-31".to_string(),
            Some(dec!(0.05)),
            None,
        );

        // Add options with implied volatility
        chain.add_option(
            pos_or_panic!(95.0),
            Some(pos_or_panic!(6.0)),
            Some(pos_or_panic!(6.5)),
            Some(Positive::ONE),
            Some(pos_or_panic!(1.5)),
            pos_or_panic!(0.25),
            Some(dec!(0.7)),
            Some(dec!(-0.3)),
            Some(dec!(0.02)),
            None,
            None,
            None,
        );

        chain.add_option(
            Positive::HUNDRED,
            Some(pos_or_panic!(3.0)),
            Some(pos_or_panic!(3.5)),
            Some(pos_or_panic!(3.0)),
            Some(pos_or_panic!(3.5)),
            pos_or_panic!(0.20),
            Some(dec!(0.5)),
            Some(dec!(-0.5)),
            Some(dec!(0.025)),
            None,
            None,
            None,
        );

        chain.add_option(
            pos_or_panic!(105.0),
            Some(Positive::ONE),
            Some(pos_or_panic!(1.5)),
            Some(pos_or_panic!(6.0)),
            Some(pos_or_panic!(6.5)),
            pos_or_panic!(0.22),
            Some(dec!(0.3)),
            Some(dec!(-0.7)),
            Some(dec!(0.02)),
            None,
            None,
            None,
        );

        let result = chain.atm_iv();
        assert!(result.is_ok());
        let iv = result.unwrap();
        assert!(*iv > Positive::ZERO);
    }

    #[test]
    fn test_atm_iv_provider_for_option_chain_empty() {
        use crate::chains::chain::OptionChain;

        let chain = OptionChain::new(
            "TEST",
            Positive::HUNDRED,
            "2025-12-31".to_string(),
            None,
            None,
        );

        let result = chain.atm_iv();
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(
            error
                .to_string()
                .contains("ATM implied volatility is not available")
        );
    }

    #[test]
    fn test_volatility_smile_symmetry() {
        struct SymmetricSmile;

        impl VolatilitySmile for SymmetricSmile {
            fn smile(&self) -> Curve {
                let mut points = BTreeSet::new();
                // Symmetric smile around ATM
                points.insert(Point2D::new(dec!(80.0), dec!(0.30)));
                points.insert(Point2D::new(dec!(90.0), dec!(0.22)));
                points.insert(Point2D::new(dec!(100.0), dec!(0.18)));
                points.insert(Point2D::new(dec!(110.0), dec!(0.22)));
                points.insert(Point2D::new(dec!(120.0), dec!(0.30)));

                Curve {
                    points,
                    x_range: (dec!(80.0), dec!(120.0)),
                }
            }
        }

        let smile = SymmetricSmile;
        let curve = smile.smile();

        let points: Vec<&Point2D> = curve.points.iter().collect();

        // Verify symmetry: IV at 80 == IV at 120, IV at 90 == IV at 110
        assert_eq!(points[0].y, points[4].y); // 80 and 120
        assert_eq!(points[1].y, points[3].y); // 90 and 110
        // ATM has lowest IV
        assert!(points[2].y < points[1].y);
    }

    #[test]
    fn test_atm_iv_provider_positive_value() {
        let value = pos_or_panic!(0.35);
        let result = value.atm_iv();

        assert!(result.is_ok());
        let iv = result.unwrap();
        assert_eq!(*iv, pos_or_panic!(0.35));
    }

    #[test]
    fn test_atm_iv_provider_small_value() {
        let value = pos_or_panic!(0.01);
        let result = value.atm_iv();

        assert!(result.is_ok());
        let iv = result.unwrap();
        assert_eq!(*iv, pos_or_panic!(0.01));
    }

    #[test]
    fn test_volatility_smile_single_point() {
        struct SinglePointSmile;

        impl VolatilitySmile for SinglePointSmile {
            fn smile(&self) -> Curve {
                let mut points = BTreeSet::new();
                points.insert(Point2D::new(dec!(100.0), dec!(0.20)));

                Curve {
                    points,
                    x_range: (dec!(100.0), dec!(100.0)),
                }
            }
        }

        let smile = SinglePointSmile;
        let curve = smile.smile();

        assert_eq!(curve.points.len(), 1);
        let point = curve.points.iter().next().unwrap();
        assert_eq!(point.x, dec!(100.0));
        assert_eq!(point.y, dec!(0.20));
    }

    #[test]
    fn test_combined_smile_and_skew_traits() {
        struct CombinedVolatility;

        impl VolatilitySmile for CombinedVolatility {
            fn smile(&self) -> Curve {
                create_sample_curve()
            }
        }

        impl VolatilitySkewCurve for CombinedVolatility {
            fn volatility_skew(&self) -> Result<Curve, CurveError> {
                let mut points = BTreeSet::new();
                points.insert(Point2D::new(dec!(-10.0), dec!(0.25)));
                points.insert(Point2D::new(dec!(0.0), dec!(0.20)));
                points.insert(Point2D::new(dec!(10.0), dec!(0.25)));

                let curve = Curve {
                    points,
                    x_range: (dec!(-10.0), dec!(10.0)),
                };
                Ok(curve)
            }
        }

        let vol = CombinedVolatility;

        // Test smile
        let smile_curve = vol.smile();
        assert_eq!(smile_curve.points.len(), 5);

        // Test skew
        let skew_curve = vol.volatility_skew().unwrap();
        assert_eq!(skew_curve.points.len(), 3);
    }
}