optionstratlib 0.16.0

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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 25/12/24
******************************************************************************/
use crate::error::decimal::DecimalError;
use crate::geometrics::HasX;
use num_traits::{FromPrimitive, ToPrimitive};
use rand::distr::Distribution;
use rand_distr::Normal;
use rust_decimal::{Decimal, MathematicalOps, RoundingStrategy};
use rust_decimal_macros::dec;

/// Represents the daily interest rate factor used for financial calculations,
/// approximately equivalent to 1/252 (a standard value for the number of trading days in a year).
///
/// This constant converts annual interest rates to daily rates by providing a division factor.
/// The value 0.00396825397 corresponds to 1/252, where 252 is the typical number of trading
/// days in a financial year.
///
/// # Usage
///
/// This constant is commonly used in financial calculations such as:
/// - Converting annual interest rates to daily rates
/// - Time value calculations for options pricing
/// - Discounting cash flows on a daily basis
/// - Interest accrual calculations
pub const ONE_DAY: Decimal = dec!(0.00396825397);

/// Asserts that two Decimal values are approximately equal within a given epsilon
#[macro_export]
macro_rules! assert_decimal_eq {
    ($left:expr, $right:expr, $epsilon:expr) => {
        let diff = ($left - $right).abs();
        assert!(
            diff <= $epsilon,
            "assertion failed: `(left == right)`\n  left: `{}`\n right: `{}`\n  diff: `{}`\n epsilon: `{}`",
            $left,
            $right,
            diff,
            $epsilon
        );
    };
}

/// Defines statistical operations for collections of decimal values.
///
/// This trait provides methods to calculate common statistical measures
/// for sequences or collections of `Decimal` values. It allows implementing
/// types to offer standardized statistical analysis capabilities.
///
/// ## Key Features
///
/// * Basic statistical calculations for `Decimal` collections
/// * Consistent interface for various collection types
/// * Precision-preserving operations using the `Decimal` type
///
/// ## Available Statistics
///
/// * `mean`: Calculates the arithmetic mean (average) of the values
/// * `std_dev`: Calculates the standard deviation, measuring the dispersion from the mean
///
/// ## Example
///
/// ```rust
/// use rust_decimal::Decimal;
/// use rust_decimal_macros::dec;
/// use optionstratlib::model::decimal::DecimalStats;
///
/// struct DecimalSeries(Vec<Decimal>);
///
/// impl DecimalStats for DecimalSeries {
///     fn mean(&self) -> Decimal {
///         let sum: Decimal = self.0.iter().sum();
///         if self.0.is_empty() {
///             dec!(0)
///         } else {
///             sum / Decimal::from(self.0.len())
///         }
///     }
///     
///     fn std_dev(&self) -> Decimal {
///         // Implementation of standard deviation calculation
///         // ...
///         dec!(0) // Placeholder return
///     }
/// }
/// ```
pub trait DecimalStats {
    /// Calculates the arithmetic mean (average) of the collection.
    ///
    /// The mean is the sum of all values divided by the count of values.
    /// This method should handle empty collections appropriately.
    fn mean(&self) -> Decimal;

    /// Calculates the standard deviation of the collection.
    ///
    /// The standard deviation measures the amount of variation or dispersion
    /// from the mean. A low standard deviation indicates that values tend to be
    /// close to the mean, while a high standard deviation indicates values are
    /// spread out over a wider range.
    fn std_dev(&self) -> Decimal;
}

impl DecimalStats for Vec<Decimal> {
    fn mean(&self) -> Decimal {
        if self.is_empty() {
            return Decimal::ZERO;
        }
        let sum: Decimal = self.iter().sum();
        sum / Decimal::from(self.len())
    }

    fn std_dev(&self) -> Decimal {
        // Population variance of a single value is zero
        if self.len() < 2usize {
            return Decimal::ZERO;
        }
        let mean = self.mean();
        let variance: Decimal = self.iter().map(|x| (x - mean).powd(Decimal::TWO)).sum();
        (variance / Decimal::from(self.len() - 1))
            .sqrt()
            .unwrap_or(Decimal::ZERO)
    }
}

