optionstratlib 0.17.3

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
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
// Scoped allow: bulk migration of unchecked `[]` indexing to
// `.get().ok_or_else(..)` tracked as follow-ups to #341. The existing
// call sites are internal to this file and audited for invariant-bound
// indices (fixed-length buffers, just-pushed slices, etc.).
#![allow(clippy::indexing_slicing)]

use crate::error::PricingError;
use crate::model::types::{OptionStyle, OptionType, Side};
use crate::pricing::payoff::{Payoff, PayoffInfo};
use crate::pricing::utils::*;
use crate::{d2f, f2d};
use positive::Positive;
use rust_decimal::{Decimal, MathematicalOps};
use std::num::NonZeroUsize;
use tracing::instrument;

#[cfg(test)]
use positive::pos_or_panic;

type BinomialTreeResult = Result<(Vec<Vec<Decimal>>, Vec<Vec<Decimal>>), PricingError>;

/// Parameters for pricing options using the Binomial Tree model.
///
/// This structure encapsulates all the necessary parameters required to calculate
/// the price of an option using the binomial pricing model. The binomial model is
/// a discrete-time, lattice-based approach to option pricing that can handle various
/// option types and styles.
///
/// The model builds a tree of possible future asset prices to determine the option's
/// value at each node, working backwards from expiration to the present value.
/// This approach is particularly valuable for American options or other early-exercise
/// scenarios.
#[derive(Debug, Clone)]
pub struct BinomialPricingParams<'a> {
    /// The current price of the underlying asset, represented as a positive value.
    pub asset: Positive,

    /// The volatility of the underlying asset, expressed as a positive value.
    /// This represents the standard deviation of the asset's returns.
    pub volatility: Positive,

    /// The risk-free interest rate used in the pricing model.
    pub int_rate: Decimal,

    /// The strike price of the option, represented as a positive value.
    pub strike: Positive,

    /// The time to expiration of the option in years, represented as a positive value.
    pub expiry: Positive,

    /// The number of steps to use in the binomial tree calculation,
    /// as a [`NonZeroUsize`] so zero is structurally invalid at the
    /// type level. Higher values increase accuracy but also
    /// computational cost. See
    /// [`crate::constants::DEFAULT_BINOMIAL_STEPS`] for a sensible
    /// default.
    pub no_steps: NonZeroUsize,

    /// The type of option (European, American, etc.) which determines
    /// when the option can be exercised.
    pub option_type: &'a OptionType,

    /// The style of the option (Call or Put) which determines whether the option
    /// gives the right to buy or sell the underlying asset.
    pub option_style: &'a OptionStyle,

    /// Indicates whether the option position is long (buying the option) or
    /// short (selling/writing the option).
    pub side: &'a Side,
}

