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

//! Raw SVI parametrisation of a single maturity slice.
//!
//! The raw SVI parametrisation expresses the total implied variance of one
//! slice as
//!
//! ```text
//! w(k) = a + b * ( rho * (k - m) + sqrt( (k - m)^2 + sigma^2 ) )
//! ```
//!
//! with five parameters `{a, b, rho, m, sigma}`:
//!
//! | Parameter | Domain      | Role                                    |
//! |-----------|-------------|-----------------------------------------|
//! | `a`       | `a in R`    | Vertical translation — variance level   |
//! | `b`       | `b >= 0`    | Slope of the wings                      |
//! | `rho`     | `|rho| < 1` | Counter-clockwise rotation — skew       |
//! | `m`       | `m in R`    | Horizontal translation — shifts smile   |
//! | `sigma`   | `sigma > 0` | ATM curvature — vertex smoothness       |
//!
//! Writing `u = k - m` and `r = sqrt(u^2 + sigma^2)`, the closed-form
//! derivatives are
//!
//! ```text
//! w'(k)  = b * ( rho + u / r )
//! w''(k) = b * sigma^2 / r^3
//! ```
//!
//! Because `b >= 0` and `sigma > 0`, `w''(k) >= 0` everywhere. A non-flat
//! (`b > 0`) slice is strictly convex; the `b = 0` degeneration is constant.
//! The slice attains its minimum
//! `w_min = a + b*sigma*sqrt(1-rho^2)` at `k_min = m - rho*sigma/sqrt(1-rho^2)`,
//! so non-negative variance holds iff `w_min >= 0`.
//!
//! # References
//!
//! - Gatheral, J., "A parsimonious arbitrage-free implied volatility
//!   parameterization with application to the valuation of volatility
//!   derivatives", Global Derivatives & Risk Management, Madrid (2004).
//! - Gatheral, J. & Jacquier, A., "Arbitrage-free SVI volatility surfaces",
//!   *Quantitative Finance* 14(1):59-71 (2014), Section 3.1.

use crate::error::ParamError;

/// Evaluates `rho*u + hypot(u, sigma)` without subtracting nearly equal wing
/// terms. Both branches rewrite the small radial correction as a ratio whose
/// denominator is bounded away from zero.
pub(crate) fn stable_shape(u: f64, sigma: f64, rho: f64, radial: f64) -> f64 {
    let unit = u / radial;
    let scaled_sigma = sigma / radial;
    if u >= 0.0 {
        let correction = sigma * scaled_sigma / (1.0 + unit);
        (1.0 + rho).mul_add(u, correction)
    } else {
        let correction = sigma * scaled_sigma / (1.0 - unit);
        (rho - 1.0).mul_add(u, correction)
    }
}

/// Evaluates `rho + u/hypot(u,sigma)` using the corresponding rationalized
/// wing correction.
pub(crate) fn stable_unit_slope(u: f64, sigma: f64, rho: f64, radial: f64) -> f64 {
    let unit = u / radial;
    let scaled_sigma = sigma / radial;
    if u >= 0.0 {
        (1.0 + rho) - scaled_sigma * scaled_sigma / (1.0 + unit)
    } else {
        (rho - 1.0) + scaled_sigma * scaled_sigma / (1.0 - unit)
    }
}

/// A raw SVI slice — five parameters describing one maturity's smile.
///
/// Constructed through [`RawSvi::new`] and validated against the raw SVI
/// domain. Its parameters cannot be mutated after construction.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use regit_svi::smile::raw::RawSvi;
///
/// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
/// // ATM total variance.
/// let w0 = svi.total_variance(0.0);
/// assert!(w0 > 0.0);
/// // This non-flat slice is strictly convex: w'' is positive everywhere.
/// assert!(svi.w_double_prime(0.0) > 0.0);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RawSvi {
    /// Vertical translation `a` — the overall variance level.
    pub(crate) a: f64,
    /// Wing slope `b >= 0`.
    pub(crate) b: f64,
    /// Correlation / skew `rho`, with `|rho| < 1`.
    pub(crate) rho: f64,
    /// Horizontal translation `m`.
    pub(crate) m: f64,
    /// ATM curvature `sigma > 0`.
    pub(crate) sigma: f64,
}

