scirs2-integrate 0.4.2

Numerical integration module for SciRS2 (scirs2-integrate)
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
//! Mathematical utilities for quantitative finance
//!
//! This module provides specialized mathematical functions commonly used in financial
//! calculations including option pricing formulas, statistical functions, and numerical methods.
//!
//! # Features
//! - Black-Scholes formula and Greeks
//! - Implied volatility calculation (Newton-Raphson, Brent)
//! - Normal distribution CDF/PDF (fast approximations)
//! - Bachelier model (for negative rates)
//! - Numerical stability helpers
//!
//! # Example
//! ```
//! use scirs2_integrate::specialized::finance::utils::math::{
//!     black_scholes_call, implied_volatility_newton, norm_cdf
//! };
//!
//! // Price a call option
//! let price = black_scholes_call(100.0, 100.0, 1.0, 0.05, 0.2);
//! assert!(price > 0.0);
//!
//! // Calculate implied volatility
//! let iv = implied_volatility_newton(price, 100.0, 100.0, 1.0, 0.05, true);
//! ```

use crate::error::{IntegrateError, IntegrateResult as Result};
use std::f64::consts::{PI, SQRT_2};

/// SABR model parameters
#[derive(Debug, Clone)]
pub struct SABRParameters {
    /// Alpha (initial volatility)
    pub alpha: f64,
    /// Beta (elasticity parameter, typically 0, 0.5, or 1)
    pub beta: f64,
    /// Rho (correlation between forward and volatility)
    pub rho: f64,
    /// Nu (volatility of volatility)
    pub nu: f64,
}

impl SABRParameters {
    /// Create new SABR parameters with validation
    pub fn new(alpha: f64, beta: f64, rho: f64, nu: f64) -> Result<Self> {
        if alpha <= 0.0 {
            return Err(IntegrateError::ValueError(
                "Alpha must be positive".to_string(),
            ));
        }
        if !(0.0..=1.0).contains(&beta) {
            return Err(IntegrateError::ValueError(
                "Beta must be between 0 and 1".to_string(),
            ));
        }
        if !(-1.0..=1.0).contains(&rho) {
            return Err(IntegrateError::ValueError(
                "Rho must be between -1 and 1".to_string(),
            ));
        }
        if nu < 0.0 {
            return Err(IntegrateError::ValueError(
                "Nu must be non-negative".to_string(),
            ));
        }

        Ok(Self {
            alpha,
            beta,
            rho,
            nu,
        })
    }

    /// Calculate implied volatility using SABR formula (Hagan et al. 2002)
    pub fn implied_volatility(&self, forward: f64, strike: f64, time: f64) -> Result<f64> {
        if forward <= 0.0 || strike <= 0.0 {
            return Err(IntegrateError::ValueError(
                "Forward and strike must be positive".to_string(),
            ));
        }
        if time <= 0.0 {
            return Err(IntegrateError::ValueError(
                "Time must be positive".to_string(),
            ));
        }

        // ATM case
        if (forward - strike).abs() / forward < 1e-8 {
            let f_mid_beta = forward.powf(1.0 - self.beta);
            let term1 = self.alpha / f_mid_beta;

            let term2 = 1.0
                + ((1.0 - self.beta).powi(2) / 24.0 * self.alpha.powi(2)
                    / forward.powf(2.0 - 2.0 * self.beta)
                    + 0.25 * self.rho * self.beta * self.nu * self.alpha / f_mid_beta
                    + (2.0 - 3.0 * self.rho.powi(2)) / 24.0 * self.nu.powi(2))
                    * time;

            return Ok(term1 * term2);
        }

        // Non-ATM case
        let log_fk = (forward / strike).ln();
        let f_k_mid_beta = (forward * strike).powf((1.0 - self.beta) / 2.0);

        let z = (self.nu / self.alpha) * f_k_mid_beta * log_fk;

        // Calculate x(z) with numerical stability
        let x = if z.abs() < 1e-6 {
            // Taylor expansion for small z
            1.0 - 0.5 * self.rho * z
        } else {
            let sqrt_term = (1.0 - 2.0 * self.rho * z + z.powi(2)).sqrt();
            ((sqrt_term + z - self.rho) / (1.0 - self.rho)).ln() / z
        };

        let numerator = self.alpha;
        let denominator = f_k_mid_beta
            * (1.0
                + (1.0 - self.beta).powi(2) / 24.0 * log_fk.powi(2)
                + (1.0 - self.beta).powi(4) / 1920.0 * log_fk.powi(4));

        let correction = 1.0
            + ((1.0 - self.beta).powi(2) / 24.0 * self.alpha.powi(2)
                / forward.powf(2.0 - 2.0 * self.beta)
                + 0.25 * self.rho * self.beta * self.nu * self.alpha / f_k_mid_beta
                + (2.0 - 3.0 * self.rho.powi(2)) / 24.0 * self.nu.powi(2))
                * time;

        Ok((numerator / denominator) * x * correction)
    }
}