/// Calculates the price of an option using the binomial model.
///
/// This function implements the binomial model for option pricing,
/// which is a numerical method for estimating the price of both European and American options.
/// The model constructs a binomial tree of possible future underlying asset prices
/// and then recursively calculates the option value from the leaves to the root of the tree.
///
/// # Arguments
///
/// * `params` - A `BinomialPricingParams` struct containing all necessary pricing parameters:
///     - `asset`: Current price of the underlying asset.
///     - `volatility`: Annualized volatility of the underlying asset.
///     - `int_rate`: Annualized risk-free interest rate.
///     - `strike`: Strike price of the option.
///     - `expiry`: Time to expiration in years.
///     - `no_steps`: Number of steps in the binomial tree.
///     - `option_type`: Type of option (e.g., European, American).
///     - `option_style`: Style of the option (Call or Put).
///     - `side`: Side of the trade (Long or Short).
///
/// # Returns
///
/// Returns the calculated price of the option as an `f64`.
///
/// # Special cases
///
/// - If `expiry` is 0, the function returns the intrinsic value of the option.
/// - If `volatility` is 0, the function calculates the option price deterministically.
///
/// # Notes
///
/// - The model's accuracy increases with the number of steps, but so does the computation time.
/// - This model assumes that the underlying asset follows a multiplicative binomial process.
/// - For American options, this model accounts for the possibility of early exercise.
///
/// # Errors
///
/// Returns [`PricingError::SqrtFailure`] when the up-factor exponent
/// produces an invalid `Decimal`, [`PricingError::BinomialNodeMissing`]
/// when the induction step cannot read an intermediate node, and
/// [`PricingError::Positive`] when any `Positive` construction
/// downstream (e.g. strike × discount factor) underflows below zero.
#[instrument(skip(params), fields(
    strike = %params.strike,
    asset = %params.asset,
    steps = params.no_steps.get(),
    style = ?*params.option_style,
    side = ?*params.side,
))]
pub fn price_binomial(params: BinomialPricingParams) -> Result<Decimal, PricingError> {
    let mut info = PayoffInfo {
        spot: params.asset,
        strike: params.strike,
        style: *params.option_style,
        side: *params.side,
        spot_prices: None,
        spot_min: None,
        spot_max: None,
    };

    if params.expiry == Decimal::ZERO {
        let intrinsic_value = f2d!(params.option_type.payoff(&info));
        return Ok(intrinsic_value);
    }
    if params.volatility == Decimal::ZERO {
        return calculate_discounted_payoff(params);
    }

    let no_steps_raw = params.no_steps.get();
    let dt = (params.expiry / Positive::new(no_steps_raw as f64)?).to_dec();
    let u = calculate_up_factor(params.volatility, dt)?;
    let d = calculate_down_factor(params.volatility, dt)?;
    let p = calculate_probability(params.int_rate, dt, d, u)?;
    let discount_factor = calculate_discount_factor(params.int_rate, dt)?;

    let mut prices: Vec<Decimal> = (0..=no_steps_raw)
        .map(|i| calculate_option_price(params.clone(), u, d, i))
        .collect::<Result<Vec<_>, _>>()?;

    for step in (0..no_steps_raw).rev() {
        for i in 0..=step {
            let option_value = option_node_value(p, prices[i + 1], prices[i], discount_factor)?;
            match params.option_type {
                OptionType::American => {
                    let spot = params.asset * u.powi(i as i64) * d.powi((step - i) as i64);
                    info.spot = spot;
                    let intrinsic_value = f2d!(params.option_type.payoff(&info));
                    prices[i] = option_value.max(intrinsic_value);
                }
                OptionType::Bermuda { exercise_dates } => {
                    // Calculate time at this step
                    let time_at_step = dt * Decimal::from(step as u32);
                    // Check if this step is an exercise date
                    let is_exercise_date = exercise_dates.iter().any(|&t| {
                        let t_dec = Decimal::try_from(t).unwrap_or(Decimal::ZERO);
                        (time_at_step - t_dec).abs() < dt / Decimal::TWO
                    });
                    if is_exercise_date {
                        let spot = params.asset * u.powi(i as i64) * d.powi((step - i) as i64);
                        info.spot = spot;
                        let intrinsic_value = f2d!(params.option_type.payoff(&info));
                        prices[i] = option_value.max(intrinsic_value);
                    } else {
                        prices[i] = option_value;
                    }
                }
                OptionType::European => {
                    prices[i] = option_value;
                }
                _ => {
                    return Err(PricingError::other(
                        "OptionType not supported for binomial pricing",
                    ));
                }
            }
        }
    }
    Ok(prices[0])
}

