optionstratlib-core 0.22.1

Core domain model of OptionStratLib: options, positions, legs, trades, checked Decimal helpers and their errors. Re-exported by the optionstratlib facade on every feature set.
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 21/8/24
******************************************************************************/
use crate::error::DecimalError;
use crate::model::Position;
use crate::model::decimal::{d_add, d_div, d_mul, d_sub, decimal_to_f64};
use crate::model::types::{OptionStyle, OptionType, Side};
use crate::model::{ExpirationDate, Options};
use chrono::{NaiveDateTime, TimeZone, Utc};
use positive::{Positive, PositiveError};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;

/// Build a `Positive` from a compile-time non-negative `Decimal` literal.
///
/// All call sites in this module pass `dec!(X.X)` with a statically
/// non-negative value, so the checked constructor is total; the
/// `Positive::ZERO` branch is unreachable and only exists to keep the
/// call site free of `.unwrap()`/`.expect()`.
#[inline]
fn pos_lit(value: Decimal) -> Positive {
    Positive::new_decimal(value).unwrap_or(Positive::ZERO)
}

/// Subtracts `rhs` from `lhs`, flooring the result at zero.
///
/// `Positive::sub_or_zero` is deprecated in positive 0.6 because saturating
/// arithmetic hides underflow. Every OptionStratLib call site genuinely wants
/// the floor (a quoted price or a strike offset never goes negative), so the
/// decision is made once, here, on top of the checked `sub_or_none`: `None`
/// (the difference would be negative) becomes zero, and no saturating
/// arithmetic is used on the `Decimal` itself. Use it only where a negative
/// difference has no meaning; anywhere else it hides an underflow, and the
/// checked `Positive::sub_or_none` is the right call.
#[doc(hidden)]
#[must_use]
#[inline]
pub fn sub_floor_zero(lhs: Positive, rhs: &Decimal) -> Positive {
    lhs.sub_or_none(rhs).unwrap_or(Positive::ZERO)
}

/// Converts a vector of `Positive` values to a vector of `f64` values.
///
/// This utility function transforms a collection of `Positive` type values
/// to standard floating-point values by applying the `to_f64()` method to each element.
/// The function consumes the input vector and returns a new vector containing the converted values.
///
/// # Parameters
///
/// * `vec` - A vector of `Positive` values to be converted.
///
/// # Returns
///
/// A vector of `f64` values corresponding to the input `Positive` values,
/// each the `f64` nearest to it ([`decimal_to_f64`], #828).
///
/// # Errors
///
/// Returns the [`DecimalError`] of [`decimal_to_f64`] for a value it cannot
/// convert.
pub fn positive_f64_to_f64(vec: Vec<Positive>) -> Result<Vec<f64>, DecimalError> {
    vec.into_iter()
        .map(|value| decimal_to_f64(value.to_dec()))
        .collect()
}

/// Creates a sample option contract with predefined parameters for testing or demonstration purposes.
///
/// This utility function simplifies the creation of option contracts by providing a standard
/// configuration with reasonable defaults. It creates a European-style option with a 30-day
/// expiration and a fixed risk-free rate of 5%.
///
/// # Parameters
///
/// * `option_style` - Specifies whether the option is a Call or Put.
/// * `side` - Determines if the position is Long or Short.
/// * `underlying_price` - The current market price of the underlying asset.
/// * `quantity` - The number of contracts in the position.
/// * `strike_price` - The price at which the option holder can exercise the option.
/// * `volatility` - The implied volatility used for pricing the option.
///
/// # Returns
///
/// An `Options` struct configured with the specified parameters and sensible defaults.
///
/// # Examples
///
/// ```rust
/// use optionstratlib_core::model::{OptionStyle, Side};
/// use positive::pos_or_panic;
/// use optionstratlib_core::model::utils::create_sample_option;
/// let option = create_sample_option(
///     OptionStyle::Call,
///     Side::Long,
///     pos_or_panic!(150.0),  // underlying price
///     pos_or_panic!(10.0),   // quantity
///     pos_or_panic!(155.0),  // strike price
///     pos_or_panic!(0.25),   // volatility (25%)
/// );
/// ```
#[allow(dead_code)]
#[must_use]
pub fn create_sample_option(
    option_style: OptionStyle,
    side: Side,
    underlying_price: Positive,
    quantity: Positive,
    strike_price: Positive,
    volatility: Positive,
) -> Options {
    Options::new(
        OptionType::European,
        side,
        "AAPL".to_string(),
        strike_price,
        ExpirationDate::Days(pos_lit(dec!(30.0))),
        volatility,
        quantity,
        underlying_price,
        dec!(0.05),
        option_style,
        pos_lit(dec!(0.01)),
        None,
    )
}