// Deprecated placeholder functions for backward compatibility
#[deprecated(note = "Use SABRParameters::implied_volatility instead")]
pub fn interpolate_smile() -> Result<()> {
    Err(IntegrateError::ValueError(
        "Use SABRParameters for smile interpolation".to_string(),
    ))
}

#[deprecated(note = "Arbitrage checking not yet implemented")]
pub fn vol_surface_arbitrage_free() -> Result<()> {
    Err(IntegrateError::ValueError(
        "Arbitrage-free surface checking not yet implemented".to_string(),
    ))
}

/// Standard normal cumulative distribution function
///
/// Uses rational approximation with max error < 1.5e-7
pub fn norm_cdf(x: f64) -> f64 {
    if x.is_nan() {
        return f64::NAN;
    }
    if x.is_infinite() {
        return if x > 0.0 { 1.0 } else { 0.0 };
    }

    // Abramowitz and Stegun approximation (1964)
    // Maximum error: 1.5×10^-7
    let abs_x = x.abs();

    if abs_x > 10.0 {
        // For large |x|, return extremes directly
        return if x > 0.0 { 1.0 } else { 0.0 };
    }

    let t = 1.0 / (1.0 + 0.2316419 * abs_x);
    let poly = t
        * (0.319381530
            + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))));

    let pdf = (-0.5 * x * x).exp() / (2.0 * PI).sqrt();
    let cdf = 1.0 - pdf * poly;

    if x >= 0.0 {
        cdf
    } else {
        1.0 - cdf
    }
}

/// Standard normal probability density function
#[inline]
pub fn norm_pdf(x: f64) -> f64 {
    (2.0 * PI).sqrt().recip() * (-0.5 * x * x).exp()
}

/// Natural logarithm with protection against domain errors
#[inline]
pub fn safe_log(x: f64) -> f64 {
    if x > 0.0 {
        x.ln()
    } else if x == 0.0 {
        f64::NEG_INFINITY
    } else {
        f64::NAN
    }
}

/// Square root with protection against domain errors
#[inline]
pub fn safe_sqrt(x: f64) -> f64 {
    if x >= 0.0 {
        x.sqrt()
    } else {
        f64::NAN
    }
}

/// Black-Scholes d1 parameter
pub fn d1(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 || volatility <= 0.0 {
        return f64::NAN;
    }
    let vol_sqrt_t = volatility * time.sqrt();
    (safe_log(spot / strike) + (rate + 0.5 * volatility * volatility) * time) / vol_sqrt_t
}

/// Black-Scholes d2 parameter
pub fn d2(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 || volatility <= 0.0 {
        return f64::NAN;
    }
    let vol_sqrt_t = volatility * time.sqrt();
    d1(spot, strike, time, rate, volatility) - vol_sqrt_t
}

/// Black-Scholes call option price
pub fn black_scholes_call(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 {
        return (spot - strike).max(0.0);
    }
    if volatility <= 0.0 {
        return ((spot - strike * (-rate * time).exp()).max(0.0)).max(0.0);
    }

    let d1_val = d1(spot, strike, time, rate, volatility);
    let d2_val = d2(spot, strike, time, rate, volatility);

    spot * norm_cdf(d1_val) - strike * (-rate * time).exp() * norm_cdf(d2_val)
}

