regit-svi 2.0.0

Arbitrage-free SVI volatility surfaces in pure Rust. Raw, Jump-Wings and SSVI parametrisations, calibration, and static-arbitrage checks. Zero dependencies.
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
// Copyright 2026 Regit.io — Nicolas Koenig
// SPDX-License-Identifier: Apache-2.0

//! Surface SVI (SSVI) parametrisation.
//!
//! SSVI parametrises the entire surface at once, as a function of
//! log-moneyness `k` and the ATM total variance `theta = w(0, t)`:
//!
//! ```text
//! w(k, theta) = (theta / 2)
//!             * ( 1 + rho*phi(theta)*k
//!                   + sqrt( (phi(theta)*k + rho)^2 + (1 - rho^2) ) )
//! ```
//!
//! The free objects are a single global correlation `rho in (-1, 1)`, the ATM
//! total-variance term structure `theta_t`, and a smoothing function
//! `phi : R+ -> R+`. Two standard choices of `phi` are supported (MATH.md §6):
//!
//! ```text
//! Heston-like:  phi(theta) = (1/(lambda*theta))
//!                          * (1 - (1 - exp(-lambda*theta))/(lambda*theta))
//! Power-law:    phi(theta) = eta / (theta^gamma * (1 + theta)^(1 - gamma))
//! ```
//!
//! For fixed `theta`, an SSVI slice equals a raw SVI slice — the closed-form
//! map is [`Ssvi::slice_at`].
//!
//! SSVI's value is that static-arbitrage conditions admit closed-form
//! inequalities (Gatheral & Jacquier 2014, Theorems 4.1 and 4.2), checked here by
//! [`Ssvi::butterfly_assessment`] and [`Ssvi::calendar_assessment`].
//!
//! # References
//!
//! - Gatheral, J. & Jacquier, A., "Arbitrage-free SVI volatility surfaces",
//!   *Quantitative Finance* 14(1):59-71 (2014), Section 4.

use crate::error::ParamError;
use crate::no_arb::evidence::{ArbitrageAssessment, ArbitrageEvidence, ArbitrageStatus};
use crate::smile::raw::{RawSvi, stable_shape};

/// SSVI smoothing function `phi : R+ -> R+`.
///
/// `phi` controls how the smile curvature evolves with maturity. Both
/// supported forms are positive and decreasing in `theta`; arbitrage evidence
/// is assessed separately because positivity alone is not sufficient.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use regit_svi::surface::ssvi::Phi;
///
/// let heston = Phi::heston(1.0)?;
/// let power = Phi::modified_power_law(0.5, 0.5)?;
/// assert!(heston.eval(0.04) > 0.0);
/// assert!(power.eval(0.04) > 0.0);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Phi(PhiKind);

#[derive(Debug, Clone, Copy, PartialEq)]
enum PhiKind {
    Heston { lambda: f64 },
    ModifiedPowerLaw { eta: f64, gamma: f64 },
}

impl Phi {
    /// Creates a validated Heston-like smoothing function.
    ///
    /// # Errors
    ///
    /// Returns [`ParamError::InvalidPhiParameter`] if `lambda <= 0`, or
    /// [`ParamError::NonFinite`] if `lambda` is not finite.
    ///
    /// # Examples
    ///
    /// ```
    /// use regit_svi::surface::ssvi::Phi;
    ///
    /// assert!(Phi::heston(1.5).is_ok());
    /// assert!(Phi::heston(0.0).is_err());
    /// ```
    pub fn heston(lambda: f64) -> Result<Self, ParamError> {
        if !lambda.is_finite() {
            return Err(ParamError::NonFinite { name: "lambda" });
        }
        if lambda <= 0.0 {
            return Err(ParamError::InvalidPhiParameter {
                name: "lambda",
                value: lambda,
            });
        }
        Ok(Self(PhiKind::Heston { lambda }))
    }