/// Creates a sample position for testing and demonstration purposes.
///
/// This function generates a `Position` instance with predefined values for some fields
/// while allowing customization of key option parameters. It's useful for creating test
/// scenarios, examples, or sample data for option position analysis.
///
/// # Parameters
///
/// * `option_style` - The style of the option (Call or Put)
/// * `side` - Whether the position is Long or Short
/// * `underlying_price` - The current price of the underlying asset
/// * `quantity` - The number of option contracts in the position
/// * `strike_price` - The price at which the option can be exercised
/// * `implied_volatility` - The market's forecast of likely movement in the underlying asset
///
/// # Returns
///
/// A `Position` instance with the specified parameters and these default values:
/// * European-style option
/// * "AAPL" as the underlying symbol
/// * 30-day expiration
/// * 5% risk-free rate
/// * 1% dividend yield
/// * Premium of $5.00
/// * Open and close fees of $0.50 each
/// * Current date and time
///
/// # Example
///
/// ```rust
/// use optionstratlib_core::model::utils::create_sample_position;
/// use optionstratlib_core::model::{OptionStyle, Side};
/// use positive::{pos_or_panic, Positive};
/// let sample_call = create_sample_position(
///     OptionStyle::Call,
///     Side::Long,
///     pos_or_panic!(150.0),  // underlying price
///     Positive::ONE,    // quantity
///     pos_or_panic!(155.0),  // strike price
///     pos_or_panic!(0.25)    // implied volatility
/// );
/// ```
#[allow(dead_code)]
#[must_use]
pub fn create_sample_position(
    option_style: OptionStyle,
    side: Side,
    underlying_price: Positive,
    quantity: Positive,
    strike_price: Positive,
    implied_volatility: Positive,
) -> Position {
    Position {
        option: Options {
            option_type: OptionType::European,
            side,
            underlying_symbol: "AAPL".to_string(),
            strike_price,
            expiration_date: ExpirationDate::Days(pos_lit(dec!(30.0))),
            implied_volatility,
            quantity,
            contract_size: Positive::ONE,
            underlying_price,
            risk_free_rate: dec!(0.05),
            option_style,
            dividend_yield: pos_lit(dec!(0.01)),
            exotic_params: None,
        },
        premium: pos_lit(dec!(5.0)),
        date: Utc::now(),
        open_fee: pos_lit(dec!(0.5)),
        close_fee: pos_lit(dec!(0.5)),
        epic: Some("Epic123".to_string()),
        extra_fields: None,
    }
}

/// Creates a sample Options object with a specific expiration date.
///
/// This utility function simplifies the creation of option contracts for testing
/// or demonstration purposes by providing a specific expiration date using a NaiveDateTime.
/// It creates a European-style option with predefined parameters and a fixed risk-free rate of 5%
/// and dividend yield of 1%.
///
/// # Parameters
///
/// * `option_style` - The style of the option (Call or Put)
/// * `side` - The position side (Long or Short)
/// * `underlying_price` - The current price of the underlying asset
/// * `quantity` - The number of option contracts
/// * `strike_price` - The strike price of the option
/// * `volatility` - The implied volatility for pricing the option
/// * `naive_date` - The expiration date and time in naive format (will be converted to UTC)
///
/// # Returns
///
/// Returns a fully configured Options instance with "AAPL" as the underlying symbol.
#[must_use]
pub fn create_sample_option_with_date(
    option_style: OptionStyle,
    side: Side,
    underlying_price: Positive,
    quantity: Positive,
    strike_price: Positive,
    volatility: Positive,
    naive_date: NaiveDateTime,
) -> Options {
    Options::new(
        OptionType::European,
        side,
        "AAPL".to_string(),
        strike_price,
        ExpirationDate::DateTime(Utc.from_utc_datetime(&naive_date)),
        volatility,
        quantity,
        underlying_price,
        dec!(0.05),
        option_style,
        pos_lit(dec!(0.01)),
        None,
    )
}

