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
// Copyright 2026 Regit.io — Nicolas Koenig
// SPDX-License-Identifier: Apache-2.0

//! Multi-slice volatility surface assembly and interpolation.
//!
//! A surface is an ordered set of calibrated slices at maturities
//! `t_1 < ... < t_n`. To evaluate total variance at an arbitrary `(k, T)`:
//!
//! - **Maturity inside the grid.** Locate the bracketing slices
//!   `t_j <= T < t_{j+1}` and interpolate linearly in total variance along
//!   constant `k`:
//!
//!   ```text
//!   w(k, T) = ( (t_{j+1} - T)*w(k, t_j) + (T - t_j)*w(k, t_{j+1}) )
//!             / (t_{j+1} - t_j)
//!   ```
//!
//!   Linear interpolation in `w` is monotone in `T`, so it introduces no
//!   calendar-spread arbitrage provided the bracketing slices are themselves
//!   ordered.
//!
//! - **Maturity outside the grid.** Total variance is extrapolated flat in
//!   implied volatility (constant `sigma_BS` beyond the first / last slice).
//!
//! For an SSVI-backed surface, evaluation is direct from the closed form at
//! the interpolated `theta_T`, and no per-`k` interpolation is needed.
//!
//! # References
//!
//! - Gatheral, J., *The Volatility Surface: A Practitioner's Guide*,
//!   Wiley (2006), Chapter 3.

use crate::error::ParamError;
use crate::no_arb::calendar::calendar_scan;
use crate::no_arb::evidence::{
    ArbitrageAssessment, ArbitrageEvidence, ArbitrageStatus, ScanEvidence,
};
use crate::smile::raw::RawSvi;
use crate::surface::ssvi::Ssvi;
use crate::surface::term_structure::TermStructure;

/// The backing representation of a [`Surface`].
#[derive(Debug, Clone, PartialEq)]
enum Backing {
    /// A set of raw slices, each tagged with its maturity (ascending order).
    Slices(Vec<(f64, RawSvi)>),
    /// An SSVI surface plus its `(maturity, theta)` term structure.
    Ssvi {
        /// The SSVI parametrisation.
        ssvi: Ssvi,
        /// `(maturity, theta)` knots, ascending in maturity.
        term: TermStructure,
    },
}

/// An interpolated volatility surface over validated maturity knots.
///
/// Construction validates maturity order and ATM variance order. Arbitrary
/// Raw slices can still cross away from ATM; use [`Self::calendar_assessment`]
/// for an evidence-bearing bounded diagnostic on a declared range.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use regit_svi::smile::raw::RawSvi;
/// use regit_svi::surface::interpolation::Surface;
///
/// let s1 = RawSvi::new(0.02, 0.3, -0.2, 0.0, 0.1)?;
/// let s2 = RawSvi::new(0.05, 0.3, -0.2, 0.0, 0.1)?;
/// let surface = Surface::from_slices(vec![(0.5, s1), (1.5, s2)])?;
/// // Total variance at an interpolated maturity.
/// let w = surface.total_variance(0.0, 1.0)?;
/// assert!(w > s1.total_variance(0.0) && w < s2.total_variance(0.0));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Surface {
    backing: Backing,
}