    /// Creates a validated power-law smoothing function.
    ///
    /// # Errors
    ///
    /// Returns [`ParamError::InvalidPhiParameter`] if `eta <= 0` or
    /// `gamma` is outside `(0, 1)`, or [`ParamError::NonFinite`] if either
    /// parameter is not finite.
    ///
    /// # Examples
    ///
    /// ```
    /// use regit_svi::surface::ssvi::Phi;
    ///
    /// assert!(Phi::modified_power_law(0.5, 0.5).is_ok());
    /// assert!(Phi::modified_power_law(0.5, 1.0).is_err());
    /// ```
    pub fn modified_power_law(eta: f64, gamma: f64) -> Result<Self, ParamError> {
        if !eta.is_finite() {
            return Err(ParamError::NonFinite { name: "eta" });
        }
        if !gamma.is_finite() {
            return Err(ParamError::NonFinite { name: "gamma" });
        }
        if eta <= 0.0 {
            return Err(ParamError::InvalidPhiParameter {
                name: "eta",
                value: eta,
            });
        }
        if gamma <= 0.0 || gamma >= 1.0 {
            return Err(ParamError::InvalidPhiParameter {
                name: "gamma",
                value: gamma,
            });
        }
        Ok(Self(PhiKind::ModifiedPowerLaw { eta, gamma }))
    }

    /// Evaluates `phi(theta)` for `theta > 0`.
    ///
    /// The Heston-like form uses `x = lambda*theta` and
    /// `phi = (1/x)*(1 - (1 - exp(-x))/x)`; the power-law form uses
    /// `phi = eta / (theta^gamma * (1 + theta)^(1-gamma))`.
    /// This infallible numerical kernel assumes finite, positive `theta` and
    /// propagates IEEE non-finite results outside that domain or range.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::surface::ssvi::Phi;
    ///
    /// // Power-law at theta = 1: phi = eta / (1 * 2^(1-gamma)).
    /// let p = Phi::modified_power_law(1.0, 0.5)?;
    /// assert!((p.eval(1.0) - 1.0 / 2.0_f64.powf(0.5)).abs() < 1e-12);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn eval(&self, theta: f64) -> f64 {
        match self.0 {
            PhiKind::Heston { lambda } => {
                let x = lambda * theta;
                if x.abs() <= 1.0e-4 {
                    0.5 + x * (-1.0 / 6.0 + x * (1.0 / 24.0 + x * (-1.0 / 120.0 + x / 720.0)))
                } else {
                    (x + (-x).exp_m1()) / (x * x)
                }
            }
            PhiKind::ModifiedPowerLaw { eta, gamma } => {
                eta / (theta.powf(gamma) * (1.0 + theta).powf(1.0 - gamma))
            }
        }
    }

    /// Returns the Heston-like `lambda`, or `None` for another family.
    #[must_use]
    pub const fn heston_lambda(self) -> Option<f64> {
        match self.0 {
            PhiKind::Heston { lambda } => Some(lambda),
            PhiKind::ModifiedPowerLaw { .. } => None,
        }
    }

    /// Returns modified-power-law `(eta, gamma)`, or `None` for another family.
    #[must_use]
    pub const fn modified_power_law_parameters(self) -> Option<(f64, f64)> {
        match self.0 {
            PhiKind::ModifiedPowerLaw { eta, gamma } => Some((eta, gamma)),
            PhiKind::Heston { .. } => None,
        }
    }
}

/// A Surface SVI parametrisation: a global correlation plus a smoothing
/// function.
///
/// The ATM total-variance term structure `theta_t` is supplied per evaluation
/// (it is interpolated from market quotes by the surface layer), so an
/// [`Ssvi`] value is the maturity-independent part of the surface.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use regit_svi::surface::ssvi::{Phi, Ssvi};
///
/// let ssvi = Ssvi::new(-0.4, Phi::modified_power_law(0.5, 0.5)?)?;
/// let w = ssvi.total_variance(0.1, 0.04);
/// assert!(w > 0.0);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ssvi {
    /// Global correlation `rho in (-1, 1)`.
    pub(crate) rho: f64,
    /// The smoothing function `phi`.
    pub(crate) phi: Phi,
}