impl RawSvi {
    /// Creates a validated raw SVI slice.
    ///
    /// Validation enforces the raw SVI domain (MATH.md §2): `b >= 0`,
    /// `|rho| < 1`, `sigma > 0`, all inputs finite, and the non-negative
    /// variance condition `a + b*sigma*sqrt(1-rho^2) >= 0`. The derived
    /// minimum and ATM total variance must also be representable as finite
    /// binary64 values.
    ///
    /// # Errors
    ///
    /// - [`ParamError::NonFinite`] if any parameter or validated derived
    ///   invariant is `NaN` or infinite.
    /// - [`ParamError::NegativeSlope`] if `b < 0`.
    /// - [`ParamError::CorrelationOutOfRange`] if `|rho| >= 1`.
    /// - [`ParamError::NonPositiveSigma`] if `sigma <= 0`.
    /// - [`ParamError::NegativeMinVariance`] if `w_min < 0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use regit_svi::smile::raw::RawSvi;
    /// use regit_svi::error::ParamError;
    ///
    /// assert!(RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1).is_ok());
    /// assert!(matches!(
    ///     RawSvi::new(0.04, -0.1, 0.0, 0.0, 0.1),
    ///     Err(ParamError::NegativeSlope { .. }),
    /// ));
    /// ```
    pub fn new(a: f64, b: f64, rho: f64, m: f64, sigma: f64) -> Result<Self, ParamError> {
        for (name, value) in [("a", a), ("b", b), ("rho", rho), ("m", m), ("sigma", sigma)] {
            if !value.is_finite() {
                return Err(ParamError::NonFinite { name });
            }
        }
        if b < 0.0 {
            return Err(ParamError::NegativeSlope { b });
        }
        if rho.abs() >= 1.0 {
            return Err(ParamError::CorrelationOutOfRange { rho });
        }
        if sigma <= 0.0 {
            return Err(ParamError::NonPositiveSigma { sigma });
        }
        let candidate = Self {
            a,
            b,
            rho,
            m,
            sigma,
        };
        let w_min = candidate.w_min();
        if !w_min.is_finite() {
            return Err(ParamError::NonFinite { name: "w_min" });
        }
        if w_min < 0.0 {
            return Err(ParamError::NegativeMinVariance { w_min });
        }
        if !candidate.k_min().is_finite() {
            return Err(ParamError::NonFinite { name: "k_min" });
        }
        if !candidate.atm_total_variance().is_finite() {
            return Err(ParamError::NonFinite { name: "w(0)" });
        }
        for (name, value) in [
            ("w'(0)", candidate.atm_skew()),
            ("w''(0)", candidate.atm_curvature()),
            ("left wing slope", candidate.left_wing_slope()),
            ("right wing slope", candidate.right_wing_slope()),
        ] {
            if !value.is_finite() {
                return Err(ParamError::NonFinite { name });
            }
        }
        Ok(candidate)
    }

    pub(crate) const fn new_unchecked(a: f64, b: f64, rho: f64, m: f64, sigma: f64) -> Self {
        Self {
            a,
            b,
            rho,
            m,
            sigma,
        }
    }

    /// Returns the vertical level parameter `a`.
    #[must_use]
    pub const fn a(self) -> f64 {
        self.a
    }

    /// Returns the non-negative wing-scale parameter `b`.
    #[must_use]
    pub const fn b(self) -> f64 {
        self.b
    }

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

    /// Returns the horizontal location parameter `m`.
    #[must_use]
    pub const fn m(self) -> f64 {
        self.m
    }

    /// Returns the strictly positive curvature parameter `sigma`.
    #[must_use]
    pub const fn sigma(self) -> f64 {
        self.sigma
    }

    /// Returns all raw parameters in canonical `(a, b, rho, m, sigma)` order.
    #[must_use]
    pub const fn parameters(self) -> (f64, f64, f64, f64, f64) {
        (self.a, self.b, self.rho, self.m, self.sigma)
    }