/// Generates a binomial tree for option pricing.
///
/// # Parameters
///
/// * `params`: A reference to `BinomialPricingParams` which contains the parameters required for
///   generating the binomial tree including expiration time, number of steps, volatility, interest rate,
///   asset price, strike price, option type, and option style.
///
/// # Returns
///
/// A tuple containing two vectors of vectors:
/// * `asset_tree`: The tree representing the possible future values of the asset at each step.
/// * `option_tree`: The tree representing the values of the option at each step.
///
/// The `generate_binomial_tree` function calculates the possible asset prices and option prices
/// at each node in a binomial tree based on the input parameters.
///
/// 1. It calculates the time interval `dt` for each step.
/// 2. `u` and `d` are the factors by which the price increases or decreases.
/// 3. `p` is the risk-neutral probability.
/// 4. It initializes the `asset_tree` and `option_tree` with the appropriate dimensions.
/// 5. The asset prices are computed for all nodes.
/// 6. The option values are computed at maturity based on the payoff function.
/// 7. The option values are then back-propagated to compute the option value at the current time.
///
/// # Example
///
/// ```rust
/// use rust_decimal::Decimal;
/// use rust_decimal_macros::dec;
/// use optionstratlib::model::types::{OptionStyle, OptionType, Side};
/// use optionstratlib::nz;
/// use positive::pos_or_panic;
/// use optionstratlib::pricing::binomial_model::{BinomialPricingParams, generate_binomial_tree};
/// use positive::Positive;
/// # fn run() -> Result<(), optionstratlib::error::Error> {
/// let params = BinomialPricingParams {
///             asset: Positive::HUNDRED,
///             volatility: pos_or_panic!(0.2),
///             int_rate: dec!(0.05),
///             strike: Positive::HUNDRED,
///             expiry: Positive::ONE,
///             no_steps: nz!(1000),
///             option_type: &OptionType::European,
///             option_style: &OptionStyle::Call,
///             side: &Side::Long,
///         };
/// let (asset_tree, option_tree) = generate_binomial_tree(&params)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Same failure surface as [`price_binomial`]:
/// [`PricingError::SqrtFailure`] when the up-factor exponent cannot
/// be represented, [`PricingError::BinomialNodeMissing`] when an
/// intermediate node of the lattice is unexpectedly absent, and
/// [`PricingError::Positive`] when a `Positive` construction
/// downstream underflows.
pub fn generate_binomial_tree(params: &BinomialPricingParams) -> BinomialTreeResult {
    let mut info = PayoffInfo {
        spot: params.asset,
        strike: params.strike,
        style: *params.option_style,
        side: *params.side,
        spot_prices: None,
        spot_min: None,
        spot_max: None,
    };

    let no_steps_raw = params.no_steps.get();
    let dt = (params.expiry / f2d!(no_steps_raw as f64)).to_dec();
    let up_factor = calculate_up_factor(params.volatility, dt)?;
    let down_factor = calculate_down_factor(params.volatility, dt)?;
    let probability = calculate_probability(params.int_rate, dt, down_factor, up_factor)?;
    let discount_factor = calculate_discount_factor(params.int_rate, dt)?;

    let mut asset_tree = vec![vec![Decimal::ZERO; no_steps_raw + 1]; no_steps_raw + 1];
    let mut option_tree = vec![vec![Decimal::ZERO; no_steps_raw + 1]; no_steps_raw + 1];

    for (step, step_vec) in asset_tree.iter_mut().enumerate() {
        for (node, node_val) in step_vec.iter_mut().enumerate().take(step + 1) {
            *node_val =
                up_factor.powi((step - node) as i64) * down_factor.powi(node as i64) * params.asset;
        }
    }

    for (node, node_val) in asset_tree[no_steps_raw]
        .iter()
        .enumerate()
        .take(no_steps_raw + 1)
    {
        info.spot = Positive::new_decimal(*node_val)?;
        option_tree[no_steps_raw][node] = f2d!(params.option_type.payoff(&info));
    }

    for step in (0..no_steps_raw).rev() {
        let (current_step_arr, next_step_arr) = option_tree.split_at_mut(step + 1);
        for (node_idx, node_val) in current_step_arr[step].iter_mut().enumerate().take(step + 1) {
            let node_value =
                option_node_value_wrapper(probability, next_step_arr, node_idx, discount_factor)?;
            match params.option_type {
                OptionType::European => {
                    *node_val = node_value;
                }
                OptionType::American => {
                    if (step == 0) & (node_idx == 0) {
                        *node_val = node_value;
                    } else {
                        info.spot = Positive::new_decimal(asset_tree[step][node_idx])?;
                        let intrinsic_value = params.option_type.payoff(&info);
                        let dec_node_val = d2f!(node_value);
                        *node_val = f2d!(intrinsic_value.max(dec_node_val));
                    }
                }
                OptionType::Bermuda { exercise_dates } => {
                    // Calculate time at this step
                    let time_at_step = dt * Decimal::from(step as u32);
                    // Check if this step is an exercise date
                    let is_exercise_date = exercise_dates.iter().any(|&t| {
                        let t_dec = Decimal::try_from(t).unwrap_or(Decimal::ZERO);
                        (time_at_step - t_dec).abs() < dt / Decimal::TWO
                    });
                    if is_exercise_date && !((step == 0) & (node_idx == 0)) {
                        info.spot = Positive::new_decimal(asset_tree[step][node_idx])?;
                        let intrinsic_value = params.option_type.payoff(&info);
                        let dec_node_val = d2f!(node_value);
                        *node_val = f2d!(intrinsic_value.max(dec_node_val));
                    } else {
                        *node_val = node_value;
                    }
                }
                _ => {
                    return Err(PricingError::other(
                        "OptionType not supported for binomial tree generation",
                    ));
                }
            }
        }
    }

    Ok((asset_tree, option_tree))
}