impl Ssvi {
    /// Creates a validated SSVI surface.
    ///
    /// # Errors
    ///
    /// - [`ParamError::NonFinite`] if `rho` is not finite.
    /// - [`ParamError::CorrelationOutOfRange`] if `|rho| >= 1`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::surface::ssvi::{Phi, Ssvi};
    ///
    /// assert!(Ssvi::new(-0.4, Phi::heston(1.0)?).is_ok());
    /// assert!(Ssvi::new(1.0, Phi::heston(1.0)?).is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(rho: f64, phi: Phi) -> Result<Self, ParamError> {
        if !rho.is_finite() {
            return Err(ParamError::NonFinite { name: "rho" });
        }
        if rho.abs() >= 1.0 {
            return Err(ParamError::CorrelationOutOfRange { rho });
        }
        Ok(Self { rho, phi })
    }

    /// Returns the global correlation parameter.
    #[must_use]
    pub const fn rho(self) -> f64 {
        self.rho
    }

    /// Returns the validated smoothing function.
    #[must_use]
    pub const fn phi(self) -> Phi {
        self.phi
    }

    /// Total implied variance `w(k, theta)` from the SSVI form.
    ///
    /// This infallible numerical kernel assumes finite `k` and finite,
    /// positive `theta`; it propagates IEEE non-finite results outside that
    /// domain or range. [`Self::slice_at`] provides validated slice mapping.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::surface::ssvi::{Phi, Ssvi};
    ///
    /// let ssvi = Ssvi::new(0.0, Phi::modified_power_law(0.5, 0.5)?)?;
    /// // With rho = 0 and k = 0, w = theta/2 * (1 + sqrt(1)) = theta.
    /// assert!((ssvi.total_variance(0.0, 0.04) - 0.04).abs() < 1e-15);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn total_variance(&self, k: f64, theta: f64) -> f64 {
        let phi = self.phi.eval(theta);
        let pk = phi * k;
        let one_minus_rho2 = 1.0 - self.rho * self.rho;
        let shifted = pk + self.rho;
        let rho_scale = one_minus_rho2.sqrt();
        let radial = shifted.hypot(rho_scale);
        let bracket = one_minus_rho2 + stable_shape(shifted, rho_scale, self.rho, radial);
        (theta / 2.0) * bracket
    }

    /// The raw SVI slice equal to this SSVI surface at fixed `theta`.
    ///
    /// Closed-form map (MATH.md §6):
    ///
    /// ```text
    /// a     = (theta/2) * (1 - rho^2)
    /// b     = theta * phi / 2
    /// rho   = rho
    /// m     = -rho / phi
    /// sigma = sqrt(1 - rho^2) / phi
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`ParamError::NonPositiveTheta`] if `theta` is non-finite or
    /// non-positive, [`ParamError::InvalidPhiParameter`] if `phi(theta)` is
    /// non-finite or non-positive, and [`ParamError::NonFinite`],
    /// [`ParamError::NonPositiveSigma`], or
    /// [`ParamError::NegativeMinVariance`] if the mapped Raw parameters or
    /// their validated derived invariants are not representable.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::surface::ssvi::{Phi, Ssvi};
    ///
    /// let ssvi = Ssvi::new(-0.3, Phi::modified_power_law(0.5, 0.5)?)?;
    /// let raw = ssvi.slice_at(0.04)?;
    /// // The raw slice reproduces the SSVI total variance.
    /// let direct = ssvi.total_variance(0.1, 0.04);
    /// assert!((raw.total_variance(0.1) - direct).abs() < 1e-12);
    /// # Ok(())
    /// # }
    /// ```
    pub fn slice_at(&self, theta: f64) -> Result<RawSvi, ParamError> {
        if theta <= 0.0 || !theta.is_finite() {
            return Err(ParamError::NonPositiveTheta { theta });
        }
        let phi = self.phi.eval(theta);
        if phi <= 0.0 || !phi.is_finite() {
            return Err(ParamError::InvalidPhiParameter {
                name: "phi(theta)",
                value: phi,
            });
        }
        let one_minus_rho2 = 1.0 - self.rho * self.rho;
        let a = (theta / 2.0) * one_minus_rho2;
        let b = theta * phi / 2.0;
        let m = -self.rho / phi;
        let sigma = one_minus_rho2.sqrt() / phi;
        RawSvi::new(a, b, self.rho, m, sigma)
    }

    /// Tests the SSVI sufficient no-butterfly-arbitrage condition at one
    /// `theta` (Gatheral & Jacquier 2014, Theorem 4.2).
    ///
    /// The slice at `theta` is free of butterfly arbitrage if both hold:
    ///
    /// ```text
    /// theta * phi      * (1 + |rho|) < 4
    /// theta * phi^2    * (1 + |rho|) <= 4
    /// ```
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::surface::ssvi::{Phi, Ssvi};
    ///
    /// let ssvi = Ssvi::new(-0.3, Phi::modified_power_law(0.5, 0.5)?)?;
    /// assert_eq!(ssvi.butterfly_assessment_at(0.04).status(), regit_svi::ArbitrageStatus::NoViolationDetected);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn butterfly_assessment_at(&self, theta: f64) -> ArbitrageAssessment {
        let evidence = ArbitrageEvidence::AnalyticSufficient {
            theorem: "Gatheral–Jacquier Theorem 4.2",
        };
        if theta <= 0.0 || !theta.is_finite() {
            return ArbitrageAssessment::new(
                ArbitrageStatus::Indeterminate,
                evidence,
                f64::NAN,
                None,
            );
        }
        let phi = self.phi.eval(theta);
        if phi <= 0.0 || !phi.is_finite() {
            return ArbitrageAssessment::new(
                ArbitrageStatus::Indeterminate,
                evidence,
                f64::NAN,
                None,
            );
        }
        let factor = 1.0 + self.rho.abs();
        let tp = theta * phi;
        let first = tp * factor;
        let second = tp * phi * factor;
        let margin = (4.0 - first).min(4.0 - second);
        let boundary_band = 128.0 * f64::EPSILON * (1.0 + first.abs().max(second.abs()).max(4.0));
        let status = if 4.0 - first > boundary_band && 4.0 - second > boundary_band {
            ArbitrageStatus::NoViolationDetected
        } else {
            ArbitrageStatus::Indeterminate
        };
        ArbitrageAssessment::new(status, evidence, margin, None)
    }

    /// Tests the SSVI sufficient no-butterfly condition across a set of
    /// `theta` values (Gatheral & Jacquier 2014, Theorem 4.2).
    ///
    /// Every supplied value is checked. This is a conclusion only on the
    /// declared set of `theta` values, not between them or beyond them.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::surface::ssvi::{Phi, Ssvi};
    ///
    /// let ssvi = Ssvi::new(-0.3, Phi::modified_power_law(0.5, 0.5)?)?;
    /// assert_eq!(ssvi.butterfly_assessment(&[0.01, 0.04, 0.09]).status(), regit_svi::ArbitrageStatus::NoViolationDetected);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn butterfly_assessment(&self, thetas: &[f64]) -> ArbitrageAssessment {
        if thetas.is_empty() {
            return ArbitrageAssessment::new(
                ArbitrageStatus::Indeterminate,
                ArbitrageEvidence::AnalyticSufficient {
                    theorem: "Gatheral–Jacquier Theorem 4.2 on declared theta support",
                },
                f64::NAN,
                None,
            );
        }
        let mut margin = f64::INFINITY;
        for &theta in thetas {
            let assessment = self.butterfly_assessment_at(theta);
            margin = margin.min(assessment.margin());
            if assessment.status() != ArbitrageStatus::NoViolationDetected {
                return ArbitrageAssessment::new(
                    ArbitrageStatus::Indeterminate,
                    assessment.evidence(),
                    margin,
                    None,
                );
            }
        }
        ArbitrageAssessment::new(
            ArbitrageStatus::NoViolationDetected,
            ArbitrageEvidence::AnalyticSufficient {
                theorem: "Gatheral–Jacquier Theorem 4.2 on declared theta support",
            },
            margin,
            None,
        )
    }

    /// Assesses the global positive-theta Theorem 4.2 envelope for the
    /// supported smoothing family.
    ///
    /// Passing is analytic sufficient evidence. Failing a sufficient envelope
    /// is [`ArbitrageStatus::Indeterminate`], never a detected violation.
    #[must_use]
    pub fn global_butterfly_assessment(&self) -> ArbitrageAssessment {
        let evidence = ArbitrageEvidence::AnalyticSufficient {
            theorem: "Gatheral–Jacquier Theorem 4.2 global family envelope",
        };
        let c = 1.0 + self.rho.abs();
        let margin = if let Some(lambda) = self.phi.heston_lambda() {
            lambda - c / 4.0
        } else if let Some((eta, gamma)) = self.phi.modified_power_law_parameters() {
            if gamma > 0.5 {
                return ArbitrageAssessment::new(
                    ArbitrageStatus::Indeterminate,
                    evidence,
                    f64::NEG_INFINITY,
                    None,
                );
            }
            let h_gamma = if (gamma - 0.5).abs() <= 64.0 * f64::EPSILON {
                1.0
            } else {
                let x = 1.0 - 2.0 * gamma;
                x.powf(x) / (2.0 - 2.0 * gamma).powf(2.0 - 2.0 * gamma)
            };
            (4.0 / c).min(2.0 / (c * h_gamma).sqrt()) - eta
        } else {
            f64::NAN
        };
        let boundary_band = 128.0
            * f64::EPSILON
            * (1.0
                + margin.abs()
                + self
                    .phi
                    .heston_lambda()
                    .unwrap_or_else(|| {
                        self.phi
                            .modified_power_law_parameters()
                            .map_or(0.0, |(eta, _)| eta)
                    })
                    .abs());
        let status = if margin > boundary_band {
            ArbitrageStatus::NoViolationDetected
        } else {
            ArbitrageStatus::Indeterminate
        };
        ArbitrageAssessment::new(status, evidence, margin, None)
    }

    /// Tests the SSVI no-calendar-spread-arbitrage condition at one `theta`
    /// (Gatheral & Jacquier 2014, Theorem 4.1, condition (ii)).
    ///
    /// Given a non-decreasing `theta_t` curve, the surface is calendar-free
    /// if, for every `theta`,
    ///
    /// ```text
    /// 0 <= d(theta * phi)/d(theta)
    ///        <= (1/rho^2) * (1 + sqrt(1 - rho^2)) * phi
    /// ```
    ///
    /// The upper bound is `+infinity` when `rho = 0`. For both supported phi
    /// families the derivative inequalities hold globally on `theta > 0` by
    /// direct differentiation; no finite theta sampling is used as a proof.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::surface::ssvi::{Phi, Ssvi};
    ///
    /// let ssvi = Ssvi::new(-0.3, Phi::modified_power_law(0.5, 0.5)?)?;
    /// assert_eq!(ssvi.calendar_assessment(&[0.04]).status(), regit_svi::ArbitrageStatus::NoViolationDetected);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    fn calendar_condition_at(&self, theta: f64) -> bool {
        if theta <= 0.0 || !theta.is_finite() {
            return false;
        }
        match self.phi.0 {
            PhiKind::ModifiedPowerLaw { gamma, .. } => {
                // d(theta*phi)/dtheta = phi*(1-gamma)/(1+theta), whose
                // ratio to phi lies in (0,1). The theorem's upper multiplier
                // is at least one for every |rho|<1.
                gamma > 0.0 && gamma < 1.0
            }
            PhiKind::Heston { lambda } => {
                // The Heston-like form is the admissible family constructed
                // in Gatheral–Jacquier §4.1; validated lambda>0 satisfies the
                // derivative condition globally.
                lambda > 0.0
            }
        }
    }

    /// Tests the SSVI no-calendar condition across a set of `theta` values
    /// (Gatheral & Jacquier 2014, Theorem 4.1).
    ///
    /// Verifies condition (i) — `theta_t` non-decreasing — on the supplied
    /// sequence, then condition (ii) at each `theta`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::surface::ssvi::{Phi, Ssvi};
    ///
    /// let ssvi = Ssvi::new(-0.3, Phi::modified_power_law(0.5, 0.5)?)?;
    /// assert_eq!(ssvi.calendar_assessment(&[0.01, 0.04, 0.09]).status(), regit_svi::ArbitrageStatus::NoViolationDetected);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn calendar_assessment(&self, thetas: &[f64]) -> ArbitrageAssessment {
        const BOUNDARY_TOLERANCE: f64 = 1e-12;
        let evidence = ArbitrageEvidence::AnalyticNecessaryAndSufficient {
            theorem: "Gatheral–Jacquier Theorem 4.1 for supported phi family",
            boundary_tolerance: BOUNDARY_TOLERANCE,
        };
        if thetas.is_empty()
            || thetas
                .iter()
                .any(|theta| !theta.is_finite() || *theta <= 0.0)
        {
            return ArbitrageAssessment::new(
                ArbitrageStatus::Indeterminate,
                evidence,
                f64::NAN,
                None,
            );
        }
        // Condition (i): theta_t non-decreasing in maturity order.
        let mut calendar_margin = f64::INFINITY;
        for pair in thetas.windows(2) {
            let difference = pair[1] - pair[0];
            calendar_margin = calendar_margin.min(difference);
            if difference < -BOUNDARY_TOLERANCE {
                return ArbitrageAssessment::new(
                    ArbitrageStatus::ViolationDetected,
                    evidence,
                    difference,
                    None,
                );
            }
            if difference < 0.0 {
                return ArbitrageAssessment::new(
                    ArbitrageStatus::Indeterminate,
                    evidence,
                    difference,
                    None,
                );
            }
        }
        // Condition (ii): the slope bound at every theta.
        if thetas
            .iter()
            .all(|&theta| self.calendar_condition_at(theta))
        {
            ArbitrageAssessment::new(
                ArbitrageStatus::NoViolationDetected,
                evidence,
                calendar_margin,
                None,
            )
        } else {
            ArbitrageAssessment::new(ArbitrageStatus::ViolationDetected, evidence, -0.0, None)
        }
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)] // Validated fixtures use contextual expectations.
mod tests {
    use super::*;

