optionstratlib 0.16.5

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
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 25/12/24
******************************************************************************/
use rust_decimal::Decimal;
use thiserror::Error;

/// # Decimal Error Management
///
/// Represents errors that can occur during decimal operations in financial calculations.
/// This enum provides a structured way to handle various error conditions that may arise
/// when working with decimal values, including validation, arithmetic operations,
/// conversions, and precision issues.
///
/// # Use Cases
///
/// * Financial calculations requiring strict decimal precision
/// * Currency and monetary value operations
/// * Option pricing models where precision is critical
/// * Risk management calculations
///
/// # Error Propagation
///
/// These errors are typically wrapped in `DecimalResult` and propagated through
/// the application's calculation pipeline.
///
/// # Variants
///
/// * `InvalidValue` - Handles errors when a value cannot be represented as a valid decimal
/// * `ArithmeticError` - Handles errors during mathematical operations
/// * `ConversionError` - Handles errors when converting between different decimal representations
/// * `OutOfBounds` - Handles errors when a value exceeds defined limits
/// * `InvalidPrecision` - Handles errors related to decimal precision settings
///
/// # Example Usage
///
/// ```rust
/// use optionstratlib::error::DecimalError;
///
/// fn validate_decimal(value: f64) -> Result<(), DecimalError> {
///     if value.is_nan() {
///         return Err(DecimalError::InvalidValue {
///             value,
///             reason: "Value cannot be NaN".to_string(),
///         });
///     }
///     
///     if value < 0.0 || value > 100.0 {
///         return Err(DecimalError::OutOfBounds {
///             value,
///             min: 0.0,
///             max: 100.0,
///         });
///     }
///     
///     Ok(())
/// }
/// ```
#[derive(Error, Debug)]
pub enum DecimalError {
    /// Error when attempting to create a decimal from an invalid value
    ///
    /// Occurs when a value cannot be properly represented as a decimal,
    /// such as when it's NaN, infinity, or otherwise unsuitable for
    /// financial calculations.
    #[error("Invalid decimal value {value}: {reason}")]
    InvalidValue {
        /// The problematic value that caused the error
        value: f64,
        /// Detailed explanation of why the value is invalid
        reason: String,
    },

    /// Error when performing decimal arithmetic operations
    ///
    /// Occurs during mathematical operations such as addition, subtraction,
    /// multiplication, or division when the operation cannot be completed
    /// correctly (e.g., division by zero, overflow).
    #[error("Decimal arithmetic error during {operation}: {reason}")]
    ArithmeticError {
        /// The operation that failed (e.g., "addition", "division")
        operation: String,
        /// Detailed explanation of why the operation failed
        reason: String,
    },

    /// Error when converting between decimal types
    ///
    /// Occurs when a decimal value cannot be correctly converted from one
    /// representation to another, such as between different precision levels
    /// or between different decimal formats.
    #[error("Failed to convert decimal from {from_type} to {to_type}: {reason}")]
    ConversionError {
        /// The source type being converted from
        from_type: String,
        /// The destination type being converted to
        to_type: String,
        /// Detailed explanation of why the conversion failed
        reason: String,
    },

    /// Error when a decimal value exceeds its bounds
    ///
    /// Occurs when a decimal value falls outside of acceptable minimum
    /// or maximum values for a specific calculation context.
    #[error("Decimal value {value} is out of bounds (min: {min}, max: {max})")]
    OutOfBounds {
        /// The value that is out of bounds
        value: f64,
        /// The minimum acceptable value
        min: f64,
        /// The maximum acceptable value
        max: f64,
    },

    /// Error when decimal precision is invalid
    ///
    /// Occurs when an operation specifies or results in an invalid precision
    /// level that cannot be properly handled.
    #[error("Invalid decimal precision {precision}: {reason}")]
    InvalidPrecision {
        /// The problematic precision value
        precision: i32,
        /// Detailed explanation of why the precision is invalid
        reason: String,
    },

    /// Expiration-date conversion error surfaced during decimal operations.
    #[error(transparent)]
    ExpirationDate(expiration_date::error::ExpirationDateError),

