optionstratlib-pricing 0.22.1

Option pricing models, Greeks and implied volatility of OptionStratLib, on Decimal and Positive boundaries. Re-exported by the optionstratlib facade under its `pricing` feature.
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 19/9/25
******************************************************************************/

//! Pricing capability for the core [`optionstratlib_core::model::Options`] contract.
//!
//! [`OptionPricing`] is the pricing-owned extension trait that carries every
//! model-based valuation of an [`optionstratlib_core::model::Options`] contract: binomial lattice,
//! Black-Scholes closed form, Monte Carlo over supplied paths, the telegraph
//! finite-difference kernel, the time-value decomposition and the implied
//! volatility bisection. The core type keeps only contract data and payoff
//! arithmetic; this trait is where the numerics attach to it.
//!
//! `Options` has no pricing methods of its own; bring this trait into scope
//! (directly, or through the `optionstratlib` prelude) to price one:
//!
//! ```rust
//! use optionstratlib_pricing::pricing::OptionPricing;
//! use optionstratlib_core::model::{ExpirationDate, OptionStyle, OptionType, Options, Side};
//! use optionstratlib_core::{model::Positive, pos_or_panic};
//! use rust_decimal_macros::dec;
//!
//! let option = Options::new(
//!     OptionType::European,
//!     Side::Long,
//!     "TEST".to_string(),
//!     pos_or_panic!(100.0),
//!     ExpirationDate::Days(pos_or_panic!(30.0)),
//!     pos_or_panic!(0.2),
//!     Positive::ONE,
//!     pos_or_panic!(100.0),
//!     dec!(0.05),
//!     OptionStyle::Call,
//!     Positive::ZERO,
//!     None,
//! );
//! let price = option.calculate_price_black_scholes()?;
//! assert!(price > rust_decimal::Decimal::ZERO);
//! # Ok::<(), optionstratlib_core::error::OptionsError>(())
//! ```

use crate::error::{PricingError, VolatilityError};
use crate::pricing::black_scholes_model::european_price_band;
use crate::pricing::constants::{IV_TOLERANCE, MAX_ITERATIONS_IV};
use crate::pricing::iv_solver::{
    IV_BRACKET_MAX, IvOutcome, iv_initial_guess, long_residual, solve_implied_volatility,
};
use crate::pricing::monte_carlo::price_option_monte_carlo;
use crate::pricing::{
    BinomialPricingParams, RegimeVolatility, TELEGRAPH_PATHS, black_scholes,
    generate_binomial_tree, price_binomial, telegraph,
};
use optionstratlib_core::constants::MIN_VOLATILITY;
use optionstratlib_core::error::{OptionsError, OptionsResult};
use optionstratlib_core::model::Options;
use optionstratlib_core::model::Positive;
use optionstratlib_core::model::decimal::{d_add, d_sub};
use optionstratlib_core::model::types::OptionType;
use rand::Rng;
use rust_decimal::Decimal;
use std::num::NonZeroUsize;

/// Result type for binomial tree pricing models, containing:
/// - The option price
/// - Price tree (asset price evolution)
/// - Option value tree (option value at each node)
pub type PriceBinomialTree = OptionsResult<(Decimal, Vec<Vec<Decimal>>, Vec<Vec<Decimal>>)>;

/// Model-based valuation of an [`optionstratlib_core::model::Options`] contract.
///
/// Every method is a pure function of the contract data held by the
/// implementor plus the method's own parameters; none of them mutates the
/// contract. Long positions report positive prices, short positions report
/// the negated price of the equivalent long contract.
///
/// The trait is implemented for [`optionstratlib_core::model::Options`] by the
/// pricing layer. `Options` has no pricing methods of its own: bring this
/// trait into scope to price one.
pub trait OptionPricing {
    /// Calculates the price of an option using the binomial tree model.
    ///
    /// This method implements the binomial option pricing model which constructs a
    /// discrete-time lattice (tree) of possible future underlying asset prices to
    /// determine the option's value. The approach is particularly valuable for pricing
    /// American options and other early-exercise scenarios.
    ///
    /// The calculation divides the time to expiration into a specified number of steps,
    /// creating a binomial tree that represents possible price paths of the underlying asset.
    /// The option's value is then calculated by working backward from expiration to the
    /// present value.
    ///
    /// # Parameters
    ///
    /// * `no_steps` - The number of steps to use in the binomial tree calculation,
    ///   as a [`NonZeroUsize`] so zero is structurally invalid at the type level
    ///   (no runtime check required). Higher values increase accuracy but also
    ///   computational cost. See [`crate::pricing::constants::DEFAULT_BINOMIAL_STEPS`]
    ///   for a sensible default.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Decimal>` - A result containing the calculated option price as a
    ///   Decimal value, or an OptionsError if the calculation failed.
    ///
    /// # Errors
    ///
    /// Returns an `OptionsError` if:
    /// * The time to expiration calculation fails
    /// * The binomial price calculation fails
    fn calculate_price_binomial(&self, no_steps: NonZeroUsize) -> OptionsResult<Decimal>;