    /// Re-checks the raw SVI domain for an existing slice.
    ///
    /// # Errors
    ///
    /// Returns the same [`ParamError`] variants as [`RawSvi::new`].
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
    /// assert!(svi.validate().is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn validate(&self) -> Result<(), ParamError> {
        Self::new(self.a, self.b, self.rho, self.m, self.sigma).map(|_| ())
    }

    /// Total implied variance `w(k) = a + b*(rho*(k-m) + sqrt((k-m)^2 + sigma^2))`.
    ///
    /// This infallible numerical kernel expects finite `k`. Values outside the
    /// representable range propagate IEEE `NaN` or infinity; use a fallible
    /// surface or implied-volatility API when finite-output validation is
    /// required.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// // With rho = 0 and m = 0, w(0) = a + b*sigma.
    /// let svi = RawSvi::new(0.04, 0.4, 0.0, 0.0, 0.1)?;
    /// assert!((svi.total_variance(0.0) - (0.04 + 0.4 * 0.1)).abs() < 1e-15);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn total_variance(&self, k: f64) -> f64 {
        let u = k - self.m;
        let r = u.hypot(self.sigma);
        self.b
            .mul_add(stable_shape(u, self.sigma, self.rho, r), self.a)
    }

    /// First derivative `w'(k) = b * (rho + u/r)`, `u = k - m`,
    /// `r = sqrt(u^2 + sigma^2)`.
    ///
    /// This infallible kernel expects finite `k` and propagates IEEE non-finite
    /// results outside the representable range.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// // At the vertex k_min the slope vanishes.
    /// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
    /// assert!(svi.w_prime(svi.k_min()).abs() < 1e-12);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn w_prime(&self, k: f64) -> f64 {
        let u = k - self.m;
        let r = u.hypot(self.sigma);
        self.b * stable_unit_slope(u, self.sigma, self.rho, r)
    }

    /// Second derivative `w''(k) = b * sigma^2 / r^3`, `r = sqrt(u^2 + sigma^2)`.
    ///
    /// Non-negative for every valid slice. It is strictly positive when
    /// `b > 0`; the `b == 0` degeneration is a flat smile.
    /// This infallible kernel expects finite `k` and propagates IEEE non-finite
    /// results outside the representable range.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
    /// assert!(svi.w_double_prime(0.5) > 0.0);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn w_double_prime(&self, k: f64) -> f64 {
        let u = k - self.m;
        let r = u.hypot(self.sigma);
        let sigma_over_r = self.sigma / r;
        self.b * sigma_over_r * sigma_over_r / r
    }

    /// Black implied volatility at log-moneyness `k` and maturity `t`:
    /// `sqrt(w(k) / t)`.
    ///
    /// # Errors
    ///
    /// Returns [`ParamError::NonPositiveMaturity`] if `t` is non-finite or
    /// non-positive. Returns [`ParamError::NonFinite`] if `k` is non-finite or
    /// the evaluated implied volatility is not finite.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// let svi = RawSvi::new(0.04, 0.0, 0.0, 0.0, 0.1)?;
    /// // Flat w = 0.04 -> vol = 0.2 at t = 1.
    /// assert!((svi.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 });
        }
        if !k.is_finite() {
            return Err(ParamError::NonFinite {
                name: "log_moneyness",
            });
        }
        let volatility = (self.total_variance(k) / t).sqrt();
        if volatility.is_finite() {
            Ok(volatility)
        } else {
            Err(ParamError::NonFinite {
                name: "implied_volatility",
            })
        }
    }

    /// Log-moneyness of the variance minimum:
    /// `k_min = m - rho*sigma/sqrt(1-rho^2)`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// // With rho = 0 the vertex sits at k = m.
    /// let svi = RawSvi::new(0.04, 0.4, 0.0, 0.05, 0.1)?;
    /// assert!((svi.k_min() - 0.05).abs() < 1e-15);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn k_min(&self) -> f64 {
        let denom = (1.0 - self.rho * self.rho).sqrt();
        self.m - self.rho * self.sigma / denom
    }

    /// Minimum total variance `w_min = a + b*sigma*sqrt(1-rho^2)`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
    /// // w_min is attained at k_min.
    /// assert!((svi.w_min() - svi.total_variance(svi.k_min())).abs() < 1e-12);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn w_min(&self) -> f64 {
        self.b
            .mul_add(self.sigma * (1.0 - self.rho * self.rho).sqrt(), self.a)
    }

    /// ATM total variance `w(0)`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
    /// assert!((svi.atm_total_variance() - svi.total_variance(0.0)).abs() < 1e-15);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn atm_total_variance(&self) -> f64 {
        self.total_variance(0.0)
    }

    /// ATM variance skew `w'(0)`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
    /// assert!((svi.atm_skew() - svi.w_prime(0.0)).abs() < 1e-15);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn atm_skew(&self) -> f64 {
        self.w_prime(0.0)
    }

    /// ATM variance curvature `w''(0)`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
    /// assert!(svi.atm_curvature() > 0.0);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn atm_curvature(&self) -> f64 {
        self.w_double_prime(0.0)
    }

    /// Asymptotic slope of the left wing `b*(rho - 1)` (non-positive).
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
    /// assert!(svi.left_wing_slope() <= 0.0);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn left_wing_slope(&self) -> f64 {
        self.b * (self.rho - 1.0)
    }

    /// Asymptotic slope of the right wing `b*(rho + 1)` (non-negative).
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use regit_svi::smile::raw::RawSvi;
    ///
    /// let svi = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1)?;
    /// assert!(svi.right_wing_slope() >= 0.0);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn right_wing_slope(&self) -> f64 {
        self.b * (self.rho + 1.0)
    }
}

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

    /// A representative valid slice used across the tests.
    fn slice() -> RawSvi {
        RawSvi::new(0.04, 0.4, -0.3, 0.05, 0.12).expect("valid test or documentation fixture")
    }

    #[test]
    fn new_accepts_valid_slice() {
        assert!(RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1).is_ok());
    }

    #[test]
    fn new_rejects_negative_b() {
        assert!(matches!(
            RawSvi::new(0.04, -0.1, 0.0, 0.0, 0.1),
            Err(ParamError::NegativeSlope { .. })
        ));
    }

    #[test]
    fn new_rejects_rho_out_of_range() {
        assert!(matches!(
            RawSvi::new(0.04, 0.4, 1.0, 0.0, 0.1),
            Err(ParamError::CorrelationOutOfRange { .. })
        ));
        assert!(matches!(
            RawSvi::new(0.04, 0.4, -1.2, 0.0, 0.1),
            Err(ParamError::CorrelationOutOfRange { .. })
        ));
    }

    #[test]
    fn new_rejects_non_positive_sigma() {
        assert!(matches!(
            RawSvi::new(0.04, 0.4, 0.0, 0.0, 0.0),
            Err(ParamError::NonPositiveSigma { .. })
        ));
    }

    #[test]
    fn new_rejects_negative_min_variance() {
        // a very negative -> w_min < 0.
        assert!(matches!(
            RawSvi::new(-1.0, 0.4, 0.0, 0.0, 0.1),
            Err(ParamError::NegativeMinVariance { .. })
        ));
    }

    #[test]
    fn new_rejects_non_finite() {
        assert!(matches!(
            RawSvi::new(f64::NAN, 0.4, 0.0, 0.0, 0.1),
            Err(ParamError::NonFinite { .. })
        ));
    }

    #[test]
    fn new_rejects_non_finite_derived_invariants() {
        assert!(matches!(
            RawSvi::new(0.0, f64::MAX, 0.0, 0.0, f64::MAX),
            Err(ParamError::NonFinite { name: "w_min" })
        ));
        assert!(matches!(
            RawSvi::new(0.0, f64::MAX, 0.0, -f64::MAX, f64::MIN_POSITIVE),
            Err(ParamError::NonFinite { name: "w(0)" })
        ));
        assert!(matches!(
            RawSvi::new(1.0, 0.0, 0.5, -f64::MAX, f64::MAX),
            Err(ParamError::NonFinite { name: "k_min" })
        ));
        assert!(matches!(
            RawSvi::new(0.0, f64::MAX / 2.0, 0.0, 0.0, f64::MIN_POSITIVE),
            Err(ParamError::NonFinite {
                name: "w''(0)" | "right wing slope"
            })
        ));
    }

    #[test]
    fn total_variance_golden_value() {
        // rho = 0, m = 0: w(0) = a + b*sigma. w(k) symmetric.
        let svi =
            RawSvi::new(0.04, 0.4, 0.0, 0.0, 0.1).expect("valid test or documentation fixture");
        assert!((svi.total_variance(0.0) - 0.08).abs() < 1e-15);
        assert!((svi.total_variance(0.5) - svi.total_variance(-0.5)).abs() < 1e-15);
    }

    #[test]
    fn total_variance_hand_computed() {
        // a=0.04, b=0.4, rho=-0.3, m=0.05, sigma=0.12, k=0.2.
        // u = 0.15, r = sqrt(0.0225 + 0.0144) = sqrt(0.0369).
        let svi = slice();
        let u = 0.2 - 0.05;
        let r = (u * u + 0.12 * 0.12_f64).sqrt();
        let expected = 0.04 + 0.4 * ((-0.3) * u + r);
        assert!((svi.total_variance(0.2) - expected).abs() < 1e-15);
    }

    #[test]
    fn derivative_matches_finite_difference() {
        let svi = slice();
        let h = 1e-6;
        for &k in &[-0.3, -0.1, 0.0, 0.15, 0.4] {
            let fd = (svi.total_variance(k + h) - svi.total_variance(k - h)) / (2.0 * h);
            assert!((svi.w_prime(k) - fd).abs() < 1e-6, "k = {k}");
        }
    }

    #[test]
    fn derivatives_preserve_extreme_wing_scale() {
        let slice = RawSvi::new(0.04, 1e-308, 0.0, 0.0, 1.0).expect("valid extreme-value fixture");
        let slope = slice.w_prime(1e308);
        assert!(slope > 0.0);
        assert!((slope - 1e-308).abs() <= f64::MIN_POSITIVE);
        assert!(slice.w_double_prime(1e308).abs() <= f64::MIN_POSITIVE);
    }

    #[test]
    fn rationalized_wings_preserve_small_radial_correction() {
        let epsilon = f64::EPSILON;
        let right = RawSvi::new(0.0, 1.0, -1.0 + epsilon, 0.0, 1.0)
            .expect("valid near-monotone right-wing fixture");
        let left = RawSvi::new(0.0, 1.0, 1.0 - epsilon, 0.0, 1.0)
            .expect("valid near-monotone left-wing fixture");
        let expected_shape = 2.720_446_049_250_313e-8;
        let expected_slope = 1.720_446_049_250_313e-16;
        assert!((right.total_variance(1e8) - expected_shape).abs() < 1e-22);
        assert!((left.total_variance(-1e8) - expected_shape).abs() < 1e-22);
        assert!((right.w_prime(1e8) - expected_slope).abs() < 1e-30);
        assert!((left.w_prime(-1e8) + expected_slope).abs() < 1e-30);
    }

    #[test]
    fn second_derivative_matches_finite_difference() {
        let svi = slice();
        let h = 1e-4;
        for &k in &[-0.3, -0.1, 0.0, 0.15, 0.4] {
            let fd = (svi.total_variance(k + h) - 2.0 * svi.total_variance(k)
                + svi.total_variance(k - h))
                / (h * h);
            assert!((svi.w_double_prime(k) - fd).abs() < 1e-4, "k = {k}");
        }
    }

    #[test]
    fn second_derivative_strictly_positive() {
        let svi = slice();
        for &k in &[-2.0, -0.5, 0.0, 0.5, 2.0] {
            assert!(svi.w_double_prime(k) > 0.0, "k = {k}");
        }
    }

    #[test]
    fn vertex_is_the_minimum() {
        let svi = slice();
        let km = svi.k_min();
        assert!(svi.w_prime(km).abs() < 1e-12);
        let wmin = svi.w_min();
        assert!((wmin - svi.total_variance(km)).abs() < 1e-12);
        // Any other point has larger w.
        assert!(svi.total_variance(km + 0.1) > wmin);
        assert!(svi.total_variance(km - 0.1) > wmin);
    }

    #[test]
    fn implied_vol_roundtrip() {
        let svi =
            RawSvi::new(0.04, 0.0, 0.0, 0.0, 0.1).expect("valid test or documentation fixture");
        let vol = svi
            .implied_vol(0.0, 1.0)
            .expect("valid test or documentation fixture");
        assert!((vol - 0.2).abs() < 1e-12);
    }

    #[test]
    fn implied_vol_rejects_bad_maturity() {
        let svi = slice();
        assert!(matches!(
            svi.implied_vol(0.0, 0.0),
            Err(ParamError::NonPositiveMaturity { .. })
        ));
    }

    #[test]
    fn implied_vol_never_returns_non_finite_success() {
        let slice = RawSvi::new(0.04, 0.4, -0.3, 0.0, 0.1).expect("valid test fixture");
        assert!(matches!(
            slice.implied_vol(f64::NAN, 1.0),
            Err(ParamError::NonFinite {
                name: "log_moneyness"
            })
        ));
        assert!(slice.implied_vol(f64::MAX, f64::MIN_POSITIVE).is_err());
    }

    #[test]
    fn atm_accessors_agree_with_evaluation() {
        let svi = slice();
        assert!((svi.atm_total_variance() - svi.total_variance(0.0)).abs() < 1e-15);
        assert!((svi.atm_skew() - svi.w_prime(0.0)).abs() < 1e-15);
        assert!((svi.atm_curvature() - svi.w_double_prime(0.0)).abs() < 1e-15);
    }

    #[test]
    fn wing_slopes_have_correct_sign() {
        let svi = slice();
        assert!(svi.left_wing_slope() <= 0.0);
        assert!(svi.right_wing_slope() >= 0.0);
        // Asymptotic check: slope of w far in the wings.
        let far = (svi.total_variance(1000.0) - svi.total_variance(999.0)) / 1.0;
        assert!((far - svi.right_wing_slope()).abs() < 1e-3);
    }

    #[test]
    fn validate_round_trips() {
        let svi = RawSvi::new_unchecked(0.04, 0.4, -0.3, 0.0, 0.1);
        assert!(svi.validate().is_ok());
        let bad = RawSvi::new_unchecked(0.04, -1.0, 0.0, 0.0, 0.1);
        assert!(bad.validate().is_err());
    }
}