/// Converts a Decimal value to an f64.
///
/// This function attempts to convert a Decimal value to an f64 floating-point number.
/// If the conversion fails, it returns a DecimalError with detailed information about
/// the failure.
///
/// # Parameters
///
/// * `value` - The Decimal value to convert
///
/// # Returns
///
/// * `Result<f64, DecimalError>` - The converted f64 value if successful, or a DecimalError
///   if the conversion fails
///
/// # Errors
///
/// Returns [`DecimalError::ConversionError`] when the `Decimal` operand cannot
/// be represented as an `f64` (e.g. out-of-range magnitude or precision loss
/// beyond the `f64` mantissa).
///
/// # Example
///
/// ```rust
/// use rust_decimal::Decimal;
/// use rust_decimal_macros::dec;
/// use tracing::info;
/// use optionstratlib::model::decimal::decimal_to_f64;
///
/// let decimal = dec!(3.14159);
/// match decimal_to_f64(decimal) {
///     Ok(float) => info!("Converted to f64: {}", float),
///     Err(e) => info!("Conversion error: {:?}", e)
/// }
/// ```
pub fn decimal_to_f64(value: Decimal) -> Result<f64, DecimalError> {
    value.to_f64().ok_or(DecimalError::ConversionError {
        from_type: format!("Decimal: {value}"),
        to_type: "f64".to_string(),
        reason: "Failed to convert Decimal to f64".to_string(),
    })
}

/// Converts an f64 floating-point number to a Decimal.
///
/// This function attempts to convert an f64 floating-point number to a Decimal value.
/// If the conversion fails (for example, if the f64 represents NaN, infinity, or is otherwise
/// not representable as a Decimal), it returns a DecimalError with detailed information about
/// the failure.
///
/// # Parameters
///
/// * `value` - The f64 value to convert
///
/// # Returns
///
/// * `Result<Decimal, DecimalError>` - The converted Decimal value if successful, or a DecimalError
///   if the conversion fails
///
/// # Errors
///
/// Returns [`DecimalError::ConversionError`] when the `f64` operand is not
/// representable as a `Decimal`, for example `NaN`, `±Infinity`, or a value
/// whose magnitude exceeds the `Decimal` range.
///
/// # Example
///
/// ```rust
/// use rust_decimal::Decimal;
/// use tracing::info;
/// use optionstratlib::model::decimal::f64_to_decimal;
///
/// let float = std::f64::consts::PI;
/// match f64_to_decimal(float) {
///     Ok(decimal) => info!("Converted to Decimal: {}", decimal),
///     Err(e) => info!("Conversion error: {:?}", e)
/// }
/// ```
pub fn f64_to_decimal(value: f64) -> Result<Decimal, DecimalError> {
    Decimal::from_f64(value).ok_or(DecimalError::ConversionError {
        from_type: format!("f64: {value}"),
        to_type: "Decimal".to_string(),
        reason: "Failed to convert f64 to Decimal".to_string(),
    })
}

/// Attempts to convert a finite `f64` into a `Decimal`.
///
/// Returns `None` when `value` is not finite (`NaN`, `+∞`, `-∞`) or
/// when `Decimal::from_f64` rejects the conversion (the latter is
/// vanishingly rare for representable `f64`). Crate-private helper
/// that standardises the `is_finite()` check paired with
/// `Decimal::from_f64` at every `f64` → `Decimal` boundary inside
/// pricing, Greeks, volatility, and simulation kernels.
///
/// Callers wrap the `None` case with a domain-specific
/// `*Error::NonFinite { context, value }` via `ok_or_else`:
///
/// ```ignore
/// let v = finite_decimal(v_f64)
///     .ok_or_else(|| PricingError::non_finite("pricing::bs::call::d1", v_f64))?;
/// ```
///
/// The guard is enforced at the public boundary of every `f64`
/// numerical kernel per the rules (`rules/global_rules.md`
/// §Arithmetic).
#[must_use]
#[inline]
pub(crate) fn finite_decimal(value: f64) -> Option<Decimal> {
    if value.is_finite() {
        Decimal::from_f64(value)
    } else {
        None
    }
}