    /// Calculates option price using the binomial tree model.
    ///
    /// This method implements a binomial tree (lattice) approach to option pricing, which
    /// discretizes the underlying asset's price movement over time. The model builds a tree
    /// of possible future asset prices and works backwards to determine the current option value.
    ///
    /// # Parameters
    ///
    /// * `no_steps` - The number of discrete time steps to use in the model,
    ///   as a [`NonZeroUsize`] so zero is structurally invalid at the type
    ///   level. Higher values increase precision but also computational cost.
    ///
    /// # Returns
    ///
    /// * `PriceBinomialTree` - A result containing:
    ///   - The calculated option price
    ///   - The asset price tree (underlying price evolution)
    ///   - The option value tree (option price at each node)
    ///
    /// This method is particularly valuable for pricing American options and other early-exercise
    /// scenarios that cannot be accurately priced using closed-form solutions.
    ///
    /// # Errors
    ///
    /// Returns [`OptionsError::ExpirationDate`] when the option's expiration
    /// cannot be converted to a positive year fraction, or propagates any
    /// `PricingError` surfaced by [`generate_binomial_tree`] (e.g.
    /// [`PricingError::BinomialNodeMissing`] or [`PricingError::SqrtFailure`]).
    fn calculate_price_binomial_tree(&self, no_steps: NonZeroUsize) -> PriceBinomialTree;

    /// Calculates option price using the Black-Scholes model.
    ///
    /// This method implements the Black-Scholes option pricing formula, which provides
    /// a closed-form solution for European-style options. The model assumes lognormal
    /// distribution of underlying asset prices and constant volatility.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Decimal>` - A result containing the calculated option price
    ///   as a Decimal value, or an error if the calculation failed.
    ///
    /// This method is computationally efficient but limited to European options without
    /// early exercise capabilities.
    ///
    /// # Errors
    ///
    /// Propagates any `PricingError` returned by [`black_scholes`] (wrapped as
    /// `OptionsError::PricingError`), most commonly
    /// `PricingError::ExpirationDate` when the expiration cannot be resolved
    /// or `PricingError::MethodError` when the closed-form formula fails
    /// numerically.
    fn calculate_price_black_scholes(&self) -> OptionsResult<Decimal>;

    /// Calculates the price of an option using the Monte Carlo simulation method.
    ///
    /// # Arguments
    ///
    /// * `prices` - A slice of `Positive` values representing the prices used
    ///   in the Monte Carlo simulation.
    ///
    /// # Returns
    ///
    /// * `OptionsResult<Positive>` - The calculated price of the option wrapped in
    ///   an `OptionsResult`. This will return a valid `Positive` value if successful,
    ///   or an error if the simulation fails.
    ///
    /// # Errors
    ///
    /// This function will return an error in the `OptionsResult` if the internal
    /// Monte Carlo price computation fails during the execution of `price_option_monte_carlo`.
    fn calculate_price_montecarlo(&self, prices: &[Positive]) -> OptionsResult<Positive>;

    /// Calculates option price with the telegraph regime-switching
    /// volatility Monte-Carlo pricer.
    ///
    /// Averages the discounted payoff over
    /// [`crate::pricing::TELEGRAPH_PATHS`] simulated paths whose volatility
    /// switches between the two levels of `volatility`, with both transition
    /// rates estimated from returns simulated at the option's implied
    /// volatility; see [`crate::pricing::telegraph()`] for the model. Call
    /// that function directly to choose the path count or the rates.
    ///
    /// # Parameters
    ///
    /// * `no_steps` - The number of discrete time steps to use in the model,
    ///   as a [`NonZeroUsize`] so zero is structurally invalid at the type
    ///   level. Higher values increase precision but also computational cost.
    /// * `volatility` - The volatilities of the two regimes. A single implied
    ///   volatility does not identify two levels, so the caller states them;
    ///   [`RegimeVolatility::constant`]`(option.implied_volatility)` prices at
    ///   the option's own volatility, which converges to Black-Scholes.
    /// * `rng` - The generator every draw of the telegraph simulation is
    ///   taken from (see [`crate::pricing::telegraph()`]). A seeded generator
    ///   such as [`optionstratlib_core::utils::deterministic_rng`] makes the
    ///   price reproducible; pass `&mut rand::rng()` to draw from the
    ///   thread-local RNG. It is a trait object so the trait stays
    ///   dyn-compatible.
    ///
    /// # Returns
    ///
    /// * `Result<Decimal, PricingError>` - A result containing the calculated option price
    ///   as a Decimal value, or a boxed error if the calculation failed.
    ///
    /// # Errors
    ///
    /// Propagates any `PricingError` returned by the `telegraph` pricing
    /// kernel (wrapped as `OptionsError::PricingError`), typically
    /// `PricingError::ExpirationDate`, `PricingError::NonFinite` or
    /// `PricingError::MethodError` when a simulated quantity is not
    /// representable.
    fn calculate_price_telegraph(
        &self,
        no_steps: NonZeroUsize,
        volatility: RegimeVolatility,
        rng: &mut dyn Rng,
    ) -> OptionsResult<Decimal>;