impl Surface {
    /// Builds a surface from `(maturity, slice)` pairs.
    ///
    /// Pairs must already be in strictly increasing positive maturity order.
    /// ATM total variance must be non-decreasing; no off-ATM ordering claim is
    /// made at construction.
    ///
    /// # Errors
    ///
    /// - [`ParamError::NonFinite`] if a maturity or slice ATM total variance
    ///   is not finite.
    /// - [`ParamError::NonPositiveMaturity`] if input is empty or a maturity
    ///   is `<= 0`.
    /// - [`ParamError::NotStrictlyIncreasing`] if maturities are duplicated or
    ///   unordered.
    /// - [`ParamError::DecreasingAtmVariance`] if ATM total variance decreases
    ///   between adjacent maturities.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    /// use regit_svi::surface::interpolation::Surface;
    ///
    /// let s = RawSvi::new(0.04, 0.3, -0.2, 0.0, 0.1)?;
    /// assert!(Surface::from_slices(vec![(1.0, s)]).is_ok());
    /// assert!(Surface::from_slices(vec![(0.0, s)]).is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_slices(slices: Vec<(f64, RawSvi)>) -> Result<Self, ParamError> {
        if slices.is_empty() {
            return Err(ParamError::NonPositiveMaturity { t: 0.0 });
        }
        for &(t, slice) in &slices {
            if !t.is_finite() {
                return Err(ParamError::NonFinite { name: "maturity" });
            }
            if t <= 0.0 {
                return Err(ParamError::NonPositiveMaturity { t });
            }
            if !slice.atm_total_variance().is_finite() {
                return Err(ParamError::NonFinite {
                    name: "slice ATM total variance",
                });
            }
        }
        for (index, pair) in slices.windows(2).enumerate() {
            if pair[1].0 <= pair[0].0 {
                return Err(ParamError::NotStrictlyIncreasing {
                    name: "maturity",
                    index: index + 1,
                    previous: pair[0].0,
                    value: pair[1].0,
                });
            }
            let previous = pair[0].1.atm_total_variance();
            let value = pair[1].1.atm_total_variance();
            if value < previous {
                return Err(ParamError::DecreasingAtmVariance {
                    index: index + 1,
                    previous,
                    value,
                });
            }
        }
        Ok(Self {
            backing: Backing::Slices(slices),
        })
    }

    /// Builds a surface from an SSVI parametrisation and its `(maturity,
    /// theta)` term structure.
    ///
    /// The term structure must already be in ascending maturity order, with
    /// non-decreasing `theta`.
    ///
    /// # Errors
    ///
    /// Converts raw knots or accepts an already validated [`TermStructure`].
    /// Propagates any [`ParamError`] produced during conversion, then returns
    /// [`ParamError::InvalidPhiParameter`], [`ParamError::NonFinite`],
    /// [`ParamError::NonPositiveSigma`], or
    /// [`ParamError::NegativeMinVariance`] if SSVI-to-Raw mapping at a theta
    /// knot is not representable.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::surface::ssvi::{Phi, Ssvi};
    /// use regit_svi::surface::interpolation::Surface;
    ///
    /// let ssvi = Ssvi::new(-0.3, Phi::modified_power_law(0.5, 0.5)?)?;
    /// let surface = Surface::from_ssvi(ssvi, vec![(0.5, 0.02), (1.0, 0.04)])?;
    /// assert!(surface.total_variance(0.0, 0.75)? > 0.0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_ssvi<T>(ssvi: Ssvi, term: T) -> Result<Self, ParamError>
    where
        T: TryInto<TermStructure>,
        ParamError: From<T::Error>,
    {
        let term = term.try_into().map_err(ParamError::from)?;
        for &(_, theta) in term.knots() {
            ssvi.slice_at(theta.get())?;
        }
        Ok(Self {
            backing: Backing::Ssvi { ssvi, term },
        })
    }

    /// The number of maturity knots in the surface.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    /// use regit_svi::surface::interpolation::Surface;
    ///
    /// let s = RawSvi::new(0.04, 0.3, -0.2, 0.0, 0.1)?;
    /// let surface = Surface::from_slices(vec![(0.5, s), (1.0, s)])?;
    /// assert_eq!(surface.len(), 2);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        match &self.backing {
            Backing::Slices(s) => s.len(),
            Backing::Ssvi { term, .. } => term.len(),
        }
    }

    /// Returns `true` if the surface has no maturity knots.
    ///
    /// A [`Surface`] is always constructed with at least one knot, so this
    /// returns `false` for every value built through the public constructors.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    /// use regit_svi::surface::interpolation::Surface;
    ///
    /// let s = RawSvi::new(0.04, 0.3, -0.2, 0.0, 0.1)?;
    /// let surface = Surface::from_slices(vec![(1.0, s)])?;
    /// assert!(!surface.is_empty());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Total implied variance `w(k, T)` at log-moneyness `k` and maturity `T`.
    ///
    /// Inside the maturity grid the value is linearly interpolated in total
    /// variance; outside it the implied volatility is held flat (constant
    /// `sigma_BS`). An SSVI-backed surface evaluates the closed form at the
    /// interpolated `theta`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    /// use regit_svi::surface::interpolation::Surface;
    ///
    /// let s1 = RawSvi::new(0.02, 0.3, -0.2, 0.0, 0.1)?;
    /// let s2 = RawSvi::new(0.05, 0.3, -0.2, 0.0, 0.1)?;
    /// let surface = Surface::from_slices(vec![(0.5, s1), (1.5, s2)])?;
    /// // Midpoint maturity -> midpoint total variance at constant k.
    /// let mid = surface.total_variance(0.0, 1.0)?;
    /// let expect = 0.5 * (s1.total_variance(0.0) + s2.total_variance(0.0));
    /// assert!((mid - expect).abs() < 1e-12);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`ParamError::NonFinite`] for non-finite log-moneyness or a
    /// non-finite evaluated total variance. Returns
    /// [`ParamError::NonPositiveMaturity`] unless `T` is finite and positive.
    pub fn total_variance(&self, k: f64, t: f64) -> Result<f64, ParamError> {
        if !k.is_finite() {
            return Err(ParamError::NonFinite {
                name: "log_moneyness",
            });
        }
        if t <= 0.0 || !t.is_finite() {
            return Err(ParamError::NonPositiveMaturity { t });
        }
        let value = match &self.backing {
            Backing::Slices(slices) => Self::total_variance_slices(slices, k, t),
            Backing::Ssvi { ssvi, term } => {
                let theta = interpolate_theta(term.knots(), t);
                ssvi.total_variance(k, theta)
            }
        };
        if value.is_finite() {
            Ok(value)
        } else {
            Err(ParamError::NonFinite {
                name: "total_variance",
            })
        }
    }

    /// Black implied volatility `sigma_BS(k, T) = sqrt(w(k, T) / T)`.
    ///
    /// # Errors
    ///
    /// Returns [`ParamError::NonPositiveMaturity`] if `T` is non-finite or
    /// non-positive. Propagates [`ParamError::NonFinite`] from total-variance
    /// evaluation for non-finite `k` or output, and returns it if the final
    /// implied volatility is non-finite.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    /// use regit_svi::surface::interpolation::Surface;
    ///
    /// let s = RawSvi::new(0.04, 0.0, 0.0, 0.0, 0.1)?;
    /// let surface = Surface::from_slices(vec![(1.0, s)])?;
    /// // Flat w = 0.04 at t = 1 -> vol = 0.2.
    /// assert!((surface.implied_vol(0.0, 1.0)? - 0.2).abs() < 1e-12);
    /// # Ok(())
    /// # }
    /// ```
    pub fn implied_vol(&self, k: f64, t: f64) -> Result<f64, ParamError> {
        if t <= 0.0 || !t.is_finite() {
            return Err(ParamError::NonPositiveMaturity { t });
        }
        let volatility = (self.total_variance(k, t)? / t).sqrt();
        if volatility.is_finite() {
            Ok(volatility)
        } else {
            Err(ParamError::NonFinite {
                name: "implied_volatility",
            })
        }
    }

    /// Assesses calendar-spread arbitrage across adjacent maturity knots.
    ///
    /// For a slice-backed surface, runs the [`calendar_scan`] on every
    /// adjacent pair over `[k_lo, k_hi]`. For Raw slices, a clean status carries
    /// [`ArbitrageEvidence::NumericalScan`] and means only that no violation was
    /// sampled on the expanded bounded grid. For an SSVI-backed surface, the
    /// analytic Theorem 4.1 assessment is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    /// use regit_svi::surface::interpolation::Surface;
    ///
    /// let s1 = RawSvi::new(0.02, 0.3, -0.2, 0.0, 0.1)?;
    /// let s2 = RawSvi::new(0.05, 0.3, -0.2, 0.0, 0.1)?;
    /// let surface = Surface::from_slices(vec![(0.5, s1), (1.5, s2)])?;
    /// let assessment = surface.calendar_assessment(-0.5, 0.5)?;
    /// assert_eq!(assessment.status(), regit_svi::ArbitrageStatus::NoViolationDetected);
    /// assert!(matches!(assessment.evidence(), regit_svi::ArbitrageEvidence::NumericalScan(_)));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`crate::DiagnosticError::NonFiniteBound`] for non-finite
    /// bounds, [`crate::DiagnosticError::InvalidOrder`] unless `k_lo < k_hi`,
    /// and, for slice-backed multi-tenor scans,
    /// [`crate::DiagnosticError::DomainOverflow`] or
    /// [`crate::DiagnosticError::NonFiniteEvaluation`] when interval expansion
    /// or evaluation is not finite.
    pub fn calendar_assessment(
        &self,
        k_lo: f64,
        k_hi: f64,
    ) -> Result<ArbitrageAssessment, crate::DiagnosticError> {
        if !k_lo.is_finite() || !k_hi.is_finite() {
            return Err(crate::DiagnosticError::NonFiniteBound);
        }
        if k_lo >= k_hi {
            return Err(crate::DiagnosticError::InvalidOrder);
        }
        match &self.backing {
            Backing::Slices(slices) => {
                if slices.len() == 1 {
                    return Ok(ArbitrageAssessment::new(
                        ArbitrageStatus::NoViolationDetected,
                        ArbitrageEvidence::AnalyticNecessaryAndSufficient {
                            theorem: "single-maturity calendar ordering is vacuous",
                            boundary_tolerance: 0.0,
                        },
                        f64::INFINITY,
                        None,
                    ));
                }
                let mut selected_minimum = f64::INFINITY;
                let mut witness = None;
                let mut scan_evidence = None;
                let mut total_samples = 0_usize;
                let mut selected_scan = 0_usize;
                let mut selected_priority = 0_u8;
                let mut selected_score = f64::INFINITY;
                let mut violation_observed = false;
                let mut boundary_unresolved = false;
                for (pair_index, pair) in slices.windows(2).enumerate() {
                    let diagnostic = calendar_scan(&pair[0].1, &pair[1].1, k_lo, k_hi)?;
                    total_samples =
                        total_samples.saturating_add(diagnostic.evidence().samples_evaluated());
                    violation_observed |= diagnostic.violation_observed();
                    boundary_unresolved |=
                        diagnostic.min_difference() <= diagnostic.evidence().config().tolerance();
                    let tolerance = diagnostic.evidence().config().tolerance();
                    let (priority, score) = calendar_scan_rank(
                        diagnostic.violation_observed(),
                        diagnostic.min_difference(),
                        tolerance,
                    );
                    if scan_evidence.is_none()
                        || priority > selected_priority
                        || (priority == selected_priority && score < selected_score)
                    {
                        selected_priority = priority;
                        selected_score = score;
                        selected_minimum = diagnostic.min_difference();
                        witness = Some(diagnostic.worst_k());
                        scan_evidence = Some(diagnostic.evidence());
                        selected_scan = pair_index;
                    }
                }
                let evidence = scan_evidence.map_or_else(
                    || ArbitrageEvidence::AnalyticNecessaryAndSufficient {
                        theorem: "single-maturity calendar ordering is vacuous",
                        boundary_tolerance: 0.0,
                    },
                    |scan| {
                        ArbitrageEvidence::NumericalScan(ScanEvidence::aggregate_selected(
                            scan,
                            slices.len().saturating_sub(1),
                            total_samples,
                            selected_scan,
                        ))
                    },
                );
                let status = if violation_observed {
                    ArbitrageStatus::ViolationDetected
                } else if boundary_unresolved {
                    ArbitrageStatus::Indeterminate
                } else {
                    ArbitrageStatus::NoViolationDetected
                };
                Ok(ArbitrageAssessment::new(
                    status,
                    evidence,
                    selected_minimum,
                    witness,
                ))
            }
            Backing::Ssvi { ssvi, term } => {
                let thetas: Vec<f64> = term.knots().iter().map(|&(_, theta)| theta.get()).collect();
                Ok(ssvi.calendar_assessment(&thetas))
            }
        }
    }

    /// Evaluates a slice-backed surface at `(k, t)` with maturity
    /// interpolation and flat-vol extrapolation.
    fn total_variance_slices(slices: &[(f64, RawSvi)], k: f64, t: f64) -> f64 {
        let n = slices.len();
        let (t0, first) = slices[0];
        let (tn, last) = slices[n - 1];

        if t <= t0 {
            // Flat implied volatility below the first maturity:
            // w(k, t) = (w(k, t0) / t0) * t.
            return (first.total_variance(k) / t0) * t.max(0.0);
        }
        if t >= tn {
            // Flat implied volatility above the last maturity.
            return (last.total_variance(k) / tn) * t;
        }

        // Bracketing slices t_j <= t < t_{j+1}; linear interpolation in w.
        for pair in slices.windows(2) {
            let (tj, sj) = pair[0];
            let (tj1, sj1) = pair[1];
            if t >= tj && t <= tj1 {
                let wj = sj.total_variance(k);
                let wj1 = sj1.total_variance(k);
                let frac = (t - tj) / (tj1 - tj);
                return wj + frac * (wj1 - wj);
            }
        }
        // Constructors enforce a non-empty, strictly ordered grid, so this is
        // reachable only through a floating-point comparison anomaly. Keep a
        // finite model value without introducing a panic into the library.
        last.total_variance(k)
    }
}