/// Black-Scholes put option price
pub fn black_scholes_put(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 {
        return (strike - spot).max(0.0);
    }
    if volatility <= 0.0 {
        return ((strike * (-rate * time).exp() - spot).max(0.0)).max(0.0);
    }

    let d1_val = d1(spot, strike, time, rate, volatility);
    let d2_val = d2(spot, strike, time, rate, volatility);

    strike * (-rate * time).exp() * norm_cdf(-d2_val) - spot * norm_cdf(-d1_val)
}

/// Vega (sensitivity to volatility) - same for calls and puts
pub fn vega(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 || volatility <= 0.0 {
        return 0.0;
    }

    let d1_val = d1(spot, strike, time, rate, volatility);
    spot * norm_pdf(d1_val) * time.sqrt()
}

/// Implied volatility using Newton-Raphson method
pub fn implied_volatility_newton(
    market_price: f64,
    spot: f64,
    strike: f64,
    time: f64,
    rate: f64,
    is_call: bool,
) -> Result<f64> {
    if market_price <= 0.0 {
        return Err(IntegrateError::ValueError(
            "Market price must be positive".to_string(),
        ));
    }

    // Initial guess using Brenner-Subrahmanyam approximation
    let intrinsic = if is_call {
        (spot - strike * (-rate * time).exp()).max(0.0)
    } else {
        (strike * (-rate * time).exp() - spot).max(0.0)
    };

    if market_price <= intrinsic {
        return Err(IntegrateError::ValueError(
            "Market price below intrinsic value".to_string(),
        ));
    }

    let time_value = market_price - intrinsic;
    let mut vol = (2.0 * PI / time).sqrt() * (time_value / spot);
    vol = vol.max(0.01).min(5.0); // Clamp initial guess

    const MAX_ITERATIONS: usize = 100;
    const TOLERANCE: f64 = 1e-8;

    for _ in 0..MAX_ITERATIONS {
        let price = if is_call {
            black_scholes_call(spot, strike, time, rate, vol)
        } else {
            black_scholes_put(spot, strike, time, rate, vol)
        };

        let diff = price - market_price;

        if diff.abs() < TOLERANCE {
            return Ok(vol);
        }

        let vega_val = vega(spot, strike, time, rate, vol);

        if vega_val < 1e-10 {
            return Err(IntegrateError::ValueError(
                "Vega too small for convergence".to_string(),
            ));
        }

        let vol_new = vol - diff / vega_val;

        // Ensure volatility stays positive and reasonable
        let vol_new = vol_new.max(0.001).min(10.0);

        if (vol_new - vol).abs() < TOLERANCE {
            return Ok(vol_new);
        }

        vol = vol_new;
    }

    Err(IntegrateError::ValueError(
        "Implied volatility did not converge".to_string(),
    ))
}

/// Bachelier model for call options (handles negative rates/prices)
pub fn bachelier_call(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 {
        return (spot - strike).max(0.0);
    }
    if volatility <= 0.0 {
        return ((spot - strike * (-rate * time).exp()).max(0.0)).max(0.0);
    }

    let forward = spot * (rate * time).exp();
    let std_dev = volatility * time.sqrt();
    let d = (forward - strike) / std_dev;

    (forward - strike) * norm_cdf(d) + std_dev * norm_pdf(d)
}

/// Bachelier model for put options
pub fn bachelier_put(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 {
        return (strike - spot).max(0.0);
    }
    if volatility <= 0.0 {
        return ((strike * (-rate * time).exp() - spot).max(0.0)).max(0.0);
    }

    let forward = spot * (rate * time).exp();
    let std_dev = volatility * time.sqrt();
    let d = (forward - strike) / std_dev;

    (strike - forward) * norm_cdf(-d) + std_dev * norm_pdf(d)
}