    /// Calculates the time value component of an option's price.
    ///
    /// Time value represents the portion of an option's premium that exceeds its intrinsic value.
    /// It reflects the market's expectation that the option may become more valuable before expiration
    /// due to potential favorable movements in the underlying asset price.
    ///
    /// The calculation uses the Black-Scholes model to determine the total option price,
    /// then subtracts the intrinsic value to find the time value component.
    ///
    /// # Returns
    /// - `Ok(Decimal)` containing the time value (never negative, minimum value is zero)
    /// - `Err` if the price calculation encounters an error
    ///
    /// # Errors
    ///
    /// Propagates any `OptionsError` returned by
    /// [`OptionPricing::calculate_price_black_scholes`] or
    /// [`Options::intrinsic_value`] (typically `OptionsError::PricingError`
    /// with `PricingError::ExpirationDate` as the inner cause).
    fn time_value(&self) -> OptionsResult<Decimal>;

    /// Estimates the implied volatility of an option from its market price
    /// using binary search.
    ///
    /// Implied volatility is a key metric in options trading that reflects
    /// the market's view of the expected volatility of the underlying asset.
    ///
    /// ### Parameters:
    ///
    /// - `market_price`: The market price of the option as a `Decimal`. This represents the cost
    ///   at which the option is traded in the market.
    ///
    /// ### Returns:
    ///
    /// - `Ok(Positive)`: A `Positive` value representing the calculated implied volatility as a percentage.
    /// - `Err(VolatilityError)`: An error indicating the reason calculation failed, such as:
    ///     - No convergence within the maximum number of iterations.
    ///     - Invalid option parameters.
    ///
    /// ### Implementation Details:
    ///
    /// - **Binary Search**: The function uses a binary search approach to iteratively find
    ///   the implied volatility (`volatility`) that narrows the difference between the calculated
    ///   option price (via Black-Scholes) and the target `market_price`.
    ///
    /// - **Short Options Adjustment**: For short options, the market price is inverted (negated),
    ///   and this adjustment ensures proper calculation of implied volatility.
    ///
    /// - **Solver**: Newton's method on the Black–Scholes vega, kept inside the bracket
    ///   `[MIN_VOLATILITY, 5]` (500 % per year) with a bisection fallback, started from the
    ///   Brenner–Subrahmanyam estimate (#859 P4). It stops when a step moves the volatility by
    ///   at most `1e-13` relative, so the result reproduces the target to the precision of
    ///   the prices rather than to the `1e-5` price tolerance of the bisection it replaced.
    ///
    /// - **Floor**: a target at or below the price at `MIN_VOLATILITY` returns `MIN_VOLATILITY`.
    ///
    /// - **No-arbitrage band**: a European target is first checked against the band of attainable
    ///   Black–Scholes prices (Hull, bounds on option prices); outside it no implied volatility
    ///   exists and the solver reports an error rather than an edge of its bracket.
    ///
    /// # Errors
    ///
    /// - [`VolatilityError::InvalidPrice`] when a European target lies
    ///   outside the no-arbitrage band `[max(S e^(-qT) - K e^(-rT), 0),
    ///   S e^(-qT)]` (call) or `[max(K e^(-rT) - S e^(-qT), 0), K e^(-rT)]`
    ///   (put), widened by `IV_TOLERANCE`: no volatility reproduces such a
    ///   price. `price` is the magnitude of `market_price`.
    /// - [`VolatilityError::NoConvergence`] when the target is inside the band
    ///   but above the price at the top of the bracket (`σ = 500 %`;
    ///   `iterations` is `0` and `last_volatility` the top), or when the
    ///   solver exhausts `MAX_ITERATIONS_IV` (1000) steps.
    /// - [`VolatilityError::DecimalError`] when a bracket or residual step
    ///   overflows `Decimal` (a target near `Decimal::MAX`).
    /// - [`VolatilityError::Options`] carrying [`OptionsError::TimeError`]
    ///   for an expired option: at `T = 0` the price is the intrinsic value
    ///   whatever the volatility, so no volatility is implied (#843).
    /// - [`VolatilityError::Options`] from the underlying Black–Scholes
    ///   evaluation or the band.
    fn calculate_implied_volatility(
        &self,
        market_price: Decimal,
    ) -> Result<Positive, VolatilityError>;
}

impl OptionPricing for Options {
    fn calculate_price_binomial(&self, no_steps: NonZeroUsize) -> OptionsResult<Decimal> {
        let expiry = self.time_to_expiration()?;
        let cpb = price_binomial(BinomialPricingParams {
            asset: self.underlying_price,
            volatility: self.implied_volatility,
            int_rate: self.risk_free_rate,
            strike: self.strike_price,
            expiry,
            no_steps,
            option_type: &self.option_type,
            option_style: &self.option_style,
            side: &self.side,
        })?;
        Ok(cpb)
    }

    fn calculate_price_binomial_tree(&self, no_steps: NonZeroUsize) -> PriceBinomialTree {
        let expiry = self.time_to_expiration()?;
        let params = BinomialPricingParams {
            asset: self.underlying_price,
            volatility: self.implied_volatility,
            int_rate: self.risk_free_rate,
            strike: self.strike_price,
            expiry,
            no_steps,
            option_type: &self.option_type,
            option_style: &self.option_style,
            side: &self.side,
        };
        let (asset_tree, option_tree) = generate_binomial_tree(&params)?;
        // The tree is already signed by `side` (#648); negating its root
        // again priced a short option at the long price.
        let price = option_tree
            .first()
            .and_then(|row| row.first())
            .copied()
            .ok_or(PricingError::BinomialNodeMissing {
                node: "option[0][0]",
            })?;
        Ok((price, asset_tree, option_tree))
    }