    #[test]
    fn phi_heston_validation() {
        assert!(Phi::heston(1.0).is_ok());
        assert!(Phi::heston(0.0).is_err());
        assert!(Phi::heston(-1.0).is_err());
        assert!(Phi::heston(f64::NAN).is_err());
    }

    #[test]
    fn heston_phi_small_theta_uses_cancellation_free_series() {
        let phi = Phi::heston(1.0).expect("valid test or documentation fixture");
        let value = phi.eval(1e-12);
        assert!(value.is_finite());
        assert!((value - 0.5).abs() < 1e-12);
    }

    #[test]
    fn total_variance_avoids_intermediate_square_overflow() {
        let ssvi = Ssvi::new(0.0, Phi::heston(1.0).expect("valid extreme-value fixture"))
            .expect("valid extreme-value fixture");
        let value = ssvi.total_variance(1e308, 0.04);
        assert!(value.is_finite());
        assert!((value - 9.867_989_404_040_118e305).abs() / value < 1e-14);
    }

    #[test]
    fn total_variance_preserves_near_monotone_wing_correction() {
        let ssvi = Ssvi::new(
            -1.0 + f64::EPSILON,
            Phi::heston(1.0).expect("valid near-wing fixture"),
        )
        .expect("valid near-wing fixture");
        let theta = 0.04;
        let k = 1e8 / ssvi.phi().eval(theta);
        let expected_bracket = 2.220_446_071_454_774e-8;
        let expected = (theta / 2.0) * expected_bracket;
        assert!((ssvi.total_variance(k, theta) - expected).abs() < 1e-23);
    }