/// Generates a random positive value from a standard normal distribution.
///
/// This function samples from a normal distribution with mean 0.0 and standard
/// deviation 1.0, and returns the value as a `Positive` type. Since the normal
/// distribution can produce negative values, the function uses the `pos!` macro
/// to convert the sample to a `Positive` value, which will handle the conversion
/// according to the `Positive` type's implementation.
///
/// # Returns
///
/// A `Positive` value sampled from a standard normal distribution.
///
/// # Examples
///
/// ```rust
/// use optionstratlib::model::decimal::decimal_normal_sample;
/// use positive::Positive;
/// let normal = decimal_normal_sample();
/// ```
///
/// # Panics
///
/// The `unreachable!` branch fires only if
/// `statrs::distribution::Normal::new(0.0, 1.0)` rejects the provided
/// parameters. `statrs` accepts any finite mean together with a
/// strictly positive standard deviation, so `(0.0, 1.0)` is always
/// valid under the `statrs` contract and the arm is unreachable in
/// practice. Kept as a panic rather than `Result` to preserve the
/// infallible sampling API.
#[must_use]
pub fn decimal_normal_sample() -> Decimal {
    let mut t_rng = rand::rng();
    // Normal::new(0.0, 1.0) is provably valid (mean=0, std=1 are accepted
    // by `statrs::distribution::Normal`), so the Err arm is unreachable.
    let normal = match Normal::new(0.0, 1.0) {
        Ok(n) => n,
        Err(_) => unreachable!("standard normal parameters are always valid"),
    };
    Decimal::from_f64(normal.sample(&mut t_rng)).unwrap_or(Decimal::ZERO)
}

impl HasX for Decimal {
    fn get_x(&self) -> Decimal {
        *self
    }
}

/// Scale applied to banker's-rounding divisions in [`d_div`].
///
/// `28` matches `Decimal::MAX_SCALE` so a rounded division preserves every
/// digit of precision the backing 96-bit mantissa can represent without
/// triggering a later rescale overflow. Divisions that need a different
/// scale (for example a P&L that rounds to cents) should apply a subsequent
/// explicit `.round_dp_with_strategy(dp, RoundingStrategy::MidpointNearestEven)`.
pub(crate) const DIV_DEFAULT_SCALE: u32 = 28;

/// Checked `Decimal` addition with operand-preserving overflow reporting.
///
/// Crate-private helper used by every monetary-flow kernel in place of the
/// raw `+` operator. Wraps [`Decimal::checked_add`] and converts `None`
/// into a [`DecimalError::Overflow`] tagged with the static `op` string
/// passed in by the call-site.
///
/// # Errors
///
/// Returns [`DecimalError::Overflow`] when the result is outside the
/// representable `Decimal` range.
#[inline]
pub(crate) fn d_add(lhs: Decimal, rhs: Decimal, op: &'static str) -> Result<Decimal, DecimalError> {
    lhs.checked_add(rhs)
        .ok_or_else(|| DecimalError::overflow(op, lhs, rhs))
}

/// Checked sum over a slice of `Decimal` values.
///
/// Crate-private helper used by multi-leg strategy P&L aggregations
/// (spreads, condors, butterflies) where each leg already returns a
/// `Result<Decimal, _>` and the sum has to preserve the checked
/// semantics of the individual legs. Returns `Decimal::ZERO` on an
/// empty slice.
///
/// Delegates to [`d_sum_iter`] so the overflow-tagging semantics stay
/// in lock-step between the slice and iterator entry points.
///
/// # Errors
///
/// Returns [`DecimalError::Overflow`] on the first accumulation that
/// exceeds the representable `Decimal` range, tagged with the
/// supplied `op` string so the caller can be identified without a
/// stack trace.
#[inline]
pub(crate) fn d_sum(values: &[Decimal], op: &'static str) -> Result<Decimal, DecimalError> {
    d_sum_iter(values.iter().copied(), op)
}