    fn calculate_price_black_scholes(&self) -> OptionsResult<Decimal> {
        Ok(black_scholes(self)?)
    }

    fn calculate_price_montecarlo(&self, prices: &[Positive]) -> OptionsResult<Positive> {
        Ok(price_option_monte_carlo(self, prices)?)
    }

    fn calculate_price_telegraph(
        &self,
        no_steps: NonZeroUsize,
        volatility: RegimeVolatility,
        rng: &mut dyn Rng,
    ) -> OptionsResult<Decimal> {
        Ok(telegraph(
            self,
            no_steps,
            TELEGRAPH_PATHS,
            None,
            None,
            volatility,
            rng,
        )?)
    }

    fn time_value(&self) -> OptionsResult<Decimal> {
        let option_price = OptionPricing::calculate_price_black_scholes(self)?.abs();
        let intrinsic_value = self.intrinsic_value(self.underlying_price)?;
        // `Decimal`'s `-` panics on overflow, which a price near the top of
        // the range against a negative intrinsic value reaches.
        let time_value = d_sub(option_price, intrinsic_value, "model::option::time_value")?;
        Ok(time_value.max(Decimal::ZERO))
    }

    fn calculate_implied_volatility(
        &self,
        market_price: Decimal,
    ) -> Result<Positive, VolatilityError> {
        // At expiry the price is the intrinsic value for every volatility
        // (#843), so a market price implies none. Rejected up front, as the
        // Black-Scholes error at `T = 0` used to do inside the bisection.
        if self.time_to_expiration()?.is_zero() {
            return Err(OptionsError::TimeError {
                operation: "calculate_implied_volatility".to_string(),
                reason:
                    "the option has expired: at T = 0 the price does not depend on the volatility"
                        .to_string(),
            }
            .into());
        }

        let is_short = self.is_short();
        let target_price = if is_short {
            -market_price
        } else {
            market_price
        };

        // A European target outside the no-arbitrage band has no implied
        // volatility (#652); without this check the bisection collapses on
        // an edge of its bracket and reports that edge as the answer.
        if matches!(self.option_type, OptionType::European) {
            let (lower, upper) = european_price_band(self).map_err(OptionsError::from)?;
            let below = target_price < d_sub(lower, IV_TOLERANCE, "pricing::iv::band::lower")?;
            let above = target_price > d_add(upper, IV_TOLERANCE, "pricing::iv::band::upper")?;
            if below || above {
                return Err(outside_band_error(market_price, target_price, lower, upper));
            }
        }

        // The shared solver of #859 P4 on one long unit; the short sign
        // convention lives in `target_price`.
        let guess = iv_initial_guess(self, target_price).unwrap_or(IV_BRACKET_MAX);
        let outcome = solve_implied_volatility(
            *MIN_VOLATILITY,
            IV_BRACKET_MAX,
            guess,
            MAX_ITERATIONS_IV,
            |sigma, with_slope| long_residual(self, target_price, sigma, with_slope),
        )?;
        match outcome {
            IvOutcome::Found(volatility) => Ok(volatility),
            // The target prices at or below the volatility floor: the
            // bisection this replaced converged on the bottom of its
            // bracket, and the floor is that bottom.
            IvOutcome::BelowBracket => Ok(*MIN_VOLATILITY),
            IvOutcome::AboveBracket => Err(VolatilityError::NoConvergence {
                iterations: 0,
                last_volatility: IV_BRACKET_MAX,
            }),
            IvOutcome::NoConvergence(last_volatility) => Err(VolatilityError::NoConvergence {
                iterations: MAX_ITERATIONS_IV,
                last_volatility,
            }),
        }
    }
}

/// Builds the error for a target outside the no-arbitrage band.
///
/// `price` carries the magnitude of the quoted `market_price` (a short
/// position quotes it negative); the reason names the signed long-equivalent
/// target and the band it missed.
#[cold]
#[inline(never)]
fn outside_band_error(
    market_price: Decimal,
    target_price: Decimal,
    lower: Decimal,
    upper: Decimal,
) -> VolatilityError {
    match Positive::new_decimal(market_price.abs()) {
        Ok(price) => VolatilityError::InvalidPrice {
            price,
            reason: format!(
                "target {target_price} is outside the no-arbitrage band [{lower}, {upper}], so no implied volatility exists"
            ),
        },
        Err(e) => VolatilityError::PositiveError(e),
    }
}

#[cfg(test)]
mod tests_option_pricing_trait {
    use super::*;
    use optionstratlib_core::model::types::{OptionStyle, Side};
    use optionstratlib_core::model::utils::create_sample_option_simplest;
    use optionstratlib_core::model::{ExpirationDate, OptionType};
    use optionstratlib_core::pos_or_panic;
    use rust_decimal_macros::dec;