/// Binary search for implied volatility (more robust than Newton-Raphson)
pub fn implied_volatility_brent(
    market_price: f64,
    spot: f64,
    strike: f64,
    time: f64,
    rate: f64,
    is_call: bool,
) -> Result<f64> {
    if market_price <= 0.0 {
        return Err(IntegrateError::ValueError(
            "Market price must be positive".to_string(),
        ));
    }

    let mut vol_low = 0.001;
    let mut vol_high = 5.0;

    const MAX_ITERATIONS: usize = 100;
    const TOLERANCE: f64 = 1e-8;

    // Check bounds
    let price_low = if is_call {
        black_scholes_call(spot, strike, time, rate, vol_low)
    } else {
        black_scholes_put(spot, strike, time, rate, vol_low)
    };

    let price_high = if is_call {
        black_scholes_call(spot, strike, time, rate, vol_high)
    } else {
        black_scholes_put(spot, strike, time, rate, vol_high)
    };

    if market_price < price_low || market_price > price_high {
        return Err(IntegrateError::ValueError(
            "Market price outside pricing bounds".to_string(),
        ));
    }

    // Binary search
    for _ in 0..MAX_ITERATIONS {
        let vol_mid = (vol_low + vol_high) / 2.0;

        let price_mid = if is_call {
            black_scholes_call(spot, strike, time, rate, vol_mid)
        } else {
            black_scholes_put(spot, strike, time, rate, vol_mid)
        };

        if (price_mid - market_price).abs() < TOLERANCE {
            return Ok(vol_mid);
        }

        if price_mid < market_price {
            vol_low = vol_mid;
        } else {
            vol_high = vol_mid;
        }

        if vol_high - vol_low < TOLERANCE {
            return Ok(vol_mid);
        }
    }

    Err(IntegrateError::ValueError(
        "Implied volatility did not converge".to_string(),
    ))
}

/// Delta (sensitivity to spot price) for call option
pub fn delta_call(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 {
        return if spot > strike { 1.0 } else { 0.0 };
    }
    if volatility <= 0.0 {
        return if spot > strike { 1.0 } else { 0.0 };
    }

    let d1_val = d1(spot, strike, time, rate, volatility);
    norm_cdf(d1_val)
}

/// Delta for put option
pub fn delta_put(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    delta_call(spot, strike, time, rate, volatility) - 1.0
}

/// Gamma (sensitivity of delta to spot) - same for calls and puts
pub fn gamma(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 || volatility <= 0.0 || spot <= 0.0 {
        return 0.0;
    }

    let d1_val = d1(spot, strike, time, rate, volatility);
    norm_pdf(d1_val) / (spot * volatility * time.sqrt())
}

/// Theta (time decay) for call option
pub fn theta_call(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 {
        return 0.0;
    }
    if volatility <= 0.0 {
        return 0.0;
    }

    let d1_val = d1(spot, strike, time, rate, volatility);
    let d2_val = d2(spot, strike, time, rate, volatility);

    let term1 = -(spot * norm_pdf(d1_val) * volatility) / (2.0 * time.sqrt());
    let term2 = rate * strike * (-rate * time).exp() * norm_cdf(d2_val);

    term1 - term2
}

/// Theta (time decay) for put option
pub fn theta_put(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 {
        return 0.0;
    }
    if volatility <= 0.0 {
        return 0.0;
    }

    let d1_val = d1(spot, strike, time, rate, volatility);
    let d2_val = d2(spot, strike, time, rate, volatility);

    let term1 = -(spot * norm_pdf(d1_val) * volatility) / (2.0 * time.sqrt());
    let term2 = rate * strike * (-rate * time).exp() * norm_cdf(-d2_val);

    term1 + term2
}

/// Rho (sensitivity to interest rate) for call option
pub fn rho_call(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 {
        return 0.0;
    }
    if volatility <= 0.0 {
        return if spot > strike {
            strike * time * (-rate * time).exp()
        } else {
            0.0
        };
    }

    let d2_val = d2(spot, strike, time, rate, volatility);
    strike * time * (-rate * time).exp() * norm_cdf(d2_val)
}