    /// Error when a `Decimal` arithmetic operation overflows the representable range.
    ///
    /// Emitted by the crate-private `d_add` / `d_sub` / `d_mul` / `d_div` helpers
    /// in [`crate::model::decimal`] when the underlying
    /// `Decimal::checked_*` call returns `None`. The `operation` tag is a
    /// short, static identifier describing the call-site (for example
    /// `"pricing::black_scholes::discount_strike"`) so failures can be
    /// traced back to their kernel without walking the call stack.
    ///
    /// The operands are captured verbatim for post-mortem debugging and
    /// are included in the formatted error output (see the `#[error]`
    /// template below). This `DecimalError` variant is propagated across
    /// domain modules through the existing `#[from]` cascade, so the
    /// operand values will appear in any log or wrapper-error string
    /// produced downstream. Callers that need to redact them for
    /// production logging should match on the `Overflow` variant
    /// explicitly and reformat rather than rely on the default `Display`.
    #[error("Decimal {operation} overflow: {lhs} op {rhs}")]
    Overflow {
        /// Short static tag identifying the call-site.
        operation: &'static str,
        /// Left-hand operand of the failed arithmetic.
        lhs: Decimal,
        /// Right-hand operand of the failed arithmetic.
        rhs: Decimal,
    },
}

/// A specialized `Result` type for decimal calculation operations.
///
/// This type alias provides a convenient shorthand for operations that can result in a
/// `DecimalError`. It helps improve code readability and reduces boilerplate when working
/// with decimal calculations throughout the library.
///
/// # Type Parameters
///
/// * `T` - The successful result type of the operation
///
/// # Examples
///
/// ```rust
/// use optionstratlib::error::{DecimalError, DecimalResult};
///
/// fn divide(a: f64, b: f64) -> DecimalResult<f64> {
///     if b == 0.0 {
///         Err(DecimalError::ArithmeticError {
///             operation: "division".to_string(),
///             reason: "division by zero".to_string(),
///         })
///     } else {
///         Ok(a / b)
///     }
/// }
/// ```
///
/// # Usage Context
///
/// This type is primarily used in the financial calculations and decimal handling
/// components of the library, where precise decimal operations are critical and
/// error handling needs to be consistent and well-structured.
///
/// # Related Types
///
/// * `DecimalError` - The error type representing various decimal operation failures
pub type DecimalResult<T> = Result<T, DecimalError>;

/// Helper methods for creating common decimal errors
///
/// This implementation provides convenient factory methods to create
/// standardized instances of `DecimalError` for common error scenarios
/// in decimal operations. These methods help maintain consistency in
/// error creation across the codebase and simplify the construction of
/// descriptive error instances.
///
/// # Example
///
/// ```rust
/// use optionstratlib::error::DecimalError;
/// // Creating an invalid value error
/// let err = DecimalError::invalid_value(12.34, "Value exceeds maximum allowed");
///
/// // Creating an arithmetic error
/// let div_err = DecimalError::arithmetic_error("division", "Division by zero");
/// ```
impl DecimalError {
    /// Creates a new `InvalidValue` error
    ///
    /// Used when a decimal value fails validation due to being outside
    /// accepted ranges or otherwise inappropriate for the context.
    ///
    /// # Parameters
    ///
    /// * `value` - The problematic floating-point value
    /// * `reason` - Explanation of why the value is invalid
    ///
    /// # Returns
    ///
    /// A new `DecimalError::InvalidValue` instance
    #[must_use]
    #[cold]
    #[inline(never)]
    pub fn invalid_value(value: f64, reason: &str) -> Self {
        DecimalError::InvalidValue {
            value,
            reason: reason.to_string(),
        }
    }

    /// Creates a new `ArithmeticError` error
    ///
    /// Used when a mathematical operation on decimal values fails, such as
    /// division by zero, overflow, or underflow.
    ///
    /// # Parameters
    ///
    /// * `operation` - The name of the operation that failed (e.g., "addition", "division")
    /// * `reason` - Explanation of why the operation failed
    ///
    /// # Returns
    ///
    /// A new `DecimalError::ArithmeticError` instance
    #[cold]
    #[inline(never)]
    #[must_use]
    pub fn arithmetic_error(operation: &str, reason: &str) -> Self {
        DecimalError::ArithmeticError {
            operation: operation.to_string(),
            reason: reason.to_string(),
        }
    }

    /// Creates a new `ConversionError` error
    ///
    /// Used when conversion between decimal types or from/to other number
    /// types fails due to compatibility or range issues.
    ///
    /// # Parameters
    ///
    /// * `from_type` - The source type being converted from
    /// * `to_type` - The destination type being converted to
    /// * `reason` - Explanation of why the conversion failed
    ///
    /// # Returns
    ///
    /// A new `DecimalError::ConversionError` instance
    #[cold]
    #[inline(never)]
    #[must_use]
    pub fn conversion_error(from_type: &str, to_type: &str, reason: &str) -> Self {
        DecimalError::ConversionError {
            from_type: from_type.to_string(),
            to_type: to_type.to_string(),
            reason: reason.to_string(),
        }
    }