    fn sample() -> Options {
        Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            pos_or_panic!(100.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.2),
            Positive::ONE,
            pos_or_panic!(100.0),
            dec!(0.05),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        )
    }

    #[test]
    fn test_option_pricing_trait_matches_inherent_black_scholes() {
        let option = sample();
        let via_trait = OptionPricing::calculate_price_black_scholes(&option);
        let via_inherent = Options::calculate_price_black_scholes(&option);
        assert_eq!(via_trait.ok(), via_inherent.ok());
    }

    #[test]
    fn test_option_pricing_trait_matches_inherent_binomial() {
        let option = sample();
        let steps = NonZeroUsize::new(50).expect("non-zero");
        let via_trait = OptionPricing::calculate_price_binomial(&option, steps);
        let via_inherent = Options::calculate_price_binomial(&option, steps);
        assert_eq!(via_trait.ok(), via_inherent.ok());
    }

    #[test]
    fn test_option_pricing_trait_matches_inherent_time_value() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let via_trait = OptionPricing::time_value(&option);
        let via_inherent = Options::time_value(&option);
        assert_eq!(via_trait.ok(), via_inherent.ok());
    }

    #[test]
    fn test_option_pricing_trait_matches_inherent_implied_volatility() {
        let option = sample();
        let market_price = dec!(3.0);
        let via_trait = OptionPricing::calculate_implied_volatility(&option, market_price);
        let via_inherent = Options::calculate_implied_volatility(&option, market_price);
        assert_eq!(via_trait.ok(), via_inherent.ok());
    }
}

#[cfg(test)]
mod tests_options_pricing {
    use super::*;
    use optionstratlib_core::model::types::{OptionStyle, OptionType, Side};
    use optionstratlib_core::model::utils::create_sample_option_simplest;
    use optionstratlib_core::model::{ExpirationDate, Options};
    use optionstratlib_core::{model::Positive, pos_or_panic};
    use rust_decimal::Decimal;

    use rust_decimal_macros::dec;

    #[test]
    fn test_calculate_price_binomial() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let price = option
            .calculate_price_binomial(optionstratlib_core::nz!(100))
            .unwrap();
        assert!(price > Decimal::ZERO);
    }

    #[test]
    fn test_calculate_price_binomial_tree() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let (price, asset_tree, option_tree) = option
            .calculate_price_binomial_tree(optionstratlib_core::nz!(5))
            .unwrap();
        assert!(price > Decimal::ZERO);
        assert_eq!(asset_tree.len(), 6);
        assert_eq!(option_tree.len(), 6);
    }

    #[test]
    fn test_calculate_price_binomial_tree_short() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Short);
        let (price, asset_tree, option_tree) = option
            .calculate_price_binomial_tree(optionstratlib_core::nz!(5))
            .unwrap();
        // A short position is a liability: the negated long price (#648). It
        // used to come back positive, the root negated twice.
        let long = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let (long_price, _, _) = long
            .calculate_price_binomial_tree(optionstratlib_core::nz!(5))
            .unwrap();
        assert!(price < Decimal::ZERO);
        assert_eq!(price, -long_price);
        assert_eq!(asset_tree.len(), 6);
        assert_eq!(option_tree.len(), 6);
    }

    #[test]
    fn test_calculate_price_black_scholes() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let price = option.calculate_price_black_scholes().unwrap();
        assert!(price > Decimal::ZERO);
    }

    #[test]
    fn test_calculate_time_value() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "AAPL".to_string(),
            Positive::HUNDRED,
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.2),
            Positive::ONE,
            pos_or_panic!(105.0),
            dec!(0.05),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );

        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value < option.calculate_price_black_scholes().unwrap());
    }
}

#[cfg(test)]
mod tests_time_value {
    use super::*;
    use optionstratlib_core::model::types::{OptionStyle, Side};
    use optionstratlib_core::model::utils::create_sample_option_simplest_strike;
    use optionstratlib_core::{model::Positive, pos_or_panic};
    use rust_decimal::Decimal;

    use optionstratlib_core::assert_decimal_eq;
    use rust_decimal_macros::dec;
    use tracing::debug;