/// Creates a sample Options object with a specific expiration date in days.
///
/// This utility function simplifies the creation of option contracts for testing
/// or demonstration purposes by providing a specific expiration date expressed
/// in days.
/// It creates a European-style option with predefined parameters and a fixed
/// risk-free rate of 5% and dividend yield of 1%.
///
/// # Parameters
///
/// * `option_style` - The style of the option (Call or Put)
/// * `side` - The position side (Long or Short)
/// * `underlying_price` - The current price of the underlying asset
/// * `quantity` - The number of option contracts
/// * `strike_price` - The strike price of the option
/// * `volatility` - The implied volatility for pricing the option
/// * `expiration_days` - The expiration days
///
/// # Returns
///
/// Returns a fully configured Options instance with "AAPL" as the underlying symbol.
#[must_use]
pub fn create_sample_option_with_days(
    option_style: OptionStyle,
    side: Side,
    underlying_price: Positive,
    quantity: Positive,
    strike_price: Positive,
    volatility: Positive,
    expiration_days: Positive,
) -> Options {
    Options::new(
        OptionType::European,
        side,
        "AAPL".to_string(),
        strike_price,
        ExpirationDate::Days(expiration_days),
        volatility,
        quantity,
        underlying_price,
        dec!(0.05),
        option_style,
        pos_lit(dec!(0.01)),
        None,
    )
}

/// Creates a simplified sample option contract for testing or demonstration purposes.
///
/// This function generates an Options instance with pre-defined values, requiring only
/// the specification of the option style (Call or Put) and market position (Long or Short).
/// It uses Apple Inc. (AAPL) as the underlying security with standard parameters suitable
/// for basic examples or testing scenarios.
///
/// # Parameters
///
/// * `option_style` - Specifies whether the option is a Call or Put
/// * `side` - Indicates whether the position is Long or Short
///
/// # Returns
///
/// Returns an `Options` instance with the following predefined values:
/// - European-style option
/// - AAPL as the underlying symbol
/// - Strike price of $100.0
/// - 30 days until expiration
/// - 20% implied volatility (0.2)
/// - Quantity of 1.0 contracts
/// - Underlying price of $100.0
/// - 5% risk-free rate
/// - 1% dividend yield
/// - No exotic parameters
///
/// # Examples
///
/// ```
/// use optionstratlib_core::model::utils::create_sample_option_simplest;
/// use optionstratlib_core::model::{OptionStyle, Side};
/// let long_call = create_sample_option_simplest(OptionStyle::Call, Side::Long);
/// let short_put = create_sample_option_simplest(OptionStyle::Put, Side::Short);
/// ```
#[must_use]
pub fn create_sample_option_simplest(option_style: OptionStyle, side: Side) -> Options {
    Options::new(
        OptionType::European,
        side,
        "AAPL".to_string(),
        Positive::HUNDRED,
        ExpirationDate::Days(pos_lit(dec!(30.0))),
        pos_lit(dec!(0.2)),
        Positive::ONE,
        Positive::HUNDRED,
        dec!(0.05),
        option_style,
        pos_lit(dec!(0.01)),
        None,
    )
}

/// Creates a sample option with specified parameters and default values.
///
/// This function provides a convenient way to create an `Options` instance with common default values
/// while allowing customization of the most important parameters: side, option style, and strike price.
/// All other parameters are set to reasonable defaults for testing or demonstration purposes.
///
/// # Parameters
/// * `side` - The position side (Long or Short) for the option.
/// * `option_style` - The style of option (Call or Put).
/// * `strike` - The strike price of the option as a `Positive` value.
///
/// # Returns
/// An `Options` instance representing a European option on AAPL stock with:
/// * 30 days until expiration
/// * 20% implied volatility
/// * Quantity of 1.0
/// * Underlying price of $100.0
/// * 5% risk-free rate
/// * 1% dividend yield
/// * No exotic parameters
///
/// # Examples
/// ```
/// use optionstratlib_core::model::utils::create_sample_option_simplest_strike;
/// use optionstratlib_core::model::{OptionStyle, Side};
/// use positive::pos_or_panic;
/// let long_call = create_sample_option_simplest_strike(
///     Side::Long,
///     OptionStyle::Call,
///     pos_or_panic!(105.0)
/// );
/// ```
#[must_use]
pub fn create_sample_option_simplest_strike(
    side: Side,
    option_style: OptionStyle,
    strike: Positive,
) -> Options {
    Options::new(
        OptionType::European,
        side,
        "AAPL".to_string(),
        strike,
        ExpirationDate::Days(pos_lit(dec!(30.0))),
        pos_lit(dec!(0.2)),
        Positive::ONE,
        Positive::HUNDRED,
        dec!(0.05),
        option_style,
        pos_lit(dec!(0.01)),
        None,
    )
}