/// Checked sum over any `IntoIterator` of `Decimal` values.
///
/// Zero-allocation counterpart to [`d_sum`]. Use at aggregation sites
/// that already have a natural iterator (e.g. `self.positions.iter()
/// .map(..)`) to avoid the intermediate `Vec<Decimal>` that `d_sum`
/// forces. Returns `Decimal::ZERO` on an empty iterator.
///
/// # Errors
///
/// Returns [`DecimalError::Overflow`] on the first accumulation that
/// exceeds the representable `Decimal` range, tagged with the
/// supplied `op` string so the caller can be identified without a
/// stack trace.
#[inline]
pub(crate) fn d_sum_iter<I>(iter: I, op: &'static str) -> Result<Decimal, DecimalError>
where
    I: IntoIterator<Item = Decimal>,
{
    let mut acc = Decimal::ZERO;
    for v in iter {
        acc = acc
            .checked_add(v)
            .ok_or_else(|| DecimalError::overflow(op, acc, v))?;
    }
    Ok(acc)
}

/// Checked `Decimal` subtraction with operand-preserving overflow reporting.
///
/// Crate-private helper used by every monetary-flow kernel in place of the
/// raw `-` operator. Wraps [`Decimal::checked_sub`] and converts `None`
/// into a [`DecimalError::Overflow`] tagged with the static `op` string
/// passed in by the call-site.
///
/// # Errors
///
/// Returns [`DecimalError::Overflow`] when the result is outside the
/// representable `Decimal` range.
#[inline]
pub(crate) fn d_sub(lhs: Decimal, rhs: Decimal, op: &'static str) -> Result<Decimal, DecimalError> {
    lhs.checked_sub(rhs)
        .ok_or_else(|| DecimalError::overflow(op, lhs, rhs))
}

/// Checked `Decimal` multiplication with operand-preserving overflow reporting.
///
/// Crate-private helper used by every monetary-flow kernel in place of the
/// raw `*` operator. Wraps [`Decimal::checked_mul`] and converts `None`
/// into a [`DecimalError::Overflow`] tagged with the static `op` string
/// passed in by the call-site.
///
/// # Errors
///
/// Returns [`DecimalError::Overflow`] when the result is outside the
/// representable `Decimal` range.
#[inline]
pub(crate) fn d_mul(lhs: Decimal, rhs: Decimal, op: &'static str) -> Result<Decimal, DecimalError> {
    lhs.checked_mul(rhs)
        .ok_or_else(|| DecimalError::overflow(op, lhs, rhs))
}

/// Checked `Decimal` division with banker's rounding at scale 28.
///
/// Crate-private helper used by every monetary-flow kernel in place of the
/// raw `/` operator. Performs [`Decimal::checked_div`] then re-rounds the
/// quotient with [`RoundingStrategy::MidpointNearestEven`] to the default
/// [`DIV_DEFAULT_SCALE`]. This policy is applied uniformly across the
/// crate so long-chain divisions do not silently accumulate bias.
///
/// # Errors
///
/// - Returns [`DecimalError::Overflow`] when the quotient is outside the
///   representable `Decimal` range.
/// - Returns [`DecimalError::ArithmeticError`] when `rhs` is zero.
#[inline]
pub(crate) fn d_div(lhs: Decimal, rhs: Decimal, op: &'static str) -> Result<Decimal, DecimalError> {
    if rhs.is_zero() {
        return Err(DecimalError::arithmetic_error(op, "division by zero"));
    }
    let raw = lhs
        .checked_div(rhs)
        .ok_or_else(|| DecimalError::overflow(op, lhs, rhs))?;
    Ok(raw.round_dp_with_strategy(DIV_DEFAULT_SCALE, RoundingStrategy::MidpointNearestEven))
}

/// Converts a Decimal value to f64 without error checking.
///
/// This macro converts a Decimal type to an f64 floating-point value.
/// It's an "unchecked" version that doesn't handle potential conversion errors.
///
/// # Parameters
/// * `$val` - A Decimal value to be converted to f64
///
/// # Example
/// ```rust
/// use rust_decimal_macros::dec;
/// use optionstratlib::d2fu;
/// let decimal_value = dec!(10.5);
/// let float_value = d2fu!(decimal_value);
/// ```
#[macro_export]
macro_rules! d2fu {
    ($val:expr) => {
        $crate::model::decimal::decimal_to_f64($val)
    };
}

/// Converts a Decimal value to f64 with error propagation.
///
/// This macro converts a Decimal type to an f64 floating-point value.
/// It propagates any errors that might occur during conversion using the `?` operator.
///
/// # Parameters
/// * `$val` - A Decimal value to be converted to f64
///
#[macro_export]
macro_rules! d2f {
    ($val:expr) => {
        $crate::model::decimal::decimal_to_f64($val)?
    };
}

/// Builds a `NonZeroUsize` from a literal or constant expression.
///
/// Ergonomic shorthand for the `NonZeroUsize::new(N).expect(..)` pattern
/// at call sites that know the value is non-zero by construction (tests,
/// examples, benchmarks). Use this whenever passing literal step or
/// simulation counts to one of the public pricing kernels migrated
/// in #337.
///
/// # Panics
///
/// Panics with a descriptive message if `$val` evaluates to zero. For
/// runtime values coming from JSON, CLI, or external APIs prefer
/// `NonZeroUsize::new(x).ok_or_else(..)` at the boundary instead.
///
/// # Examples
///
/// ```rust
/// use optionstratlib::nz;
/// use std::num::NonZeroUsize;
///
/// let steps = nz!(100);
/// assert_eq!(steps.get(), 100);
/// ```
#[macro_export]
macro_rules! nz {
    ($val:expr) => {{
        ::std::num::NonZeroUsize::new($val)
            .unwrap_or_else(|| panic!("nz!({}) must be non-zero", stringify!($val)))
    }};
}

/// Converts an f64 value to Decimal without error checking.
///
/// This macro converts an f64 floating-point value to a Decimal type.
/// It's an "unchecked" version that doesn't handle potential conversion errors.
///
/// # Parameters
/// * `$val` - An f64 value to be converted to Decimal
///
/// # Example
/// ```rust
/// use optionstratlib::f2du;
/// let float_value = 10.5;
/// let decimal_value = f2du!(float_value);
/// ```
#[macro_export]
macro_rules! f2du {
    ($val:expr) => {
        $crate::model::decimal::f64_to_decimal($val)
    };
}

/// Converts an f64 value to Decimal with error propagation.
///
/// This macro converts an f64 floating-point value to a Decimal type.
/// It propagates any errors that might occur during conversion using the `?` operator.
///
/// # Parameters
/// * `$val` - An f64 value to be converted to Decimal
///
#[macro_export]
macro_rules! f2d {
    ($val:expr) => {
        $crate::model::decimal::f64_to_decimal($val)?
    };
}

/// Conversion helpers' sanity tests (public module to support doctest wiring).
#[cfg(test)]
pub mod tests {
    use super::*;
    use std::str::FromStr;

    #[test]
    fn test_f64_to_decimal_valid() {
        let value = 42.42;
        let result = f64_to_decimal(value);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Decimal::from_str("42.42").unwrap());
    }

    #[test]
    fn test_f64_to_decimal_zero() {
        let value = 0.0;
        let result = f64_to_decimal(value);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Decimal::from_str("0").unwrap());
    }

    #[test]
    fn test_decimal_to_f64_valid() {
        let decimal = Decimal::from_str("42.42").unwrap();
        let result = decimal_to_f64(decimal);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42.42);
    }

    #[test]
    fn test_decimal_to_f64_zero() {
        let decimal = Decimal::from_str("0").unwrap();
        let result = decimal_to_f64(decimal);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0.0);
    }
}