    /// Creates a new `OutOfBounds` error
    ///
    /// Used when a decimal value falls outside of specified minimum and maximum bounds.
    ///
    /// # Parameters
    ///
    /// * `value` - The out-of-bounds floating-point value
    /// * `min` - The lower bound (inclusive) of the valid range
    /// * `max` - The upper bound (inclusive) of the valid range
    ///
    /// # Returns
    ///
    /// A new `DecimalError::OutOfBounds` instance
    #[cold]
    #[inline(never)]
    #[must_use]
    pub fn out_of_bounds(value: f64, min: f64, max: f64) -> Self {
        DecimalError::OutOfBounds { value, min, max }
    }

    /// Creates a new `InvalidPrecision` error
    ///
    /// Used when a specified decimal precision is invalid, such as being negative,
    /// too large, or otherwise inappropriate for the context.
    ///
    /// # Parameters
    ///
    /// * `precision` - The problematic precision value
    /// * `reason` - Explanation of why the precision is invalid
    ///
    /// # Returns
    ///
    /// A new `DecimalError::InvalidPrecision` instance
    #[cold]
    #[inline(never)]
    #[must_use]
    pub fn invalid_precision(precision: i32, reason: &str) -> Self {
        DecimalError::InvalidPrecision {
            precision,
            reason: reason.to_string(),
        }
    }

    /// Creates a new `Overflow` error for a failed checked arithmetic operation.
    ///
    /// Used by the crate-private `d_add` / `d_sub` / `d_mul` / `d_div` helpers
    /// to surface an overflow of the underlying `Decimal::checked_*` call
    /// with full operand context.
    ///
    /// # Parameters
    ///
    /// * `operation` - Short static tag identifying the call-site
    ///   (for example `"pricing::black_scholes::discount_strike"`).
    /// * `lhs` - Left-hand operand of the failed arithmetic.
    /// * `rhs` - Right-hand operand of the failed arithmetic.
    ///
    /// # Returns
    ///
    /// A new `DecimalError::Overflow` instance.
    #[cold]
    #[inline(never)]
    #[must_use]
    pub fn overflow(operation: &'static str, lhs: Decimal, rhs: Decimal) -> Self {
        DecimalError::Overflow {
            operation,
            lhs,
            rhs,
        }
    }
}

impl From<expiration_date::error::ExpirationDateError> for DecimalError {
    #[inline]
    fn from(err: expiration_date::error::ExpirationDateError) -> Self {
        DecimalError::ExpirationDate(err)
    }
}

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

    #[test]
    fn test_invalid_value_error() {
        let error = DecimalError::invalid_value(-1.0, "Value cannot be negative");
        assert!(matches!(error, DecimalError::InvalidValue { .. }));
        assert!(error.to_string().contains("cannot be negative"));
    }

    #[test]
    fn test_arithmetic_error() {
        let error = DecimalError::arithmetic_error("division", "Division by zero");
        assert!(matches!(error, DecimalError::ArithmeticError { .. }));
        assert!(error.to_string().contains("Division by zero"));
    }

    #[test]
    fn test_conversion_error() {
        let error = DecimalError::conversion_error("f64", "Decimal", "Value out of range");
        assert!(matches!(error, DecimalError::ConversionError { .. }));
        assert!(error.to_string().contains("out of range"));
    }

    #[test]
    fn test_out_of_bounds_error() {
        let error = DecimalError::out_of_bounds(150.0, 0.0, 100.0);
        assert!(matches!(error, DecimalError::OutOfBounds { .. }));
        assert!(error.to_string().contains("150"));
    }

    #[test]
    fn test_invalid_precision_error() {
        let error = DecimalError::invalid_precision(-1, "Precision must be non-negative");
        assert!(matches!(error, DecimalError::InvalidPrecision { .. }));
        assert!(error.to_string().contains("non-negative"));
    }

    #[test]
    fn test_overflow_error() {
        let error = DecimalError::overflow("test::site", Decimal::MAX, Decimal::MAX);
        assert!(matches!(error, DecimalError::Overflow { .. }));
        let rendered = error.to_string();
        assert!(rendered.contains("test::site"));
        assert!(rendered.contains("overflow"));
    }

    #[test]
    fn test_overflow_fields() {
        let lhs = Decimal::MAX;
        let rhs = Decimal::from(2);
        if let DecimalError::Overflow {
            operation,
            lhs: captured_lhs,
            rhs: captured_rhs,
        } = DecimalError::overflow("test::mul", lhs, rhs)
        {
            assert_eq!(operation, "test::mul");
            assert_eq!(captured_lhs, lhs);
            assert_eq!(captured_rhs, rhs);
        } else {
            panic!("expected Overflow variant");
        }
    }
}