    #[test]
    fn empty_butterfly_support_is_indeterminate() {
        let ssvi = Ssvi::new(
            -0.3,
            Phi::modified_power_law(0.5, 0.5).expect("valid test fixture"),
        )
        .expect("valid test fixture");
        assert_eq!(
            ssvi.butterfly_assessment(&[]).status(),
            ArbitrageStatus::Indeterminate
        );
    }

    #[test]
    fn boundary_near_calendar_decrease_is_indeterminate() {
        let ssvi = Ssvi::new(-0.3, Phi::heston(1.0).expect("valid test fixture"))
            .expect("valid test fixture");
        let theta = 0.04_f64;
        let smaller = f64::from_bits(theta.to_bits() - 1);
        let assessment = ssvi.calendar_assessment(&[theta, smaller]);
        assert_eq!(assessment.status(), ArbitrageStatus::Indeterminate);
        assert!(assessment.margin() < 0.0);
    }

    #[test]
    fn material_calendar_decrease_is_a_violation() {
        let ssvi = Ssvi::new(-0.3, Phi::heston(1.0).expect("valid test fixture"))
            .expect("valid test fixture");
        let assessment = ssvi.calendar_assessment(&[0.04, 0.039]);
        assert_eq!(assessment.status(), ArbitrageStatus::ViolationDetected);
    }