    #[test]
    fn test_calculate_time_value_long_call() {
        let option = create_sample_option_simplest_strike(
            Side::Long,
            OptionStyle::Call,
            pos_or_panic!(105.0),
        );
        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value <= option.calculate_price_black_scholes().unwrap());
    }

    #[test]
    fn test_calculate_time_value_short_call() {
        let option = create_sample_option_simplest_strike(
            Side::Short,
            OptionStyle::Call,
            pos_or_panic!(105.0),
        );
        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value <= option.calculate_price_black_scholes().unwrap().abs());
    }

    #[test]
    fn test_calculate_time_value_long_put() {
        let option =
            create_sample_option_simplest_strike(Side::Long, OptionStyle::Put, pos_or_panic!(95.0));
        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value <= option.calculate_price_black_scholes().unwrap());
    }

    #[test]
    fn test_calculate_time_value_short_put() {
        let option = create_sample_option_simplest_strike(
            Side::Short,
            OptionStyle::Put,
            pos_or_panic!(95.0),
        );
        let time_value = option.time_value().unwrap();
        assert!(time_value > Decimal::ZERO);
        assert!(time_value <= option.calculate_price_black_scholes().unwrap().abs());
    }

    #[test]
    fn test_calculate_time_value_at_the_money() {
        let call =
            create_sample_option_simplest_strike(Side::Long, OptionStyle::Call, Positive::HUNDRED);
        let put =
            create_sample_option_simplest_strike(Side::Long, OptionStyle::Put, Positive::HUNDRED);

        let call_time_value = call.time_value().unwrap();
        let put_time_value = put.time_value().unwrap();

        assert!(call_time_value > Decimal::ZERO);
        assert!(put_time_value > Decimal::ZERO);
        assert_eq!(
            call_time_value,
            call.calculate_price_black_scholes().unwrap()
        );
        assert_eq!(put_time_value, put.calculate_price_black_scholes().unwrap());
    }

    #[test]
    fn test_calculate_time_value_deep_in_the_money() {
        let call = create_sample_option_simplest_strike(
            Side::Long,
            OptionStyle::Call,
            pos_or_panic!(150.0),
        );
        let put =
            create_sample_option_simplest_strike(Side::Long, OptionStyle::Put, pos_or_panic!(50.0));

        let call_time_value = call.time_value().unwrap();
        let put_time_value = put.time_value().unwrap();

        let call_price = call.calculate_price_black_scholes().unwrap();
        let put_price = put.calculate_price_black_scholes().unwrap();

        assert_decimal_eq!(call_time_value, call_price, dec!(0.01));
        assert_decimal_eq!(put_time_value, put_price, dec!(0.01));
        debug!("Call time value: {}", call_time_value);
        debug!("Call BS price: {}", call_price);
        debug!("Put time value: {}", put_time_value);
        debug!("Put BS price: {}", put_price);
        assert!(call_time_value <= call_price);
        assert!(put_time_value <= put_price);
    }
}

#[cfg(test)]
mod tests_calculate_price_binomial {
    use super::*;
    use optionstratlib_core::model::types::{OptionStyle, OptionType, Side};
    use optionstratlib_core::model::utils::{
        create_sample_option, create_sample_option_simplest, create_sample_option_with_date,
    };
    use optionstratlib_core::model::{ExpirationDate, Options};
    use optionstratlib_core::{model::Positive, pos_or_panic};
    use rust_decimal::Decimal;

    use chrono::Utc;
    use rust_decimal_macros::dec;
    use std::str::FromStr;

    #[test]
    fn test_european_call_option_basic() {
        // Test a basic European call option with standard parameters
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let result = option.calculate_price_binomial(optionstratlib_core::nz!(100));
        assert!(result.is_ok());
        let price = result.unwrap();
        // Price should be positive for a long call at-the-money
        assert!(price > Decimal::ZERO);
    }

    #[test]
    fn test_american_put_option() {
        // Test American put option which should have early exercise value
        let option = Options::new(
            OptionType::American,
            Side::Long,
            "TEST".to_string(),
            Positive::HUNDRED,
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.2),  // volatility
            Positive::ONE,       // quantity
            pos_or_panic!(95.0), // underlying price (slightly ITM for put)
            dec!(0.05),          // risk-free rate
            OptionStyle::Put,
            Positive::ZERO, // dividend yield
            None,
        );

        let result = option.calculate_price_binomial(optionstratlib_core::nz!(100));
        assert!(result.is_ok());
        let price = result.unwrap();
        // Price should be positive and reflect early exercise premium
        assert!(price > Decimal::ZERO);
    }

    #[test]
    fn test_zero_volatility() {
        let mut option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        option.implied_volatility = Positive::ZERO;
        let result = option.calculate_price_binomial(optionstratlib_core::nz!(100));
        assert!(result.is_ok());
        // With zero volatility, price should equal discounted intrinsic value
    }

    #[test]
    fn test_zero_time_to_expiry() {
        // Test option at expiration
        let now = Utc::now().naive_utc();
        let option = create_sample_option_with_date(
            OptionStyle::Call,
            Side::Long,
            Positive::HUNDRED,
            Positive::ONE,
            pos_or_panic!(95.0),
            pos_or_panic!(0.2),
            now,
        );

        let result = option.calculate_price_binomial(optionstratlib_core::nz!(100));
        assert!(result.is_ok());
        let price = result.unwrap();
        // At expiry, price should equal intrinsic value
        assert_eq!(price, Decimal::from(5));
    }

    // The former `test_invalid_steps` test used to pass `0` to
    // `calculate_price_binomial` and assert that the runtime guard
    // returned `InvalidStepCount`. After #337 the signature is
    // `NonZeroUsize`, so the invariant is enforced at the type level
    // and the test is now obsolete (cannot construct the invalid
    // input).

    #[test]
    fn test_deep_itm_call() {
        let option = create_sample_option(
            OptionStyle::Call,
            Side::Long,
            pos_or_panic!(150.0), // Underlying price much higher than strike
            Positive::ONE,
            Positive::HUNDRED,
            pos_or_panic!(0.2),
        );

        let result = option.calculate_price_binomial(optionstratlib_core::nz!(100));
        assert!(result.is_ok());
        let price = result.unwrap();
        // Price should be close to intrinsic value for deep ITM
        assert!(price > Decimal::from(45)); // At least intrinsic - some time value
    }

    #[test]
    fn test_deep_otm_put() {
        let option = create_sample_option(
            OptionStyle::Put,
            Side::Long,
            pos_or_panic!(150.0), // Underlying price much higher than strike
            Positive::ONE,
            Positive::HUNDRED,
            pos_or_panic!(0.2),
        );

        let result = option.calculate_price_binomial(optionstratlib_core::nz!(100));
        assert!(result.is_ok());
        let price = result.unwrap();
        // Price should be very small for deep OTM
        assert!(price < Decimal::from(1));
    }

    #[test]
    fn test_convergence() {
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);

        // Test that increasing steps leads to convergence
        let price_100 = option
            .calculate_price_binomial(optionstratlib_core::nz!(100))
            .unwrap();
        let price_1000 = option
            .calculate_price_binomial(optionstratlib_core::nz!(1000))
            .unwrap();

        // Prices should be close to each other
        let diff = (price_1000 - price_100).abs();
        assert!(diff < Decimal::from_str("0.1").unwrap());
    }

    #[test]
    fn test_short_position() {
        let long_call_option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let mut short_call_option = long_call_option.clone();
        short_call_option.side = Side::Short;
        let mut short_put_option = short_call_option.clone();
        short_put_option.option_style = OptionStyle::Put;
        let mut long_put_option = short_put_option.clone();
        long_put_option.side = Side::Long;

        let long_call_price = long_call_option
            .calculate_price_binomial(optionstratlib_core::nz!(100))
            .unwrap();
        let short_call_price = short_call_option
            .calculate_price_binomial(optionstratlib_core::nz!(100))
            .unwrap();
        let long_put_price = long_put_option
            .calculate_price_binomial(optionstratlib_core::nz!(100))
            .unwrap();
        let short_put_price = short_put_option
            .calculate_price_binomial(optionstratlib_core::nz!(100))
            .unwrap();

        // Short position should be negative of long position
        assert_eq!(long_call_price, -short_call_price);
        assert_eq!(long_put_price, -short_put_price);
    }
}

