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

//! Evidence strength and status for static-arbitrage assessments.

use core::fmt;

/// Error returned when a bounded numerical diagnostic has no valid domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticError {
    /// A scan bound was `NaN` or infinite.
    NonFiniteBound,
    /// The lower scan bound is not strictly below the upper bound.
    InvalidOrder,
    /// Adding the built-in diagnostic margin overflowed the finite range.
    DomainOverflow,
    /// The diagnostic function was non-finite at a sampled point.
    NonFiniteEvaluation,
}

impl fmt::Display for DiagnosticError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NonFiniteBound => formatter.write_str("diagnostic bounds must be finite"),
            Self::InvalidOrder => {
                formatter.write_str("diagnostic lower bound must be below upper bound")
            }
            Self::DomainOverflow => formatter.write_str("diagnostic domain overflowed"),
            Self::NonFiniteEvaluation => {
                formatter.write_str("diagnostic evaluation was non-finite")
            }
        }
    }
}

impl std::error::Error for DiagnosticError {}

/// What an arbitrage procedure established.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArbitrageStatus {
    /// A conclusive counterexample or failed necessary condition was found.
    ViolationDetected,
    /// The selected procedure found no violation in its stated scope.
    NoViolationDetected,
    /// Floating-point boundary proximity prevents a reliable conclusion.
    Indeterminate,
}

/// Validated configuration for a bounded numerical scan.
///
/// # Examples
///
/// ```
/// use regit_svi::ScanConfig;
///
/// let config = ScanConfig::new(-2.0, 2.0, 801, 1e-12);
/// assert_eq!(config.map(ScanConfig::points), Some(801));
/// assert!(ScanConfig::new(2.0, -2.0, 801, 1e-12).is_none());
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScanConfig {
    lower: f64,
    upper: f64,
    points: usize,
    tolerance: f64,
}

impl ScanConfig {
    /// Creates a finite, ordered scan domain with at least three points.
    #[must_use]
    pub fn new(lower: f64, upper: f64, points: usize, tolerance: f64) -> Option<Self> {
        if lower.is_finite()
            && upper.is_finite()
            && lower < upper
            && points >= 3
            && tolerance.is_finite()
            && tolerance >= 0.0
        {
            Some(Self {
                lower,
                upper,
                points,
                tolerance,
            })
        } else {
            None
        }
    }

    /// Lower log-moneyness bound.
    #[must_use]
    pub const fn lower(self) -> f64 {
        self.lower
    }
    /// Upper log-moneyness bound.
    #[must_use]
    pub const fn upper(self) -> f64 {
        self.upper
    }
    /// Number of equally spaced samples.
    #[must_use]
    pub const fn points(self) -> usize {
        self.points
    }
    /// Sign-classification tolerance.
    #[must_use]
    pub const fn tolerance(self) -> f64 {
        self.tolerance
    }
}

/// Reproducible metadata for a bounded numerical diagnostic.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use regit_svi::{RawSvi, ScanEvidence};
/// use regit_svi::no_arb::butterfly::butterfly_scan;
///
/// let slice = RawSvi::new(0.04, 0.1, -0.2, 0.0, 0.3)?;
/// let evidence: ScanEvidence = butterfly_scan(&slice, -0.5, 0.5)?.evidence();
/// assert_eq!(evidence.requested_domain(), (-0.5, 0.5));
/// assert_eq!(evidence.requested_points(), 401);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScanEvidence {
    config: ScanConfig,
    requested_lower: f64,
    requested_upper: f64,
    requested_points: usize,
    samples_evaluated: usize,
    scan_count: usize,
    total_samples_evaluated: usize,
    selected_scan: usize,
    refinement_attempted: bool,
    refinement: Option<RootEvidence>,
}

/// Stage reached by the theorem-guided Raw SVI diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RawSearchStage {
    /// The normalized parameter domain was checked.
    Domain,
    /// The asymptotic wing conditions were checked.
    Wings,
    /// The Fukasawa interval was constructed.
    FukasawaInterval,
    /// The normalized location was compared with that interval.
    Location,
    /// The two roots delimiting the positive part of `G2` were found.
    G2Roots,
    /// The compactified global numerical search was run.
    SigmaSearch,
    /// All stages completed.
    Complete,
}

/// Reproducible evidence for one bracket-preserving scalar root solve.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RootEvidence {
    root: f64,
    lower: f64,
    upper: f64,
    residual: f64,
    evaluations: usize,
    termination: RootTermination,
}

/// Successful termination reason for a bracket-preserving root refinement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RootTermination {
    /// An endpoint or iterate evaluated exactly to zero in binary64.
    ExactRoot,
    /// The retained sign-changing bracket met the configured width tolerance.
    BracketTolerance,
}

impl RootEvidence {
    pub(crate) const fn new(
        root: f64,
        lower: f64,
        upper: f64,
        residual: f64,
        evaluations: usize,
        termination: RootTermination,
    ) -> Self {
        Self {
            root,
            lower,
            upper,
            residual,
            evaluations,
            termination,
        }
    }

    /// Returned root estimate at which the residual was evaluated.
    #[must_use]
    pub const fn root(self) -> f64 {
        self.root
    }