    #[test]
    fn phi_power_law_validation() {
        assert!(Phi::modified_power_law(0.5, 0.5).is_ok());
        assert!(Phi::modified_power_law(0.0, 0.5).is_err());
        assert!(Phi::modified_power_law(0.5, 0.0).is_err());
        assert!(Phi::modified_power_law(0.5, 1.0).is_err());
        assert!(Phi::modified_power_law(f64::INFINITY, 0.5).is_err());
    }

    #[test]
    fn phi_eval_positive_and_decreasing() {
        for phi in [
            Phi::heston(1.0).expect("valid test or documentation fixture"),
            Phi::modified_power_law(0.5, 0.5).expect("valid test or documentation fixture"),
        ] {
            let a = phi.eval(0.01);
            let b = phi.eval(0.04);
            let c = phi.eval(0.16);
            assert!(a > 0.0 && b > 0.0 && c > 0.0);
            assert!(a > b && b > c, "phi should be decreasing in theta");
        }
    }

    #[test]
    fn phi_power_law_golden() {
        // phi(1) = eta / (1^gamma * 2^(1-gamma)).
        let p = Phi::modified_power_law(1.0, 0.5).expect("valid test or documentation fixture");
        assert!((p.eval(1.0) - 1.0 / 2.0_f64.sqrt()).abs() < 1e-12);
    }