#[cfg(test)]
mod tests_options_black_scholes {
    use super::*;
    use optionstratlib_core::assert_decimal_eq;
    use optionstratlib_core::model::types::{OptionStyle, OptionType, Side};
    use optionstratlib_core::model::{ExpirationDate, Options};
    use optionstratlib_core::{model::Positive, pos_or_panic};
    use rust_decimal_macros::dec;

    #[test]
    fn test_new_option_call() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "SP500".to_string(),
            pos_or_panic!(5790.0),
            ExpirationDate::Days(pos_or_panic!(18.0)),
            pos_or_panic!(0.1117),
            Positive::ONE,
            pos_or_panic!(5781.88),
            dec!(0.05),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            pos_or_panic!(60.306_765_882_668_3),
            dec!(1e-8)
        );
    }

    #[test]
    fn test_new_option_call_bis() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "SP500".to_string(),
            pos_or_panic!(6050.0),
            ExpirationDate::Days(pos_or_panic!(61.2)),
            pos_or_panic!(0.12594),
            Positive::ONE,
            pos_or_panic!(6032.18),
            dec!(0.0),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            pos_or_panic!(115.56),
            dec!(1e-2)
        );
    }

    #[test]
    fn test_new_option_put() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "SP500".to_string(),
            pos_or_panic!(6050.0),
            ExpirationDate::Days(pos_or_panic!(61.2)),
            pos_or_panic!(0.1258),
            Positive::ONE,
            pos_or_panic!(6032.18),
            dec!(0.0),
            OptionStyle::Put,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            pos_or_panic!(133.25),
            dec!(1e-2)
        );
    }

    #[test]
    fn test_new_option_call_short() {
        let option = Options::new(
            OptionType::European,
            Side::Short,
            "SP500".to_string(),
            pos_or_panic!(6050.0),
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.12594),
            Positive::ONE,
            pos_or_panic!(6032.18),
            dec!(0.0),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            dec!(-114.34),
            dec!(1e-2)
        );
    }

    #[test]
    fn test_new_option_put_short() {
        let option = Options::new(
            OptionType::European,
            Side::Short,
            "SP500".to_string(),
            pos_or_panic!(6050.0),
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.12594),
            Positive::ONE,
            pos_or_panic!(6032.18),
            dec!(0.0),
            OptionStyle::Put,
            Positive::ZERO,
            None,
        );
        assert_decimal_eq!(
            option.calculate_price_black_scholes().unwrap(),
            dec!(-132.16),
            dec!(1e-2)
        );
    }
}

#[cfg(test)]
mod tests_calculate_implied_volatility {
    use super::*;
    use crate::error::VolatilityError;
    use optionstratlib_core::assert_pos_relative_eq;
    use optionstratlib_core::model::types::{OptionStyle, OptionType, Side};
    use optionstratlib_core::model::{ExpirationDate, Options};
    use optionstratlib_core::{model::Positive, pos_or_panic};
    use rust_decimal::Decimal;
    use rust_decimal_macros::dec;