    /// Final lower bracket endpoint.
    #[must_use]
    pub const fn lower(self) -> f64 {
        self.lower
    }
    /// Final upper bracket endpoint.
    #[must_use]
    pub const fn upper(self) -> f64 {
        self.upper
    }
    /// Absolute function residual at the returned root estimate.
    #[must_use]
    pub const fn residual(self) -> f64 {
        self.residual
    }
    /// Function evaluations used by the solve.
    #[must_use]
    pub const fn evaluations(self) -> usize {
        self.evaluations
    }

    /// Successful root-refinement termination reason.
    #[must_use]
    pub const fn termination(self) -> RootTermination {
        self.termination
    }
}

/// Metadata for the theorem-guided numerical search used on regular Raw SVI.
///
/// This records a numerical diagnostic, not a proof of a global optimum.  In
/// particular, increasing arithmetic precision would reduce roundoff but
/// would not prove that the compactified optimization found the global
/// maximum.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use regit_svi::{ArbitrageEvidence, RawSearchStage, RawSvi};
/// use regit_svi::no_arb::butterfly::assess_raw;
///
/// let slice = RawSvi::new(0.04, 0.1, -0.2, 0.0, 0.3)?;
/// match assess_raw(&slice, 1e-10).evidence() {
///     ArbitrageEvidence::NumericalSearch(search) => {
///         assert_eq!(search.stage(), RawSearchStage::Complete);
///         assert!(search.terminated());
///     }
///     _ => return Err(std::io::Error::other("expected numerical search evidence").into()),
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SearchEvidence {
    algorithm: &'static str,
    stage: RawSearchStage,
    compact_domains: [(f64, f64); 2],
    absolute_tolerance: f64,
    relative_tolerance: f64,
    optimization_error: f64,
    evaluations: usize,
    subdivisions: usize,
    roots: [Option<RootEvidence>; 4],
    fukasawa_interval: Option<(f64, f64)>,
    sigma_star: Option<f64>,
    argmax_ell: Option<f64>,
    terminated: bool,
}

impl SearchEvidence {
    #[allow(clippy::too_many_arguments)]
    pub(crate) const fn new(
        algorithm: &'static str,
        stage: RawSearchStage,
        compact_domains: [(f64, f64); 2],
        absolute_tolerance: f64,
        relative_tolerance: f64,
        optimization_error: f64,
        evaluations: usize,
        subdivisions: usize,
        roots: [Option<RootEvidence>; 4],
        fukasawa_interval: Option<(f64, f64)>,
        sigma_star: Option<f64>,
        argmax_ell: Option<f64>,
        terminated: bool,
    ) -> Self {
        Self {
            algorithm,
            stage,
            compact_domains,
            absolute_tolerance,
            relative_tolerance,
            optimization_error,
            evaluations,
            subdivisions,
            roots,
            fukasawa_interval,
            sigma_star,
            argmax_ell,
            terminated,
        }
    }

    /// Name of the numerical algorithm.
    #[must_use]
    pub const fn algorithm(self) -> &'static str {
        self.algorithm
    }
    /// Last completed diagnostic stage.
    #[must_use]
    pub const fn stage(self) -> RawSearchStage {
        self.stage
    }
    /// Negative and positive compactified search intervals.
    #[must_use]
    pub const fn compact_domains(self) -> [(f64, f64); 2] {
        self.compact_domains
    }
    /// Absolute classification tolerance.
    #[must_use]
    pub const fn absolute_tolerance(self) -> f64 {
        self.absolute_tolerance
    }
    /// Relative classification tolerance.
    #[must_use]
    pub const fn relative_tolerance(self) -> f64 {
        self.relative_tolerance
    }
    /// Reported heuristic optimization-uncertainty estimate.
    #[must_use]
    pub const fn optimization_error(self) -> f64 {
        self.optimization_error
    }
    /// Total function evaluations, including root solves.
    #[must_use]
    pub const fn evaluations(self) -> usize {
        self.evaluations
    }
    /// Number of terminal compactified subintervals.
    #[must_use]
    pub const fn subdivisions(self) -> usize {
        self.subdivisions
    }
    /// Root evidence in Fukasawa-left, Fukasawa-right, G2-left, G2-right order.
    #[must_use]
    pub const fn roots(self) -> [Option<RootEvidence>; 4] {
        self.roots
    }
    /// Computed open Fukasawa interval, when available.
    #[must_use]
    pub const fn fukasawa_interval(self) -> Option<(f64, f64)> {
        self.fukasawa_interval
    }
    /// Numerically estimated critical `sigma`, when available.
    #[must_use]
    pub const fn sigma_star(self) -> Option<f64> {
        self.sigma_star
    }
    /// Normalized location of the largest sampled objective value.
    #[must_use]
    pub const fn argmax_ell(self) -> Option<f64> {
        self.argmax_ell
    }
    /// Whether the configured subdivision budget completed without non-finite values.
    #[must_use]
    pub const fn terminated(self) -> bool {
        self.terminated
    }
}