/// Computes the mean and standard deviation of a vector containing `Positive` values.
///
/// # Arguments
///
/// * `vec` - A non-empty `Vec<Positive>` containing the data for which the mean and standard
///   deviation are to be calculated.
///
/// # Returns
///
/// A tuple containing:
/// - `Positive` - The mean of the provided vector.
/// - `Positive` - The standard deviation of the provided vector.
///
/// # Errors
///
/// Returns [`PositiveError::ArithmeticError`] when the sample is empty — no
/// mean is defined for it — and when accumulating the values or the squared
/// deviations overflows the `Positive` range. Returns
/// [`PositiveError::InvalidValue`] when a squared deviation is not
/// representable as a finite `f64`. The raw `Positive` operators abort the
/// process in all of those cases, so every step is taken through its checked
/// counterpart.
///
/// # Example
///
/// ```rust
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use positive::Positive;
/// use optionstratlib_core::model::utils::mean_and_std;
///
/// let data = vec![
///     Positive::new(2.0)?, Positive::new(4.0)?, Positive::new(4.0)?, Positive::new(4.0)?,
///     Positive::new(5.0)?, Positive::new(5.0)?, Positive::new(7.0)?, Positive::new(9.0)?,
/// ];
/// let (mean, std) = mean_and_std(data)?;
///
/// assert_eq!(mean.to_f64(), 5.0);
/// assert_eq!(std.to_f64(), 4.0_f64.sqrt());
/// # Ok(())
/// # }
/// ```
///
/// # Details
///
/// - The mean is computed by summing the `Positive` values and dividing by the count of elements.
/// - The standard deviation is derived from the variance, which is the average of the squared differences
///   from the mean. The variance is then converted into standard deviation by taking its square root.
///
/// Note: The `Positive` type and associated operations are defined in the `crate::model::types` module.
pub fn mean_and_std(vec: Vec<Positive>) -> Result<(Positive, Positive), PositiveError> {
    if vec.is_empty() {
        return Err(PositiveError::ArithmeticError {
            operation: "mean_and_std".to_string(),
            reason: "an empty sample has no mean".to_string(),
        });
    }
    // `Decimal::from(usize)` is exact for every length a `Vec` can hold, so
    // the divisor introduces no rounding of its own.
    let count = Decimal::from(vec.len());

    let mut total = Positive::ZERO;
    for value in &vec {
        total = total.checked_add(value)?;
    }
    let mean = total.checked_div_dec(count)?;

    // The squared deviations are taken in `f64`, as they always have been, so
    // the returned figures are unchanged for every sample the panicking form
    // accepted. What changes is the reporting: a deviation that overflows
    // `f64` now surfaces instead of collapsing to zero.
    // Each `Decimal` reaches `f64` through `decimal_to_f64` (#828); its error
    // is reported as the arithmetic error this function returns.
    let to_f64 = |value: Positive| {
        decimal_to_f64(value.to_dec()).map_err(|e| PositiveError::ArithmeticError {
            operation: "mean_and_std".to_string(),
            reason: e.to_string(),
        })
    };
    let mean_f64 = to_f64(mean)?;
    let mut squared_deviations = Positive::ZERO;
    for value in &vec {
        let deviation = Positive::new((to_f64(*value)? - mean_f64).powi(2))?;
        squared_deviations = squared_deviations.checked_add(&deviation)?;
    }
    let variance = squared_deviations.checked_div_dec(count)?;
    let std = Positive::new(to_f64(variance)?.sqrt())?; // scan-banned: allow -- f64 `sqrt`: returns NaN for negative input, it does not abort; the non-finite value is rejected at the `Decimal` boundary

    Ok((mean, std))
}

/// Trait for rounding operations on numeric types, specifically for financial calculations.
///
/// This trait provides methods to round a number to the nearest integer and to a specified
/// number of decimal places, ensuring precision and accuracy in financial computations.
///
pub trait ToRound {
    /// Rounds the number to the nearest integer.
    ///
    /// This method rounds the number to the nearest whole number, removing any fractional part.
    fn round(&self) -> Decimal;