#[cfg(test)]
mod tests_random_generation {
    use super::*;
    use approx::assert_relative_eq;
    use rand::distr::Distribution;
    use std::collections::HashMap;

    #[test]
    fn test_normal_sample_returns() {
        // Run the function multiple times to ensure it always returns a positive value
        for _ in 0..1000 {
            let sample = decimal_normal_sample();
            assert!(sample <= Decimal::TEN);
            assert!(sample >= -Decimal::TEN);
        }
    }

    #[test]
    fn test_normal_sample_distribution() {
        // Generate a large number of samples to check distribution characteristics
        const NUM_SAMPLES: usize = 10000;
        let mut samples = Vec::with_capacity(NUM_SAMPLES);

        for _ in 0..NUM_SAMPLES {
            samples.push(decimal_normal_sample().to_f64().unwrap());
        }

        // Calculate mean and standard deviation
        let sum: f64 = samples.iter().sum();
        let mean = sum / NUM_SAMPLES as f64;

        let variance_sum: f64 = samples.iter().map(|&x| (x - mean).powi(2)).sum();
        let std_dev = (variance_sum / NUM_SAMPLES as f64).sqrt();

        // Check if the distribution approximately matches a standard normal
        // Note: These tests use wide tolerances since we're working with random samples
        assert_relative_eq!(mean, 0.0, epsilon = 0.04);
        assert_relative_eq!(std_dev, 1.0, epsilon = 0.03);
    }