impl ScanEvidence {
    pub(crate) const fn new(
        config: ScanConfig,
        requested_domain: (f64, f64),
        requested_points: usize,
        samples_evaluated: usize,
        refinement_attempted: bool,
        refinement: Option<RootEvidence>,
    ) -> Self {
        Self {
            config,
            requested_lower: requested_domain.0,
            requested_upper: requested_domain.1,
            requested_points,
            samples_evaluated,
            scan_count: 1,
            total_samples_evaluated: samples_evaluated,
            selected_scan: 0,
            refinement_attempted,
            refinement,
        }
    }

    pub(crate) const fn aggregate_selected(
        selected: Self,
        scan_count: usize,
        total_samples_evaluated: usize,
        selected_scan: usize,
    ) -> Self {
        Self {
            scan_count,
            total_samples_evaluated,
            selected_scan,
            ..selected
        }
    }

    /// Caller-requested log-moneyness bounds before diagnostic expansion.
    #[must_use]
    pub const fn requested_domain(self) -> (f64, f64) {
        (self.requested_lower, self.requested_upper)
    }

    /// Requested grid resolution before any implementation expansion.
    #[must_use]
    pub const fn requested_points(self) -> usize {
        self.requested_points
    }

    /// The configured domain, resolution, and tolerance.
    #[must_use]
    pub const fn config(self) -> ScanConfig {
        self.config
    }
    /// Number of successfully evaluated samples in the selected scan.
    #[must_use]
    pub const fn samples_evaluated(self) -> usize {
        self.samples_evaluated
    }

    /// Number of bounded scans represented by this evidence.
    #[must_use]
    pub const fn scan_count(self) -> usize {
        self.scan_count
    }

    /// Total successfully evaluated samples across all represented scans.
    #[must_use]
    pub const fn total_samples_evaluated(self) -> usize {
        self.total_samples_evaluated
    }

    /// Zero-based represented scan whose config, domain, sample count, and
    /// refinement metadata are retained as the selected adverse scan.
    #[must_use]
    pub const fn selected_scan(self) -> usize {
        self.selected_scan
    }

    /// Whether a sampled sign-change bracket triggered root refinement.
    #[must_use]
    pub const fn refinement_attempted(self) -> bool {
        self.refinement_attempted
    }

    /// Completed bracket-preserving root-solve evidence, when available.
    #[must_use]
    pub const fn refinement(self) -> Option<RootEvidence> {
        self.refinement
    }
}

/// Strength and scope of the evidence behind a status.
#[allow(clippy::large_enum_variant)] // Search metadata is intentionally an owned, allocation-free audit record.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ArbitrageEvidence {
    /// An analytic necessary-and-sufficient characterization, evaluated in `f64`.
    AnalyticNecessaryAndSufficient {
        /// Name of the theorem or identity used.
        theorem: &'static str,
        /// Boundary tolerance used to emit [`ArbitrageStatus::Indeterminate`].
        boundary_tolerance: f64,
    },
    /// Analytic sufficient conditions; failure is not evidence of violation.
    AnalyticSufficient {
        /// Name of the sufficient theorem used.
        theorem: &'static str,
    },
    /// An analytic necessary condition; its failure proves a violation.
    AnalyticNecessary {
        /// Name of the necessary condition used.
        condition: &'static str,
    },
    /// A bounded numerical scan, which cannot establish a global conclusion.
    NumericalScan(ScanEvidence),
    /// A theorem-guided numerical root and global-search procedure.
    NumericalSearch(SearchEvidence),
}

/// A status coupled to the evidence that supports it.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use regit_svi::{ArbitrageEvidence, ArbitrageStatus, RawSvi};
/// use regit_svi::no_arb::butterfly::assess_raw;
///
/// let slice = RawSvi::new(0.04, 0.1, -0.2, 0.0, 0.3)?;
/// let assessment = assess_raw(&slice, 1e-10);
/// assert_eq!(assessment.status(), ArbitrageStatus::NoViolationDetected);
/// assert!(matches!(assessment.evidence(), ArbitrageEvidence::NumericalSearch(_)));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ArbitrageAssessment {
    status: ArbitrageStatus,
    evidence: ArbitrageEvidence,
    margin: f64,
    witness: Option<f64>,
}

impl ArbitrageAssessment {
    #[allow(clippy::large_types_passed_by_value)] // The evidence is Copy and retained inline by design.
    pub(crate) const fn new(
        status: ArbitrageStatus,
        evidence: ArbitrageEvidence,
        margin: f64,
        witness: Option<f64>,
    ) -> Self {
        Self {
            status,
            evidence,
            margin,
            witness,
        }
    }

    /// Returns the three-way conclusion.
    #[must_use]
    pub const fn status(self) -> ArbitrageStatus {
        self.status
    }
    /// Returns how and over what scope the conclusion was obtained.
    #[must_use]
    pub const fn evidence(self) -> ArbitrageEvidence {
        self.evidence
    }
    /// Returns the smallest signed condition margin observed or derived.
    #[must_use]
    pub const fn margin(self) -> f64 {
        self.margin
    }
    /// Returns a violating or worst sampled log-moneyness when available.
    #[must_use]
    pub const fn witness(self) -> Option<f64> {
        self.witness
    }
}