/// Orders adjacent-pair scans by semantic status, then normalized adversity.
fn calendar_scan_rank(violation: bool, minimum: f64, tolerance: f64) -> (u8, f64) {
    let priority = if violation {
        2
    } else {
        u8::from(minimum <= tolerance)
    };
    (priority, minimum / tolerance)
}

/// Interpolates the `theta` term structure at maturity `t`.
///
/// Linear interpolation between adjacent `(maturity, theta)` knots, with flat
/// extrapolation of `theta / t` (constant ATM implied variance) outside the
/// grid.
fn interpolate_theta(
    term: &[(
        crate::market::units::Maturity,
        crate::market::units::TotalVariance,
    )],
    t: f64,
) -> f64 {
    let n = term.len();
    let (t_first, theta_first) = (term[0].0.get(), term[0].1.get());
    let (t_last, theta_last) = (term[n - 1].0.get(), term[n - 1].1.get());

    if t <= t_first {
        return (theta_first / t_first) * t.max(0.0);
    }
    if t >= t_last {
        return (theta_last / t_last) * t;
    }
    for pair in term.windows(2) {
        let (t_lo, theta_lo) = (pair[0].0.get(), pair[0].1.get());
        let (t_hi, theta_hi) = (pair[1].0.get(), pair[1].1.get());
        if t >= t_lo && t <= t_hi {
            let frac = (t - t_lo) / (t_hi - t_lo);
            return theta_lo + frac * (theta_hi - theta_lo);
        }
    }
    theta_last
}

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

    #[test]
    fn from_slices_requires_explicit_order() {
        let s =
            RawSvi::new(0.04, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        assert!(Surface::from_slices(vec![(2.0, s), (0.5, s), (1.0, s)]).is_err());
        let surface = Surface::from_slices(vec![(0.5, s), (1.0, s), (2.0, s)])
            .expect("valid test or documentation fixture");
        assert_eq!(surface.len(), 3);
    }

    #[test]
    fn from_slices_rejects_bad_maturity() {
        let s =
            RawSvi::new(0.04, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        assert!(Surface::from_slices(vec![(0.0, s)]).is_err());
        assert!(Surface::from_slices(vec![(1.0, s), (1.0, s)]).is_err());
        assert!(Surface::from_slices(vec![]).is_err());
    }

    #[test]
    fn from_slices_rejects_non_finite_atm_evaluation_defensively() {
        let overflow = RawSvi::new_unchecked(0.0, f64::MAX, 0.0, -f64::MAX, f64::MIN_POSITIVE);
        assert!(matches!(
            Surface::from_slices(vec![(1.0, overflow)]),
            Err(ParamError::NonFinite {
                name: "slice ATM total variance"
            })
        ));
    }

    #[test]
    fn interpolation_is_linear_in_w() {
        let s1 =
            RawSvi::new(0.02, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        let s2 =
            RawSvi::new(0.06, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        let surface = Surface::from_slices(vec![(1.0, s1), (3.0, s2)])
            .expect("valid test or documentation fixture");
        // At t = 2 (midpoint), w is the average at every k.
        for &k in &[-0.3, 0.0, 0.3] {
            let mid = surface
                .total_variance(k, 2.0)
                .expect("positive finite maturity");
            let expect = 0.5 * (s1.total_variance(k) + s2.total_variance(k));
            assert!((mid - expect).abs() < 1e-12, "k = {k}");
        }
    }

    #[test]
    fn interpolation_recovers_knot_values() {
        let s1 =
            RawSvi::new(0.02, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        let s2 =
            RawSvi::new(0.06, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        let surface = Surface::from_slices(vec![(1.0, s1), (3.0, s2)])
            .expect("valid test or documentation fixture");
        assert!(
            (surface
                .total_variance(0.1, 1.0)
                .expect("positive finite maturity")
                - s1.total_variance(0.1))
            .abs()
                < 1e-12
        );
        assert!(
            (surface
                .total_variance(0.1, 3.0)
                .expect("positive finite maturity")
                - s2.total_variance(0.1))
            .abs()
                < 1e-12
        );
    }

    #[test]
    fn extrapolation_is_flat_in_vol() {
        let s =
            RawSvi::new(0.04, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        let surface =
            Surface::from_slices(vec![(1.0, s)]).expect("valid test or documentation fixture");
        // Below: w(k, 0.5) = w(k, 1) * 0.5 (constant vol).
        let w_half = surface
            .total_variance(0.0, 0.5)
            .expect("positive finite maturity");
        assert!((w_half - s.total_variance(0.0) * 0.5).abs() < 1e-12);
        // Above: w(k, 2) = w(k, 1) * 2.
        let w_double = surface
            .total_variance(0.0, 2.0)
            .expect("positive finite maturity");
        assert!((w_double - s.total_variance(0.0) * 2.0).abs() < 1e-12);
        // Implied vol is constant across extrapolated maturities.
        let v05 = surface
            .implied_vol(0.0, 0.5)
            .expect("valid test or documentation fixture");
        let v20 = surface
            .implied_vol(0.0, 2.0)
            .expect("valid test or documentation fixture");
        assert!((v05 - v20).abs() < 1e-12);
    }

    #[test]
    fn implied_vol_rejects_bad_maturity() {
        let s =
            RawSvi::new(0.04, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        let surface =
            Surface::from_slices(vec![(1.0, s)]).expect("valid test or documentation fixture");
        assert!(surface.implied_vol(0.0, 0.0).is_err());
        assert!(surface.total_variance(0.0, -1.0).is_err());
        assert!(surface.total_variance(0.0, f64::NAN).is_err());
        assert!(surface.total_variance(f64::NAN, 1.0).is_err());
        assert!(match surface.implied_vol(0.0, f64::MIN_POSITIVE) {
            Ok(value) => value.is_finite(),
            Err(_) => true,
        });
    }

    #[test]
    fn slice_surface_calendar_check() {
        let early =
            RawSvi::new(0.02, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        let late =
            RawSvi::new(0.06, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        let ok = Surface::from_slices(vec![(0.5, early), (1.5, late)])
            .expect("valid test or documentation fixture");
        assert!(
            ok.calendar_assessment(-0.5, 0.5)
                .expect("finite diagnostic bounds")
                .status()
                == ArbitrageStatus::NoViolationDetected
        );
        // A decreasing ATM term structure is rejected at construction.
        assert!(Surface::from_slices(vec![(0.5, late), (1.5, early)]).is_err());
    }

    #[test]
    fn single_slice_calendar_assessment_validates_declared_bounds() {
        let slice = RawSvi::new(0.04, 0.1, 0.0, 0.0, 0.2).expect("valid fixture");
        let surface = Surface::from_slices(vec![(1.0, slice)]).expect("valid surface");
        assert_eq!(
            surface.calendar_assessment(f64::NAN, 1.0),
            Err(crate::DiagnosticError::NonFiniteBound)
        );
        assert_eq!(
            surface.calendar_assessment(1.0, -1.0),
            Err(crate::DiagnosticError::InvalidOrder)
        );
    }

    #[test]
    fn roundoff_scale_calendar_crossing_is_indeterminate() {
        let slope = f64::EPSILON;
        let early = RawSvi::new(0.04 - slope * 0.1, slope, 0.0, 0.0, 0.1)
            .expect("valid almost-flat early slice");
        let late = RawSvi::new(0.04, 0.0, 0.0, 0.0, 0.1).expect("valid flat late slice");
        let surface = Surface::from_slices(vec![(1.0, early), (2.0, late)])
            .expect("equal finite ATM anchors");
        assert_eq!(
            surface
                .calendar_assessment(-1.0, 1.0)
                .expect("valid bounded diagnostic")
                .status(),
            ArbitrageStatus::Indeterminate
        );
    }

    #[test]
    fn raw_surface_calendar_scan_is_explicitly_bounded() {
        let early =
            RawSvi::new(0.02, 0.5, 0.0, 0.0, 0.1).expect("valid hidden-wing-crossing fixture");
        let late =
            RawSvi::new(1.0, 0.1, 0.0, 0.0, 0.1).expect("valid hidden-wing-crossing fixture");
        let surface = Surface::from_slices(vec![(0.5, early), (1.5, late)])
            .expect("ATM-ordered maturity knots");
        assert!(
            surface
                .calendar_assessment(-1.0, 1.0)
                .expect("finite diagnostic bounds")
                .status()
                == ArbitrageStatus::NoViolationDetected
        );
        assert!(
            surface
                .calendar_assessment(-3.0, 3.0)
                .expect("finite diagnostic bounds")
                .status()
                == ArbitrageStatus::ViolationDetected
        );
    }

    #[test]
    fn aggregated_calendar_evidence_separates_selected_and_total_scope() {
        let first = RawSvi::new(0.02, 0.1, 0.0, 0.0, 0.2).expect("valid fixture");
        let second = RawSvi::new(0.05, 0.1, 0.0, 0.0, 0.2).expect("valid fixture");
        let third = RawSvi::new(0.09, 0.1, 0.0, 0.0, 0.2).expect("valid fixture");
        let surface = Surface::from_slices(vec![(0.5, first), (1.0, second), (2.0, third)])
            .expect("ordered surface");
        let assessment = surface
            .calendar_assessment(-1.0, 1.0)
            .expect("finite diagnostic");
        let evidence = assessment.evidence();
        assert!(matches!(evidence, ArbitrageEvidence::NumericalScan(_)));
        let ArbitrageEvidence::NumericalScan(evidence) = evidence else {
            return;
        };
        assert_eq!(evidence.scan_count(), 2);
        assert_eq!(evidence.samples_evaluated(), 401);
        assert_eq!(evidence.total_samples_evaluated(), 802);
        assert!(evidence.selected_scan() < evidence.scan_count());
    }

    #[test]
    fn aggregate_selects_material_violation_over_more_negative_unresolved_pair() {
        let sigma = 0.1_f64;
        let small_slope = 1e-8_f64;
        let first = RawSvi::new(
            small_slope.mul_add(-sigma, 1.0),
            small_slope,
            0.0,
            0.0,
            sigma,
        )
        .expect("small-scale curved fixture");
        let second = RawSvi::new(1.0, 0.0, 0.0, 0.0, sigma).expect("small-scale flat fixture");
        let large_level = 1e8_f64;
        let large_slope = 5e-8_f64;
        let third = RawSvi::new(
            large_slope.mul_add(-sigma, large_level),
            large_slope,
            0.0,
            0.0,
            sigma,
        )
        .expect("large-scale curved fixture");
        let fourth =
            RawSvi::new(large_level, 0.0, 0.0, 0.0, sigma).expect("large-scale flat fixture");
        let surface = Surface::from_slices(vec![
            (0.5, first),
            (1.0, second),
            (1.5, third),
            (2.0, fourth),
        ])
        .expect("ATM-ordered scale-separated surface");
        let assessment = surface
            .calendar_assessment(-1.0, 1.0)
            .expect("finite diagnostic");
        assert_eq!(assessment.status(), ArbitrageStatus::ViolationDetected);
        let evidence = assessment.evidence();
        assert!(matches!(evidence, ArbitrageEvidence::NumericalScan(_)));
        let ArbitrageEvidence::NumericalScan(evidence) = evidence else {
            return;
        };
        assert_eq!(evidence.scan_count(), 3);
        assert_eq!(evidence.selected_scan(), 0);
        assert!(assessment.margin() < -evidence.config().tolerance());
        assert!(evidence.refinement_attempted());
    }

    #[test]
    fn ssvi_surface_evaluates_and_interpolates() {
        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 surface = Surface::from_ssvi(ssvi, vec![(0.5, 0.02), (1.0, 0.04), (2.0, 0.08)])
            .expect("valid test or documentation fixture");
        // At a knot maturity, theta is exact.
        let w_knot = surface
            .total_variance(0.1, 1.0)
            .expect("positive finite maturity");
        assert!((w_knot - ssvi.total_variance(0.1, 0.04)).abs() < 1e-12);
        // Interpolated maturity is between bracketing values.
        let w_mid = surface
            .total_variance(0.0, 1.5)
            .expect("positive finite maturity");
        assert!(w_mid > ssvi.total_variance(0.0, 0.04));
        assert!(w_mid < ssvi.total_variance(0.0, 0.08));
    }

    #[test]
    fn from_ssvi_rejects_non_finite_slice_mapping() {
        let ssvi = Ssvi::new(
            0.0,
            Phi::heston(f64::MAX).expect("finite positive phi parameter"),
        )
        .expect("valid SSVI correlation");
        assert!(matches!(
            Surface::from_ssvi(ssvi, vec![(1.0, f64::MAX)]),
            Err(ParamError::InvalidPhiParameter {
                name: "phi(theta)",
                ..
            })
        ));
    }

    #[test]
    fn ssvi_surface_calendar_check() {
        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 surface = Surface::from_ssvi(ssvi, vec![(0.5, 0.02), (1.0, 0.04), (2.0, 0.08)])
            .expect("valid test or documentation fixture");
        assert!(
            surface
                .calendar_assessment(-0.5, 0.5)
                .expect("finite diagnostic bounds")
                .status()
                == ArbitrageStatus::NoViolationDetected
        );
        assert_eq!(
            surface.calendar_assessment(f64::NAN, 1.0),
            Err(crate::DiagnosticError::NonFiniteBound)
        );
        assert_eq!(
            surface.calendar_assessment(1.0, 1.0),
            Err(crate::DiagnosticError::InvalidOrder)
        );
    }

    #[test]
    fn ssvi_surface_rejects_bad_term() {
        let ssvi = Ssvi::new(
            -0.3,
            Phi::heston(1.0).expect("valid test or documentation fixture"),
        )
        .expect("valid test or documentation fixture");
        assert!(Surface::from_ssvi(ssvi, vec![]).is_err());
        assert!(Surface::from_ssvi(ssvi, vec![(1.0, 0.0)]).is_err());
        assert!(Surface::from_ssvi(ssvi, vec![(0.0, 0.04)]).is_err());
    }

    #[test]
    fn is_empty_is_false_for_built_surface() {
        let s =
            RawSvi::new(0.04, 0.3, -0.2, 0.0, 0.1).expect("valid test or documentation fixture");
        let surface =
            Surface::from_slices(vec![(1.0, s)]).expect("valid test or documentation fixture");
        assert!(!surface.is_empty());
    }
}