#[cfg(test)]
mod tests_price_binomial {
    use super::*;
    use crate::assert_decimal_eq;
    use crate::model::types::OptionType;
    use rust_decimal_macros::dec;

    const EPSILON: Decimal = dec!(1e-6);

    #[test]
    fn test_european_call_option() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            strike: Positive::HUNDRED,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.2),
            expiry: Positive::ONE,
            no_steps: crate::nz!(3),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert_decimal_eq!(price, dec!(11.0438708), EPSILON);
    }

    #[test]
    fn test_european_put_option() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: crate::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert_decimal_eq!(price, dec!(5.571526), EPSILON);
    }

    #[test]
    fn test_european_put_option_extended() {
        let params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::ONE,
            no_steps: crate::nz!(1),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert_decimal_eq!(price, dec!(4.446415), EPSILON);
    }

    #[test]
    fn test_short_option() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: crate::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let long_price = price_binomial(params.clone()).unwrap();
        let short_price = price_binomial(BinomialPricingParams {
            side: &Side::Short,
            ..params
        })
        .unwrap();
        assert_decimal_eq!(long_price, -short_price, EPSILON);
    }

    #[test]
    fn test_zero_volatility() {
        let asset = Positive::HUNDRED;
        let strike = Positive::HUNDRED;
        let int_rate = dec!(0.05);
        let expiry = Positive::ONE;

        let params = BinomialPricingParams {
            asset,
            volatility: Positive::ZERO,
            int_rate,
            strike,
            expiry,
            no_steps: crate::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();

        let exact_price = (asset * (int_rate * expiry).exp() - strike).max(Positive::ZERO)
            * (-int_rate * expiry).exp();

        assert_decimal_eq!(price, exact_price, EPSILON);
    }

    #[test]
    fn test_deep_in_the_money() {
        let params = BinomialPricingParams {
            asset: pos_or_panic!(150.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: crate::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert!(price > dec!(50.0));
    }

    #[test]
    fn test_deep_out_of_the_money() {
        let params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: crate::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert!(price < Decimal::ONE);
    }

    #[test]
    fn test_zero_time_to_expiry() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ZERO,
            no_steps: crate::nz!(1000),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert_decimal_eq!(price, Decimal::ZERO, EPSILON);
    }
}

#[cfg(test)]
mod tests_generate_binomial_tree {
    use super::*;
    use crate::assert_decimal_eq;
    use crate::model::types::OptionType;
    use rust_decimal_macros::dec;

    const EPSILON: Decimal = dec!(1e-5);

    #[test]
    fn test_binomial_tree_basic() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            strike: Positive::HUNDRED,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.2),
            expiry: Positive::ONE,
            no_steps: crate::nz!(3),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        // Check if the asset tree is generated correctly
        assert_eq!(asset_tree[0][0], dec!(100.0));
        assert_decimal_eq!(asset_tree[1][0], dec!(112.2400899), EPSILON);
        assert_decimal_eq!(asset_tree[3][1], dec!(112.2400899), EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(11.0438708), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(17.713887), EPSILON);
        assert_decimal_eq!(option_tree[1][1], dec!(3.500653), EPSILON);
        assert_decimal_eq!(option_tree[2][0], dec!(27.631232), EPSILON);
        assert_decimal_eq!(option_tree[2][1], dec!(6.5458625), EPSILON);
        assert_decimal_eq!(option_tree[2][2], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][0], dec!(41.398244), EPSILON);
        assert_decimal_eq!(option_tree[3][1], dec!(12.240089), EPSILON);
        assert_decimal_eq!(option_tree[3][2], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][3], Decimal::ZERO, EPSILON);
    }

    #[test]
    fn test_binomial_tree_put_option() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            strike: Positive::HUNDRED,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.2),
            expiry: Positive::ONE,
            no_steps: crate::nz!(3),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let (_, option_tree) = generate_binomial_tree(&params).unwrap();

        assert_decimal_eq!(option_tree[3][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][1], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][2], dec!(10.905274), EPSILON);
        assert_decimal_eq!(option_tree[3][3], dec!(29.277764), EPSILON);
    }

    #[test]
    fn test_binomial_tree_call_option_check() {
        let params = BinomialPricingParams {
            asset: pos_or_panic!(30.0),
            strike: pos_or_panic!(30.0),
            expiry: Positive::ONE,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.17),
            no_steps: crate::nz!(1),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        // Test asset tree
        assert_eq!(asset_tree.len(), 2);
        assert_decimal_eq!(asset_tree[0][0], dec!(30.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(35.559145), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(25.309944), EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(3.213401), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(5.559145), EPSILON);
        assert_decimal_eq!(option_tree[1][1], Decimal::ZERO, EPSILON);

        let params = BinomialPricingParams {
            asset: pos_or_panic!(30.0),
            strike: pos_or_panic!(30.0),
            expiry: Positive::ONE,
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.17),
            no_steps: crate::nz!(2),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        // Test asset tree
        assert_eq!(asset_tree.len(), 3);
        assert_decimal_eq!(asset_tree[0][0], dec!(30.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(33.831947), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(26.602075), EPSILON);
        assert_decimal_eq!(asset_tree[2][0], dec!(38.153354), EPSILON);
        assert_decimal_eq!(asset_tree[2][1], dec!(30.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][2], dec!(23.589013), EPSILON);

        assert_decimal_eq!(option_tree[0][0], dec!(2.564481), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(4.572649), EPSILON);
        assert_decimal_eq!(option_tree[1][1], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][0], dec!(8.153354), EPSILON);
        assert_decimal_eq!(option_tree[2][1], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][2], Decimal::ZERO, EPSILON);
    }

    #[test]
    fn test_binomial_tree_put_option_check() {
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            strike: pos_or_panic!(110.0),
            expiry: pos_or_panic!(3.0), // Assuming each time step is 1 unit of time
            int_rate: dec!(0.05),
            volatility: pos_or_panic!(0.09531018), // Calculated to match the 10% up/down movement
            no_steps: crate::nz!(3),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        // Test asset tree
        assert_eq!(asset_tree.len(), 4);
        assert_decimal_eq!(asset_tree[0][0], dec!(100.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(110.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(90.909090), EPSILON);
        assert_decimal_eq!(asset_tree[2][0], dec!(121.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][1], dec!(100.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][2], dec!(82.644628), EPSILON);
        assert_decimal_eq!(asset_tree[3][0], dec!(133.1), EPSILON);
        assert_decimal_eq!(asset_tree[3][1], dec!(110.0), EPSILON);
        assert_decimal_eq!(asset_tree[3][2], dec!(90.909090), EPSILON);
        assert_decimal_eq!(asset_tree[3][3], dec!(75.131480), EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(2.890941), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(1.125426), EPSILON);
        assert_decimal_eq!(option_tree[1][1], dec!(8.623025), EPSILON);
        assert_decimal_eq!(option_tree[2][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][1], dec!(4.635236), EPSILON);
        assert_decimal_eq!(option_tree[2][2], dec!(21.990608), EPSILON);
        assert_decimal_eq!(option_tree[3][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][1], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[3][2], dec!(19.090909), EPSILON);
        assert_decimal_eq!(option_tree[3][3], dec!(34.868519), EPSILON);
    }

    #[test]
    fn test_binomial_tree_european_put_option() {
        // Define parameters for an American option test case
        let params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::TWO,
            no_steps: crate::nz!(2),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        assert_decimal_eq!(asset_tree[0][0], dec!(50.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(61.070137), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(40.936537), EPSILON);
        assert_decimal_eq!(asset_tree[2][0], dec!(74.591234), EPSILON);
        assert_decimal_eq!(asset_tree[2][1], dec!(50.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][2], dec!(33.516002), EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(3.8687179), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(0.8038018), EPSILON);
        assert_decimal_eq!(option_tree[1][1], dec!(8.5273923), EPSILON);
        assert_decimal_eq!(option_tree[2][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][1], dec!(2.0), EPSILON);
        assert_decimal_eq!(option_tree[2][2], dec!(18.483997), EPSILON);
    }

    #[test]
    fn test_binomial_tree_american_put_option() {
        // Define parameters for an American option test case
        let params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::TWO,
            no_steps: crate::nz!(2),
            option_type: &OptionType::American,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };
        let (asset_tree, option_tree) = generate_binomial_tree(&params).unwrap();

        assert_decimal_eq!(asset_tree[0][0], dec!(50.0), EPSILON);
        assert_decimal_eq!(asset_tree[1][0], dec!(61.070137), EPSILON);
        assert_decimal_eq!(asset_tree[1][1], dec!(40.936537), EPSILON);
        assert_decimal_eq!(asset_tree[2][0], dec!(74.591234), EPSILON);
        assert_decimal_eq!(asset_tree[2][1], dec!(50.0), EPSILON);
        assert_decimal_eq!(asset_tree[2][2], dec!(33.516002), EPSILON);
        assert_decimal_eq!(option_tree[2][0], Decimal::ZERO, EPSILON);
        assert_decimal_eq!(option_tree[2][1], dec!(2.0), EPSILON);
        assert_decimal_eq!(option_tree[2][2], dec!(18.483997), EPSILON);
        assert_decimal_eq!(option_tree[1][0], dec!(0.803801), EPSILON);

        assert_decimal_eq!(option_tree[1][1], params.strike - asset_tree[1][1], EPSILON);
        assert_decimal_eq!(option_tree[0][0], dec!(4.887966), EPSILON);
    }
}

#[cfg(test)]
mod tests_bermuda_option {
    use super::*;
    use crate::assert_decimal_eq;
    use crate::model::types::OptionType;
    use rust_decimal_macros::dec;

    const EPSILON: Decimal = dec!(1e-4);

    #[test]
    fn test_bermuda_price_between_european_and_american() {
        // Bermuda price should be: European <= Bermuda <= American
        let european_params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::ONE,
            no_steps: crate::nz!(100),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let american_params = BinomialPricingParams {
            option_type: &OptionType::American,
            ..european_params.clone()
        };

        // Exercise at 3 months, 6 months, 9 months
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![0.25, 0.5, 0.75],
        };
        let bermuda_params = BinomialPricingParams {
            option_type: &bermuda_type,
            ..european_params.clone()
        };

        let european_price = price_binomial(european_params).unwrap();
        let american_price = price_binomial(american_params).unwrap();
        let bermuda_price = price_binomial(bermuda_params).unwrap();

        assert!(
            european_price <= bermuda_price,
            "European {} should be <= Bermuda {}",
            european_price,
            bermuda_price
        );
        assert!(
            bermuda_price <= american_price,
            "Bermuda {} should be <= American {}",
            bermuda_price,
            american_price
        );
    }

    #[test]
    fn test_bermuda_single_exercise_date() {
        // Single exercise date should give price between European and American
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![0.5],
        };
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.3),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(105.0),
            expiry: Positive::ONE,
            no_steps: crate::nz!(50),
            option_type: &bermuda_type,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert!(
            price > Decimal::ZERO,
            "Bermuda put price should be positive"
        );
    }

    #[test]
    fn test_bermuda_many_exercise_dates_approaches_american() {
        // With many exercise dates, Bermuda should approach American price
        let european_params = BinomialPricingParams {
            asset: pos_or_panic!(50.0),
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(52.0),
            expiry: Positive::ONE,
            no_steps: crate::nz!(52),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let american_params = BinomialPricingParams {
            option_type: &OptionType::American,
            ..european_params.clone()
        };

        // Weekly exercise dates (52 dates for 1 year)
        let exercise_dates: Vec<f64> = (1..=52).map(|i| i as f64 / 52.0).collect();
        let bermuda_type = OptionType::Bermuda { exercise_dates };
        let bermuda_params = BinomialPricingParams {
            option_type: &bermuda_type,
            ..european_params.clone()
        };

        let american_price = price_binomial(american_params).unwrap();
        let bermuda_price = price_binomial(bermuda_params).unwrap();

        // Bermuda with weekly exercise should be close to American
        let diff = (american_price - bermuda_price).abs();
        assert!(
            diff < dec!(0.5),
            "Bermuda with 52 exercise dates should be close to American: diff = {}",
            diff
        );
    }

    #[test]
    fn test_bermuda_no_exercise_dates_equals_european() {
        // Empty exercise dates results in European-like behavior
        let european_params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.2),
            int_rate: dec!(0.05),
            strike: Positive::HUNDRED,
            expiry: Positive::ONE,
            no_steps: crate::nz!(50),
            option_type: &OptionType::European,
            option_style: &OptionStyle::Put,
            side: &Side::Long,
        };

        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![],
        };
        let bermuda_params = BinomialPricingParams {
            option_type: &bermuda_type,
            ..european_params.clone()
        };

        let european_price = price_binomial(european_params).unwrap();
        let bermuda_price = price_binomial(bermuda_params).unwrap();

        assert_decimal_eq!(european_price, bermuda_price, EPSILON);
    }

    #[test]
    fn test_bermuda_call_option() {
        let bermuda_type = OptionType::Bermuda {
            exercise_dates: vec![0.25, 0.5, 0.75],
        };
        let params = BinomialPricingParams {
            asset: Positive::HUNDRED,
            volatility: pos_or_panic!(0.25),
            int_rate: dec!(0.05),
            strike: pos_or_panic!(95.0),
            expiry: Positive::ONE,
            no_steps: crate::nz!(100),
            option_type: &bermuda_type,
            option_style: &OptionStyle::Call,
            side: &Side::Long,
        };

        let price = price_binomial(params).unwrap();
        assert!(
            price > dec!(5.0),
            "ITM Bermuda call should have value > intrinsic"
        );
    }
}