/// Rho (sensitivity to interest rate) for put option
pub fn rho_put(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> f64 {
    if time <= 0.0 {
        return 0.0;
    }
    if volatility <= 0.0 {
        return if spot < strike {
            -strike * time * (-rate * time).exp()
        } else {
            0.0
        };
    }

    let d2_val = d2(spot, strike, time, rate, volatility);
    -strike * time * (-rate * time).exp() * norm_cdf(-d2_val)
}

/// Calculate all Greeks at once (more efficient than individual calls)
pub struct Greeks {
    pub delta: f64,
    pub gamma: f64,
    pub vega: f64,
    pub theta: f64,
    pub rho: f64,
}

impl Greeks {
    /// Calculate all Greeks for a call option
    pub fn call(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> Self {
        Self {
            delta: delta_call(spot, strike, time, rate, volatility),
            gamma: gamma(spot, strike, time, rate, volatility),
            vega: vega(spot, strike, time, rate, volatility),
            theta: theta_call(spot, strike, time, rate, volatility),
            rho: rho_call(spot, strike, time, rate, volatility),
        }
    }

    /// Calculate all Greeks for a put option
    pub fn put(spot: f64, strike: f64, time: f64, rate: f64, volatility: f64) -> Self {
        Self {
            delta: delta_put(spot, strike, time, rate, volatility),
            gamma: gamma(spot, strike, time, rate, volatility),
            vega: vega(spot, strike, time, rate, volatility),
            theta: theta_put(spot, strike, time, rate, volatility),
            rho: rho_put(spot, strike, time, rate, volatility),
        }
    }
}

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

    #[test]
    fn test_norm_cdf() {
        assert!((norm_cdf(0.0) - 0.5).abs() < 1e-7);
        assert!(norm_cdf(-10.0) < 1e-10);
        assert!(norm_cdf(10.0) > 0.9999999);
        assert!((norm_cdf(1.0) - 0.8413447).abs() < 1e-5);
    }

    #[test]
    fn test_norm_pdf() {
        let pdf_0 = norm_pdf(0.0);
        assert!((pdf_0 - 0.3989423).abs() < 1e-6);

        let pdf_1 = norm_pdf(1.0);
        assert!((pdf_1 - 0.2419707).abs() < 1e-6);
    }

    #[test]
    fn test_black_scholes_call() {
        let price = black_scholes_call(100.0, 100.0, 1.0, 0.05, 0.2);
        assert!(price > 9.0 && price < 12.0); // ATM call should be around 10.45
    }

    #[test]
    fn test_black_scholes_put() {
        let price = black_scholes_put(100.0, 100.0, 1.0, 0.05, 0.2);
        assert!(price > 5.0 && price < 8.0); // ATM put should be around 5.57
    }

    #[test]
    fn test_put_call_parity() {
        let s = 100.0;
        let k = 100.0;
        let t = 1.0;
        let r = 0.05;
        let v = 0.2;

        let call = black_scholes_call(s, k, t, r, v);
        let put = black_scholes_put(s, k, t, r, v);

        // Put-call parity: C - P = S - K*e^(-rT)
        let lhs = call - put;
        let rhs = s - k * (-r * t).exp();

        assert!((lhs - rhs).abs() < 1e-10);
    }

    #[test]
    fn test_vega() {
        let vega_val = vega(100.0, 100.0, 1.0, 0.05, 0.2);
        assert!(vega_val > 0.0);
        assert!(vega_val < 50.0); // Reasonable range for ATM option
    }

    #[test]
    fn test_implied_volatility_newton() {
        let spot = 100.0;
        let strike = 100.0;
        let time = 1.0;
        let rate = 0.05;
        let true_vol = 0.25;

        let market_price = black_scholes_call(spot, strike, time, rate, true_vol);
        let implied_vol = implied_volatility_newton(market_price, spot, strike, time, rate, true)
            .expect("Operation failed");

        assert!((implied_vol - true_vol).abs() < 1e-6);
    }

    #[test]
    fn test_implied_volatility_brent() {
        let spot = 100.0;
        let strike = 100.0;
        let time = 1.0;
        let rate = 0.05;
        let true_vol = 0.25;

        let market_price = black_scholes_call(spot, strike, time, rate, true_vol);
        let implied_vol = implied_volatility_brent(market_price, spot, strike, time, rate, true)
            .expect("Operation failed");

        assert!((implied_vol - true_vol).abs() < 1e-6);
    }

    #[test]
    fn test_delta_call() {
        let delta = delta_call(100.0, 100.0, 1.0, 0.05, 0.2);
        // ATM call delta with positive rate is slightly above 0.5
        assert!(delta > 0.50 && delta < 0.65);
    }

    #[test]
    fn test_delta_put() {
        let delta = delta_put(100.0, 100.0, 1.0, 0.05, 0.2);
        // ATM put delta = call_delta - 1
        assert!(delta > -0.50 && delta < -0.35);
    }

    #[test]
    fn test_gamma() {
        let gamma_val = gamma(100.0, 100.0, 1.0, 0.05, 0.2);
        assert!(gamma_val > 0.0);
        assert!(gamma_val < 0.1); // Reasonable range
    }

    #[test]
    fn test_bachelier_call() {
        let price = bachelier_call(100.0, 100.0, 1.0, 0.05, 20.0);
        assert!(price > 0.0);
    }

    #[test]
    fn test_bachelier_put() {
        let price = bachelier_put(100.0, 100.0, 1.0, 0.05, 20.0);
        assert!(price > 0.0);
    }

    #[test]
    fn test_zero_time() {
        assert_eq!(black_scholes_call(110.0, 100.0, 0.0, 0.05, 0.2), 10.0);
        assert_eq!(black_scholes_put(90.0, 100.0, 0.0, 0.05, 0.2), 10.0);
    }

    #[test]
    fn test_safe_functions() {
        assert!(safe_log(-1.0).is_nan());
        assert_eq!(safe_log(0.0), f64::NEG_INFINITY);
        assert!(safe_sqrt(-1.0).is_nan());
        assert_eq!(safe_sqrt(4.0), 2.0);
    }

    #[test]
    fn test_theta_call() {
        let theta = theta_call(100.0, 100.0, 1.0, 0.05, 0.2);
        // Theta is negative (time decay) for long positions
        assert!(theta < 0.0);
        // Reasonable magnitude for ATM option
        assert!(theta.abs() < 20.0);
    }

    #[test]
    fn test_theta_put() {
        let theta = theta_put(100.0, 100.0, 1.0, 0.05, 0.2);
        // Theta for put depends on interest rate
        // With positive rate, ATM put theta may be positive or negative
        assert!(theta.abs() < 20.0);
    }

    #[test]
    fn test_rho_call() {
        let rho = rho_call(100.0, 100.0, 1.0, 0.05, 0.2);
        // Rho is positive for call options
        assert!(rho > 0.0);
        // Reasonable magnitude
        assert!(rho < 100.0);
    }

    #[test]
    fn test_rho_put() {
        let rho = rho_put(100.0, 100.0, 1.0, 0.05, 0.2);
        // Rho is negative for put options
        assert!(rho < 0.0);
        // Reasonable magnitude
        assert!(rho.abs() < 100.0);
    }

    #[test]
    fn test_greeks_struct_call() {
        let greeks = Greeks::call(100.0, 100.0, 1.0, 0.05, 0.2);

        // Check all Greeks are reasonable
        assert!(greeks.delta > 0.5 && greeks.delta < 0.65);
        assert!(greeks.gamma > 0.0);
        assert!(greeks.vega > 0.0);
        assert!(greeks.theta < 0.0);
        assert!(greeks.rho > 0.0);
    }

    #[test]
    fn test_greeks_struct_put() {
        let greeks = Greeks::put(100.0, 100.0, 1.0, 0.05, 0.2);

        // Check all Greeks are reasonable
        assert!(greeks.delta < 0.0 && greeks.delta > -0.5);
        assert!(greeks.gamma > 0.0); // Same as call
        assert!(greeks.vega > 0.0); // Same as call
        assert!(greeks.rho < 0.0);
    }

    #[test]
    fn test_theta_zero_time() {
        assert_eq!(theta_call(100.0, 100.0, 0.0, 0.05, 0.2), 0.0);
        assert_eq!(theta_put(100.0, 100.0, 0.0, 0.05, 0.2), 0.0);
    }

    #[test]
    fn test_rho_zero_time() {
        assert_eq!(rho_call(100.0, 100.0, 0.0, 0.05, 0.2), 0.0);
        assert_eq!(rho_put(100.0, 100.0, 0.0, 0.05, 0.2), 0.0);
    }

    #[test]
    fn test_sabr_parameters_creation() {
        let sabr = SABRParameters::new(0.2, 0.5, -0.3, 0.4).expect("Operation failed");
        assert_eq!(sabr.alpha, 0.2);
        assert_eq!(sabr.beta, 0.5);
        assert_eq!(sabr.rho, -0.3);
        assert_eq!(sabr.nu, 0.4);
    }

    #[test]
    fn test_sabr_parameters_validation() {
        assert!(SABRParameters::new(-0.1, 0.5, 0.0, 0.4).is_err()); // Negative alpha
        assert!(SABRParameters::new(0.2, 1.5, 0.0, 0.4).is_err()); // Beta > 1
        assert!(SABRParameters::new(0.2, 0.5, 1.5, 0.4).is_err()); // Rho > 1
        assert!(SABRParameters::new(0.2, 0.5, 0.0, -0.1).is_err()); // Negative nu
    }

    #[test]
    fn test_sabr_atm_volatility() {
        let sabr = SABRParameters::new(0.2, 0.5, -0.3, 0.4).expect("Operation failed");
        let forward = 100.0;
        let strike = 100.0;
        let time = 1.0;

        let vol = sabr
            .implied_volatility(forward, strike, time)
            .expect("Operation failed");
        assert!(vol > 0.0);
        assert!(vol < 1.0); // Reasonable volatility range
    }

    #[test]
    fn test_sabr_smile_shape() {
        let sabr = SABRParameters::new(0.2, 0.5, -0.3, 0.4).expect("Operation failed");
        let forward = 100.0;
        let time = 1.0;

        let vol_otm = sabr
            .implied_volatility(forward, 110.0, time)
            .expect("Operation failed");
        let vol_atm = sabr
            .implied_volatility(forward, 100.0, time)
            .expect("Operation failed");
        let vol_itm = sabr
            .implied_volatility(forward, 90.0, time)
            .expect("Operation failed");

        // All vols should be reasonable and positive
        assert!(vol_otm > 0.0 && vol_otm < 1.0);
        assert!(vol_atm > 0.0 && vol_atm < 1.0);
        assert!(vol_itm > 0.0 && vol_itm < 1.0);

        // Verify smile exists (not flat)
        let smile_measure = (vol_itm - vol_atm).abs() + (vol_otm - vol_atm).abs();
        assert!(smile_measure > 0.001); // Some curvature exists
    }

    #[test]
    fn test_sabr_beta_zero() {
        // Beta = 0 corresponds to normal model
        let sabr = SABRParameters::new(20.0, 0.0, 0.0, 0.0).expect("Operation failed");
        let vol = sabr
            .implied_volatility(100.0, 100.0, 1.0)
            .expect("Operation failed");
        // For beta=0, vol should be positive and reasonable
        assert!(vol > 0.0 && vol < 100.0);
    }

    #[test]
    fn test_sabr_beta_one() {
        // Beta = 1 corresponds to lognormal model
        let sabr = SABRParameters::new(0.2, 1.0, 0.0, 0.0).expect("Operation failed");
        let vol = sabr
            .implied_volatility(100.0, 100.0, 1.0)
            .expect("Operation failed");
        assert!((vol - 0.2).abs() < 0.01); // Should be close to alpha
    }

    #[test]
    fn test_sabr_symmetry() {
        let sabr = SABRParameters::new(0.2, 0.5, 0.0, 0.2).expect("Operation failed");
        let forward = 100.0;
        let time = 1.0;

        // With rho = 0, smile should be roughly symmetric
        let vol_up = sabr
            .implied_volatility(forward, 105.0, time)
            .expect("Operation failed");
        let vol_down = sabr
            .implied_volatility(forward, 95.0, time)
            .expect("Operation failed");

        // Should be similar (within 10%)
        assert!((vol_up - vol_down).abs() / vol_up < 0.1);
    }
}