    #[test]
    fn test_normal_distribution_transformation() {
        let mut t_rng = rand::rng();
        let normal = Normal::new(-1.0, 0.5).unwrap(); // Deliberately using a distribution with negative mean

        // Count occurrences of values after transformation
        let mut value_counts: HashMap<i32, usize> = HashMap::new();
        const SAMPLES: usize = 5000;

        for _ in 0..SAMPLES {
            let raw_sample = normal.sample(&mut t_rng);
            let positive_sample = raw_sample.to_f64().unwrap();

            // Bucket values to the nearest integer for counting
            let bucket = (positive_sample.round() as i32).max(0);
            *value_counts.entry(bucket).or_insert(0) += 1;
        }

        // Verify that zero values appear frequently (due to negative values being transformed)
        assert!(value_counts.get(&0).unwrap_or(&0) > &(SAMPLES / 10));

        // Verify that we have a range of positive values
        let max_bucket = value_counts.keys().max().unwrap_or(&0);
        assert!(*max_bucket > 0);
    }

    #[test]
    fn test_normal_sample_consistency() {
        // This test ensures that multiple calls in sequence produce different values
        let sample1 = decimal_normal_sample();
        let sample2 = decimal_normal_sample();
        let sample3 = decimal_normal_sample();

        // It's statistically extremely unlikely to get the same value three times in a row
        // This verifies that the RNG is properly producing different values
        assert!(sample1 != sample2 || sample2 != sample3);
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod checked_helpers_tests {
    use super::*;

    #[test]
    fn d_add_happy_path() {
        let result = d_add(dec!(1.25), dec!(2.50), "test::add");
        assert_eq!(result.unwrap(), dec!(3.75));
    }

    #[test]
    fn d_add_overflow_on_max_plus_max() {
        let err = d_add(Decimal::MAX, Decimal::MAX, "test::add").unwrap_err();
        match err {
            DecimalError::Overflow { operation, .. } => assert_eq!(operation, "test::add"),
            other => panic!("expected Overflow, got {other:?}"),
        }
    }

    #[test]
    fn d_sub_happy_path() {
        let result = d_sub(dec!(10), dec!(3.5), "test::sub");
        assert_eq!(result.unwrap(), dec!(6.5));
    }

    #[test]
    fn d_sub_overflow_on_min_minus_max() {
        let err = d_sub(Decimal::MIN, Decimal::MAX, "test::sub").unwrap_err();
        assert!(
            matches!(err, DecimalError::Overflow { operation, .. } if operation == "test::sub")
        );
    }

    #[test]
    fn d_mul_happy_path() {
        let result = d_mul(dec!(2.5), dec!(4), "test::mul");
        assert_eq!(result.unwrap(), dec!(10.0));
    }

    #[test]
    fn d_mul_overflow_on_max_times_two() {
        let err = d_mul(Decimal::MAX, dec!(2), "test::mul").unwrap_err();
        assert!(
            matches!(err, DecimalError::Overflow { operation, .. } if operation == "test::mul")
        );
    }

    #[test]
    fn d_div_happy_path_exact() {
        let result = d_div(dec!(10), dec!(4), "test::div");
        assert_eq!(result.unwrap(), dec!(2.5));
    }

    #[test]
    fn d_div_applies_banker_rounding() {
        // Divide by three is recurring and must round half-to-even at the default scale.
        let result = d_div(dec!(1), dec!(3), "test::div").unwrap();
        // `1 / 3` at scale 28 under banker's rounding produces the canonical
        // `0.3333333333333333333333333333` (scale 28). Any other trailing digit
        // would signal the rounding strategy drifted.
        assert_eq!(result, dec!(0.3333333333333333333333333333));
    }

    #[test]
    fn d_div_zero_denominator_returns_arithmetic_error() {
        let err = d_div(dec!(1), Decimal::ZERO, "test::div").unwrap_err();
        assert!(matches!(err, DecimalError::ArithmeticError { .. }));
    }

    #[test]
    fn d_div_tag_is_preserved_on_overflow() {
        // `Decimal::MIN / 0.5` overflows because the quotient is 2 * MIN.
        let err = d_div(Decimal::MIN, dec!(0.5), "test::div").unwrap_err();
        match err {
            DecimalError::Overflow { operation, .. } => assert_eq!(operation, "test::div"),
            other => panic!("expected Overflow, got {other:?}"),
        }
    }

    #[test]
    fn d_sum_empty_returns_zero() {
        assert_eq!(d_sum(&[], "test::sum").unwrap(), Decimal::ZERO);
    }

    #[test]
    fn d_sum_happy_path() {
        let result = d_sum(&[dec!(1.5), dec!(2.25), dec!(-0.75), dec!(10)], "test::sum");
        assert_eq!(result.unwrap(), dec!(13));
    }

    #[test]
    fn d_sum_overflow_returns_tagged_error() {
        let err = d_sum(&[Decimal::MAX, Decimal::MAX], "test::sum").unwrap_err();
        assert!(
            matches!(err, DecimalError::Overflow { operation, .. } if operation == "test::sum")
        );
    }

    #[test]
    fn d_sum_iter_empty_returns_zero() {
        let empty: std::iter::Empty<Decimal> = std::iter::empty();
        assert_eq!(d_sum_iter(empty, "test::sum_iter").unwrap(), Decimal::ZERO);
    }

    #[test]
    fn d_sum_iter_happy_path_matches_d_sum() {
        let values = [dec!(1.5), dec!(2.25), dec!(-0.75), dec!(10)];
        let via_iter = d_sum_iter(values.iter().copied(), "test::sum_iter").unwrap();
        let via_slice = d_sum(&values, "test::sum_iter").unwrap();
        assert_eq!(via_iter, dec!(13));
        assert_eq!(via_iter, via_slice);
    }

    #[test]
    fn d_sum_iter_accepts_lazy_map() {
        // Exercise the no-allocation pathway: a `map` adapter over a range
        // should aggregate without any intermediate `Vec`.
        let sum = d_sum_iter((1i64..=4).map(Decimal::from), "test::sum_iter_lazy").unwrap();
        assert_eq!(sum, dec!(10));
    }

    #[test]
    fn d_sum_iter_overflow_returns_tagged_error() {
        let err = d_sum_iter([Decimal::MAX, Decimal::MAX], "test::sum_iter").unwrap_err();
        assert!(
            matches!(err, DecimalError::Overflow { operation, .. } if operation == "test::sum_iter")
        );
    }
}