    #[test]
    fn ssvi_new_validation() {
        let phi = Phi::heston(1.0).expect("valid test or documentation fixture");
        assert!(Ssvi::new(-0.4, phi).is_ok());
        assert!(Ssvi::new(1.0, phi).is_err());
        assert!(Ssvi::new(f64::NAN, phi).is_err());
    }

    #[test]
    fn ssvi_total_variance_atm_zero_rho() {
        // rho = 0, k = 0: w = theta/2 * (1 + 1) = theta.
        let ssvi = Ssvi::new(
            0.0,
            Phi::modified_power_law(0.5, 0.5).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        assert!((ssvi.total_variance(0.0, 0.04) - 0.04).abs() < 1e-15);
    }

    #[test]
    fn slice_at_reproduces_total_variance() {
        let ssvi = Ssvi::new(
            -0.3,
            Phi::modified_power_law(0.5, 0.5).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        let raw = ssvi
            .slice_at(0.04)
            .expect("valid test or documentation fixture");
        for &k in &[-0.5, -0.1, 0.0, 0.1, 0.5] {
            let direct = ssvi.total_variance(k, 0.04);
            assert!((raw.total_variance(k) - direct).abs() < 1e-12, "k = {k}");
        }
    }

    #[test]
    fn slice_at_rejects_non_positive_theta() {
        let ssvi = Ssvi::new(
            -0.3,
            Phi::heston(1.0).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        assert!(matches!(
            ssvi.slice_at(0.0),
            Err(ParamError::NonPositiveTheta { .. })
        ));
    }

    #[test]
    fn slice_at_heston_reproduces_total_variance() {
        let ssvi = Ssvi::new(
            0.2,
            Phi::heston(2.0).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        let raw = ssvi
            .slice_at(0.09)
            .expect("valid test or documentation fixture");
        for &k in &[-0.4, 0.0, 0.4] {
            let direct = ssvi.total_variance(k, 0.09);
            assert!((raw.total_variance(k) - direct).abs() < 1e-12, "k = {k}");
        }
    }

    #[test]
    fn butterfly_free_holds_for_small_eta() {
        // Power-law corollary: eta*(1+|rho|) <= 2 implies butterfly-free.
        let ssvi = Ssvi::new(
            -0.3,
            Phi::modified_power_law(0.5, 0.5).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        assert_eq!(
            ssvi.butterfly_assessment(&[0.01, 0.04, 0.09, 0.25])
                .status(),
            ArbitrageStatus::NoViolationDetected
        );
    }

    #[test]
    fn butterfly_violation_for_large_phi() {
        // A power-law phi with large eta gives huge phi near theta -> 0,
        // which violates Theorem 4.2 (theta*phi^2*(1+|rho|) > 4).
        let ssvi = Ssvi::new(
            0.5,
            Phi::modified_power_law(20.0, 0.9).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        assert_eq!(
            ssvi.butterfly_assessment_at(1e-3).status(),
            ArbitrageStatus::Indeterminate
        );
    }

    #[test]
    fn theorem_42_binary64_boundary_is_indeterminate() {
        let theta = 4.0_f64;
        let gamma = 0.5_f64;
        let boundary_eta = theta.powf(gamma) * (1.0 + theta).powf(1.0 - gamma);
        let boundary = Ssvi::new(
            0.0,
            Phi::modified_power_law(boundary_eta, gamma).expect("positive boundary phi"),
        )
        .expect("valid SSVI");
        assert_eq!(
            boundary.butterfly_assessment_at(theta).status(),
            ArbitrageStatus::Indeterminate
        );

        let interior = Ssvi::new(
            0.0,
            Phi::modified_power_law(boundary_eta * (1.0 - 1024.0 * f64::EPSILON), gamma)
                .expect("strictly interior phi"),
        )
        .expect("valid SSVI");
        assert_eq!(
            interior.butterfly_assessment_at(theta).status(),
            ArbitrageStatus::NoViolationDetected
        );
    }

    #[test]
    fn global_butterfly_envelope_boundary_is_indeterminate() {
        let boundary = Ssvi::new(0.0, Phi::heston(0.25).expect("positive boundary lambda"))
            .expect("valid SSVI");
        assert_eq!(
            boundary.global_butterfly_assessment().status(),
            ArbitrageStatus::Indeterminate
        );
    }

    #[test]
    fn butterfly_free_rejects_bad_theta() {
        let ssvi = Ssvi::new(
            0.0,
            Phi::heston(1.0).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        assert_eq!(
            ssvi.butterfly_assessment_at(0.0).status(),
            ArbitrageStatus::Indeterminate
        );
        assert_eq!(
            ssvi.butterfly_assessment_at(-1.0).status(),
            ArbitrageStatus::Indeterminate
        );
    }

    #[test]
    fn calendar_free_for_monotone_thetas() {
        let ssvi = Ssvi::new(
            -0.3,
            Phi::modified_power_law(0.5, 0.5).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        assert_eq!(
            ssvi.calendar_assessment(&[0.01, 0.04, 0.09]).status(),
            ArbitrageStatus::NoViolationDetected
        );
    }

    #[test]
    fn calendar_arbitrage_for_decreasing_thetas() {
        let ssvi = Ssvi::new(
            -0.3,
            Phi::modified_power_law(0.5, 0.5).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        assert_eq!(
            ssvi.calendar_assessment(&[0.09, 0.04, 0.01]).status(),
            ArbitrageStatus::ViolationDetected
        );
    }

    #[test]
    fn calendar_free_at_zero_rho() {
        let ssvi = Ssvi::new(
            0.0,
            Phi::modified_power_law(0.5, 0.5).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        assert_eq!(
            ssvi.calendar_assessment(&[0.04]).status(),
            ArbitrageStatus::NoViolationDetected
        );
    }
}