    /// Rounds the number to a specified number of decimal places.
    ///
    /// This method rounds the number to the specified number of digits after the decimal point,
    /// providing control over the precision of the rounded value.
    ///
    /// # Arguments
    ///
    /// * `decimal_places` - The number of decimal places to round to.
    fn round_to(&self, decimal_places: u32) -> Decimal;
}

/// Generates a price vector for the payoff graph: `num_points` prices evenly
/// spaced from `min_price` to `max_price`, both ends included.
///
/// # Errors
///
/// Returns [`DecimalError::InvalidValue`] when `num_points` is below two,
/// so there is no spacing between the ends (one point divided by zero and
/// zero points underflowed `num_points - 1`, #788), or too large to
/// allocate, and
/// [`DecimalError::Overflow`] when the range, the step or a price leaves the
/// `Decimal` range.
pub fn generate_price_points(
    min_price: Decimal,
    max_price: Decimal,
    num_points: usize,
) -> Result<Vec<Decimal>, DecimalError> {
    let Some(intervals) = num_points.checked_sub(1).filter(|n| *n > 0) else {
        return Err(DecimalError::invalid_value(
            num_points as f64,
            "a price grid needs at least two points",
        ));
    };
    let range = d_sub(
        max_price,
        min_price,
        "model::utils::generate_price_points/range",
    )?;
    let step = d_div(
        range,
        Decimal::from(intervals),
        "model::utils::generate_price_points/step",
    )?;
    // Reserved fallibly: `Vec::with_capacity` aborts with `capacity overflow`
    // on a count wider than the address space.
    let mut prices = Vec::new();
    prices.try_reserve_exact(num_points).map_err(|_| {
        DecimalError::invalid_value(
            num_points as f64,
            "a price grid this large cannot be allocated",
        )
    })?;

    for i in 0..num_points {
        let offset = d_mul(
            step,
            Decimal::from(i),
            "model::utils::generate_price_points/offset",
        )?;
        prices.push(d_add(
            min_price,
            offset,
            "model::utils::generate_price_points/price",
        )?);
    }

    Ok(prices)
}

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

    #[test]
    fn test_generate_price_points_spans_both_ends() {
        let prices = generate_price_points(dec!(90), dec!(110), 5);
        assert_eq!(
            prices.ok(),
            Some(vec![dec!(90), dec!(95), dec!(100), dec!(105), dec!(110)])
        );
    }

    // One point divided by zero (`Division by zero`) and zero points
    // underflowed `num_points - 1` (#788).
    #[test]
    fn test_generate_price_points_below_two_points_is_error() {
        for num_points in [0, 1] {
            assert!(matches!(
                generate_price_points(dec!(90), dec!(110), num_points),
                Err(DecimalError::InvalidValue { .. })
            ));
        }
    }

    // `Vec::with_capacity(usize::MAX)` aborted with `capacity overflow`.
    #[test]
    fn test_generate_price_points_unallocatable_is_error() {
        assert!(matches!(
            generate_price_points(dec!(90), dec!(110), usize::MAX),
            Err(DecimalError::InvalidValue { .. })
        ));
    }

    #[test]
    fn test_generate_price_points_overflow_is_error() {
        assert!(generate_price_points(Decimal::MIN, Decimal::MAX, 3).is_err());
    }
}

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

    #[test]
    fn test_positive_f64_to_f64_non_empty() {
        let positive_vec = vec![
            Positive::new(10.0).unwrap(),
            Positive::new(20.0).unwrap(),
            Positive::new(30.0).unwrap(),
        ];

        let f64_vec = positive_f64_to_f64(positive_vec);

        assert!(matches!(f64_vec, Ok(v) if v == vec![10.0, 20.0, 30.0]));
    }

    #[test]
    fn test_positive_f64_to_f64_single_element() {
        let positive_vec = vec![Positive::new(42.0).unwrap()];

        let f64_vec = positive_f64_to_f64(positive_vec);

        assert!(matches!(f64_vec, Ok(v) if v == vec![42.0]));
    }

    #[test]
    #[should_panic]
    fn test_positive_f64_to_f64_invalid_positivef64() {
        Positive::new(-10.0).unwrap();
    }
}

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

    use approx::assert_relative_eq;
    use positive::pos_or_panic;

    #[test]
    fn test_basic_mean_and_std() {
        let values = vec![
            Positive::TWO,
            pos_or_panic!(4.0),
            pos_or_panic!(4.0),
            pos_or_panic!(4.0),
            pos_or_panic!(5.0),
            pos_or_panic!(5.0),
            pos_or_panic!(7.0),
            pos_or_panic!(9.0),
        ];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert_relative_eq!(mean.to_f64(), 5.0, epsilon = 0.0001);
        assert_relative_eq!(std.to_f64(), 2.0, epsilon = 0.0001);
    }

    #[test]
    fn test_identical_values() {
        let values = vec![
            pos_or_panic!(5.0),
            pos_or_panic!(5.0),
            pos_or_panic!(5.0),
            pos_or_panic!(5.0),
        ];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert_relative_eq!(mean.to_f64(), 5.0, epsilon = 0.0001);
        assert_relative_eq!(std.to_f64(), 0.0, epsilon = 0.0001);
    }

    #[test]
    fn test_single_value() {
        let values = vec![pos_or_panic!(3.0)];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert_relative_eq!(mean.to_f64(), 3.0, epsilon = 0.0001);
        assert_relative_eq!(std.to_f64(), 0.0, epsilon = 0.0001);
    }

    #[test]
    fn test_small_numbers() {
        let values = vec![pos_or_panic!(0.1), pos_or_panic!(0.2), pos_or_panic!(0.3)];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert_relative_eq!(mean.to_f64(), 0.2, epsilon = 0.0001);
        assert_relative_eq!(std.to_f64(), 0.08164966, epsilon = 0.0001);
    }

    #[test]
    fn test_large_numbers() {
        let values = vec![
            pos_or_panic!(1000.0),
            pos_or_panic!(2000.0),
            pos_or_panic!(3000.0),
        ];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert_relative_eq!(mean.to_f64(), 2000.0, epsilon = 0.0001);
        assert_relative_eq!(std.to_f64(), 816.4966, epsilon = 0.1);
    }

    #[test]
    fn test_mixed_range() {
        let values = vec![
            pos_or_panic!(0.5),
            pos_or_panic!(5.0),
            pos_or_panic!(50.0),
            pos_or_panic!(500.0),
        ];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert_relative_eq!(mean.to_f64(), 138.875, epsilon = 0.001);
        assert_relative_eq!(std.to_f64(), 209.392, epsilon = 0.001);
    }

    #[test]
    fn test_empty_vector() {
        let values: Vec<Positive> = vec![];
        let error = mean_and_std(values).expect_err("an empty sample has no mean");
        assert!(matches!(error, PositiveError::ArithmeticError { .. }));
    }

    #[test]
    fn test_sum_overflow_returns_error() {
        let values = vec![Positive::MAX, Positive::MAX];
        let error = mean_and_std(values).expect_err("two maxima overflow the sum");
        assert!(matches!(error, PositiveError::ArithmeticError { .. }));
    }

    #[test]
    fn test_symmetric_distribution() {
        let values = vec![
            Positive::ONE,
            Positive::TWO,
            pos_or_panic!(3.0),
            pos_or_panic!(4.0),
            pos_or_panic!(5.0),
        ];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert_relative_eq!(mean.to_f64(), 3.0, epsilon = 0.0001);
        assert_relative_eq!(std.to_f64(), std::f64::consts::SQRT_2, epsilon = 0.0001);
    }

    #[test]
    fn test_result_is_positive() {
        let values = vec![Positive::ONE, Positive::TWO, pos_or_panic!(3.0)];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert!(mean > Positive::ZERO);
        assert!(std > Positive::ZERO);
    }

    #[test]
    fn test_precision() {
        let values = vec![
            pos_or_panic!(1.23456789),
            pos_or_panic!(2.34567890),
            pos_or_panic!(3.45678901),
        ];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert_relative_eq!(mean.to_f64(), 2.34567860, epsilon = 0.00000001);
        assert_relative_eq!(std.to_f64(), 0.90721797, epsilon = 0.00000001);
    }

    #[test]
    fn test_precision_bis() {
        let values = vec![
            pos_or_panic!(0.123456789),
            pos_or_panic!(0.134567890),
            pos_or_panic!(0.145678901),
        ];
        let (mean, std) = mean_and_std(values).expect("the sample is non-empty and finite");

        assert_relative_eq!(mean.to_f64(), 0.13456786, epsilon = 0.00000001);
        assert_relative_eq!(std.to_f64(), 0.00907213, epsilon = 0.00000001);
    }
}