    /// The option at `iv` prices `market_price` (signed by side) to `1e-12`
    /// relative.
    fn assert_reprices(option: &Options, iv: Positive, market_price: Decimal) {
        let mut repriced = option.clone();
        repriced.implied_volatility = iv;
        let price = repriced.calculate_price_black_scholes().unwrap();
        let error = ((price - market_price) / market_price).abs();
        assert!(
            error <= dec!(1e-12),
            "repriced {price} vs {market_price}: {error}"
        );
    }

    #[test]
    fn test_implied_volatility_call() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            pos_or_panic!(5790.0), // strike
            ExpirationDate::Days(pos_or_panic!(18.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(5781.88), // underlying
            dec!(0.05),             // rate
            OptionStyle::Call,
            Positive::ZERO, // div
            None,
        );

        let market_price = dec!(60.30);
        let iv = option.calculate_implied_volatility(market_price).unwrap();

        // The bisection replaced in #859 P4 stopped at a `1e-5` price
        // tolerance and was pinned at 0.111618041; the solver now returns the
        // volatility that reprices the target to `1e-12` relative.
        assert_reprices(&option, iv, market_price);
        assert_pos_relative_eq!(iv, pos_or_panic!(0.111618041), pos_or_panic!(1e-3));
    }

    #[test]
    fn test_implied_volatility_put() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            pos_or_panic!(6050.0), // strike
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(6032.18), // underlying
            dec!(0.0),              // rate
            OptionStyle::Put,
            Positive::ZERO, // div
            None,
        );

        let market_price = dec!(132.16);
        let iv = option.calculate_implied_volatility(market_price).unwrap();
        // The bisection replaced in #859 P4 stopped at a `1e-5` price
        // tolerance and was pinned at 0.125961; the solver now returns the
        // volatility that reprices the target to `1e-12` relative.
        assert_reprices(&option, iv, market_price);
        assert_pos_relative_eq!(iv, pos_or_panic!(0.125961), pos_or_panic!(1e-3));
    }

    #[test]
    fn test_implied_volatility_call_short() {
        let option = Options::new(
            OptionType::European,
            Side::Short,
            "TEST".to_string(),
            pos_or_panic!(6050.0), // strike
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(6032.18), // underlying
            dec!(0.0),              // rate
            OptionStyle::Call,
            Positive::ZERO, // div
            None,
        );

        let market_price = dec!(-114.16);
        let iv = option.calculate_implied_volatility(market_price).unwrap();

        // The bisection replaced in #859 P4 stopped at a `1e-5` price
        // tolerance and was pinned at 0.1258087; the solver now returns the
        // volatility that reprices the target to `1e-12` relative.
        assert_reprices(&option, iv, market_price);
        assert_pos_relative_eq!(iv, pos_or_panic!(0.1258087), pos_or_panic!(1e-3));
    }

    #[test]
    fn test_implied_volatility_put_short() {
        let option = Options::new(
            OptionType::European,
            Side::Short,
            "TEST".to_string(),
            pos_or_panic!(6050.0), // strike
            ExpirationDate::Days(pos_or_panic!(60.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(6032.18), // underlying
            dec!(0.0),              // rate
            OptionStyle::Put,
            Positive::ZERO, // div
            None,
        );

        let market_price = dec!(-132.27);
        let iv = option.calculate_implied_volatility(market_price).unwrap();
        // The bisection replaced in #859 P4 stopped at a `1e-5` price
        // tolerance and was pinned at 0.12611389; the solver now returns the
        // volatility that reprices the target to `1e-12` relative.
        assert_reprices(&option, iv, market_price);
        assert_pos_relative_eq!(iv, pos_or_panic!(0.12611389), pos_or_panic!(1e-3));
    }

    #[test]
    fn test_invalid_market_price() {
        let option = Options::default();
        let result = option.calculate_implied_volatility(Decimal::ZERO);
        assert!(matches!(result, Err(VolatilityError::Options(_))));
    }

    #[test]
    fn test_expired_option() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            Positive::HUNDRED,
            ExpirationDate::Days(Positive::ZERO),
            pos_or_panic!(0.2),
            Positive::ONE,
            Positive::HUNDRED,
            dec!(0.05),
            OptionStyle::Call,
            Positive::ZERO,
            None,
        );

        let result = option.calculate_implied_volatility(dec!(2.5));
        assert!(matches!(result, Err(VolatilityError::Options(_))));
    }

    #[test]
    fn test_convergence_edge_cases() {
        let option = Options::new(
            OptionType::European,
            Side::Long,
            "TEST".to_string(),
            pos_or_panic!(5790.0), // strike
            ExpirationDate::Days(pos_or_panic!(18.0)),
            pos_or_panic!(0.1),     // initial iv
            Positive::ONE,          // qty
            pos_or_panic!(5781.88), // underlying
            dec!(0.05),             // rate
            OptionStyle::Call,
            Positive::ZERO, // div
            None,
        );

        // Test with small initial vol
        let iv = option.calculate_implied_volatility(dec!(60.30)).unwrap();
        assert_pos_relative_eq!(iv, pos_or_panic!(0.111328125), pos_or_panic!(0.01));

        // Test with large initial vol
        let iv = option.calculate_implied_volatility(dec!(60.30)).unwrap();
        assert_pos_relative_eq!(iv, pos_or_panic!(0.111328125), pos_or_panic!(0.01));
    }
}