libitofin 0.6.1

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
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
//! Volatility term structures.
//!
//! Port of `ql/termstructures/voltermstructure.{hpp,cpp}` and
//! `ql/termstructures/volatility/equityfx/blackvoltermstructure.{hpp,cpp}`.
//! [`VolatilityTermStructure`] adds the strike domain and the business-day
//! convention to the [`TermStructure`] contract; [`BlackVolTermStructure`]
//! layers the Black volatility and variance queries on top, in both date and
//! time form, range- and strike-checked exactly as the C++ base performs them
//! before dispatching to the implementation hooks.
//!
//! ## Divergences from QuantLib
//!
//! - C++ splits the implementation adapters into two abstract classes:
//!   `BlackVolatilityTermStructure` (derives variance from volatility) and
//!   `BlackVarianceTermStructure` (derives volatility from variance). Both
//!   hooks stay required here, preserving C++'s pure-virtual guarantee; the
//!   first adapter becomes the provided
//!   [`variance_from_vol`](BlackVolTermStructure::variance_from_vol) helper,
//!   which volatility-quoted curves call from their one-line
//!   [`black_variance_impl`](BlackVolTermStructure::black_variance_impl).
//!   The variance-quoted adapter follows with `BlackVarianceCurve`/`Surface`
//!   (EPIC-4); such curves derive the volatility as
//!   `sqrt(var(max(t, 1e-5)) / max(t, 1e-5))`.
//! - `smileSection`/`atmLevel` need the smile-section layer and follow with
//!   it; `accept(AcyclicVisitor&)` is not ported (dispatch happens through
//!   the traits).
//! - `QL_ENSURE` on non-decreasing variances becomes an `Err`, per D4.

mod blackconstantvol;
mod blackvariancecurve;
mod blackvariancesurface;
mod localconstantvol;
mod localvolcurve;
mod localvolsurface;
mod localvoltermstructure;
mod optionlet;
mod swaption;
mod volatilitytype;

pub use blackconstantvol::BlackConstantVol;
pub use blackvariancecurve::{BlackVarianceCurve, BlackVolTimeExtrapolation};
pub use blackvariancesurface::{BlackVarianceSurface, Extrapolation};
pub use localconstantvol::LocalConstantVol;
pub use localvolcurve::LocalVolCurve;
pub use localvolsurface::LocalVolSurface;
pub use localvoltermstructure::LocalVolTermStructure;
pub use optionlet::{ConstantOptionletVolatility, OptionletVolatilityStructure};
pub use swaption::{ConstantSwaptionVolatility, SwaptionVolatilityStructure};
pub use volatilitytype::VolatilityType;

use std::any::Any;

use crate::errors::QlResult;
use crate::termstructures::TermStructure;
use crate::time::businessdayconvention::BusinessDayConvention;
use crate::time::date::Date;
use crate::time::period::Period;
use crate::types::{Rate, Real, Time, Volatility};
use crate::{fail, require};

/// Volatility term structure.
///
/// Mirrors QuantLib's `VolatilityTermStructure`: the strike domain, the
/// business-day convention used in tenor-to-date conversion, and the
/// strike-range check shared by every volatility query.
pub trait VolatilityTermStructure: TermStructure {
    /// The business day convention used in tenor to date conversion.
    fn business_day_convention(&self) -> BusinessDayConvention;

    /// The minimum strike for which the term structure can return vols.
    fn min_strike(&self) -> Rate;

    /// The maximum strike for which the term structure can return vols.
    fn max_strike(&self) -> Rate;

    /// Period/date conversion, swaption style: the reference date advanced by
    /// `period` on the structure's calendar per its business-day convention.
    fn option_date_from_tenor(&self, period: Period) -> QlResult<Date> {
        let Some(calendar) = self.calendar() else {
            fail!("no calendar provided for this volatility term structure");
        };
        Ok(calendar.advance_by_period(
            self.reference_date()?,
            period,
            self.business_day_convention(),
            false,
        ))
    }

    /// Strike-range check: `strike` must sit inside the curve domain unless
    /// extrapolation applies.
    ///
    /// Divergence: the finiteness clause. QuantLib's `checkStrike` compares
    /// against `minStrike()` / `maxStrike()` only, and an extrapolating curve
    /// short-circuits that comparison entirely, so `+inf` reaches the
    /// interpolator.
    fn check_strike(&self, strike: Rate, extrapolate: bool) -> QlResult<()> {
        if !strike.is_finite() {
            fail!("strike ({strike}) must be finite");
        }
        require!(
            extrapolate
                || self.allows_extrapolation()
                || (strike >= self.min_strike() && strike <= self.max_strike()),
            "strike ({strike}) is outside the curve domain [{min},{max}]",
            min = self.min_strike(),
            max = self.max_strike()
        );
        Ok(())
    }
}

/// Black-volatility term structure.
///
/// Mirrors QuantLib's `BlackVolTermStructure`: concrete curves implement
/// [`black_vol_impl`](Self::black_vol_impl) (and, when variance-quoted,
/// [`black_variance_impl`](Self::black_variance_impl)); the provided queries
/// perform the range and strike checks and dispatch to the hooks, which may
/// therefore assume extrapolation is required. Volatilities are expressed on
/// an annual basis.
///
/// The `Any` supertrait stands in for the C++ `dynamic_pointer_cast`s that
/// inspect a curve's concrete type (`GeneralizedBlackScholesProcess` probes
/// for `BlackConstantVol` to pick its local-volatility shortcut).
pub trait BlackVolTermStructure: VolatilityTermStructure + Any {
    /// Black volatility calculation hook; range checks have already run.
    fn black_vol_impl(&self, t: Time, strike: Real) -> QlResult<Volatility>;

    /// Black variance calculation hook; range checks have already run.
    ///
    /// Volatility-quoted curves delegate to
    /// [`variance_from_vol`](Self::variance_from_vol).
    fn black_variance_impl(&self, t: Time, strike: Real) -> QlResult<Real>;

    /// Variance derived from the volatility as `vol^2 * t` (C++'s
    /// `BlackVolatilityTermStructure` adapter).
    fn variance_from_vol(&self, t: Time, strike: Real) -> QlResult<Real> {
        let vol = self.black_vol_impl(t, strike)?;
        ensure_finite_volatility(vol)?;
        Ok(vol * vol * t)
    }

    /// Spot volatility at a date.
    fn black_vol_date(
        &self,
        maturity: Date,
        strike: Real,
        extrapolate: bool,
    ) -> QlResult<Volatility> {
        self.check_range_date(maturity, extrapolate)?;
        self.check_strike(strike, extrapolate)?;
        let t = self.time_from_reference(maturity)?;
        let vol = self.black_vol_impl(t, strike)?;
        ensure_finite_volatility(vol)?;
        Ok(vol)
    }

    /// Spot volatility at a time.
    fn black_vol(&self, maturity: Time, strike: Real, extrapolate: bool) -> QlResult<Volatility> {
        self.check_range_time(maturity, extrapolate)?;
        self.check_strike(strike, extrapolate)?;
        let vol = self.black_vol_impl(maturity, strike)?;
        ensure_finite_volatility(vol)?;
        Ok(vol)
    }

    /// Spot variance at a date.
    fn black_variance_date(
        &self,
        maturity: Date,
        strike: Real,
        extrapolate: bool,
    ) -> QlResult<Real> {
        self.check_range_date(maturity, extrapolate)?;
        self.check_strike(strike, extrapolate)?;
        let t = self.time_from_reference(maturity)?;
        let var = self.black_variance_impl(t, strike)?;
        ensure_valid_variance(var)?;
        Ok(var)
    }

    /// Spot variance at a time.
    fn black_variance(&self, maturity: Time, strike: Real, extrapolate: bool) -> QlResult<Real> {
        self.check_range_time(maturity, extrapolate)?;
        self.check_strike(strike, extrapolate)?;
        let var = self.black_variance_impl(maturity, strike)?;
        ensure_valid_variance(var)?;
        Ok(var)
    }

    /// Forward (at-the-money) volatility between two dates.
    fn black_forward_vol_dates(
        &self,
        date1: Date,
        date2: Date,
        strike: Real,
        extrapolate: bool,
    ) -> QlResult<Volatility> {
        require!(date1 <= date2, "{date1} later than {date2}");
        self.check_range_date(date2, extrapolate)?;
        let time1 = self.time_from_reference(date1)?;
        let time2 = self.time_from_reference(date2)?;
        self.black_forward_vol(time1, time2, strike, extrapolate)
    }

    /// Forward (at-the-money) volatility between two times.
    fn black_forward_vol(
        &self,
        time1: Time,
        time2: Time,
        strike: Real,
        extrapolate: bool,
    ) -> QlResult<Volatility> {
        if time1 > time2 || !time1.is_finite() || !time2.is_finite() {
            fail!("{time1} later than {time2}");
        }
        self.check_range_time(time2, extrapolate)?;
        self.check_strike(strike, extrapolate)?;
        if time2 == time1 {
            if time1 == 0.0 {
                let epsilon = 1.0e-5;
                let var = self.black_variance_impl(epsilon, strike)?;
                ensure_valid_variance(var)?;
                Ok((var / epsilon).sqrt())
            } else {
                let epsilon = Time::min(1.0e-5, time1);
                let var1 = self.black_variance_impl(time1 - epsilon, strike)?;
                let var2 = self.black_variance_impl(time1 + epsilon, strike)?;
                ensure_non_decreasing(var1, var2)?;
                Ok(((var2 - var1) / (2.0 * epsilon)).sqrt())
            }
        } else {
            let var1 = self.black_variance_impl(time1, strike)?;
            let var2 = self.black_variance_impl(time2, strike)?;
            ensure_non_decreasing(var1, var2)?;
            Ok(((var2 - var1) / (time2 - time1)).sqrt())
        }
    }

    /// Forward (at-the-money) variance between two dates.
    fn black_forward_variance_dates(
        &self,
        date1: Date,
        date2: Date,
        strike: Real,
        extrapolate: bool,
    ) -> QlResult<Real> {
        require!(date1 <= date2, "{date1} later than {date2}");
        self.check_range_date(date2, extrapolate)?;
        let time1 = self.time_from_reference(date1)?;
        let time2 = self.time_from_reference(date2)?;
        self.black_forward_variance(time1, time2, strike, extrapolate)
    }

    /// Forward (at-the-money) variance between two times.
    fn black_forward_variance(
        &self,
        time1: Time,
        time2: Time,
        strike: Real,
        extrapolate: bool,
    ) -> QlResult<Real> {
        if time1 > time2 || !time1.is_finite() || !time2.is_finite() {
            fail!("{time1} later than {time2}");
        }
        self.check_range_time(time2, extrapolate)?;
        self.check_strike(strike, extrapolate)?;
        let v1 = self.black_variance_impl(time1, strike)?;
        let v2 = self.black_variance_impl(time2, strike)?;
        ensure_non_decreasing(v1, v2)?;
        Ok(v2 - v1)
    }
}

fn ensure_non_decreasing(var1: Real, var2: Real) -> QlResult<()> {
    ensure_valid_variance(var1)?;
    ensure_valid_variance(var2)?;
    if var2 < var1 {
        fail!("variances must be non-decreasing");
    }
    Ok(())
}

/// Reject a variance that is negative or non-finite.
///
/// Divergence: `voltermstructure.hpp` / `blackvoltermstructure.cpp` validate
/// only the time and strike ranges, never the value an implementation returns.
/// A curve whose `blackVarianceImpl` yields a negative variance hands C++ a NaN
/// volatility from `std::sqrt`; this port fails at the source instead.
fn ensure_valid_variance(var: Real) -> QlResult<()> {
    if !var.is_finite() || var < 0.0 {
        fail!("variance ({var}) must be finite and non-negative");
    }
    Ok(())
}

/// Reject a non-finite volatility. Divergence: as for [`ensure_valid_variance`].
fn ensure_finite_volatility(vol: Volatility) -> QlResult<()> {
    if !vol.is_finite() {
        fail!("volatility ({vol}) must be finite");
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::patterns::observable::{AsObservable, Observable};
    use crate::termstructures::TermStructureBase;
    use crate::time::calendars::target::Target;
    use crate::time::date::Month;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::timeunit::TimeUnit;

    struct MockVolCurve {
        base: TermStructureBase,
        vol: Volatility,
        variance_override: Option<fn(Time) -> Real>,
        strike_domain: (Rate, Rate),
    }

    impl MockVolCurve {
        fn flat(vol: Volatility) -> MockVolCurve {
            MockVolCurve {
                base: TermStructureBase::with_reference_date(
                    Date::new(15, Month::June, 2026),
                    Some(Target::new()),
                    Some(Actual360::new()),
                ),
                vol,
                variance_override: None,
                strike_domain: (Rate::MIN, Rate::MAX),
            }
        }
    }

    impl AsObservable for MockVolCurve {
        fn observable(&self) -> &Observable {
            self.base.observable()
        }
    }

    impl TermStructure for MockVolCurve {
        fn base(&self) -> &TermStructureBase {
            &self.base
        }

        fn max_date(&self) -> Date {
            Date::new(15, Month::June, 2036)
        }
    }

    impl VolatilityTermStructure for MockVolCurve {
        fn business_day_convention(&self) -> BusinessDayConvention {
            BusinessDayConvention::Following
        }

        fn min_strike(&self) -> Rate {
            self.strike_domain.0
        }

        fn max_strike(&self) -> Rate {
            self.strike_domain.1
        }
    }

    impl BlackVolTermStructure for MockVolCurve {
        fn black_vol_impl(&self, _t: Time, _strike: Real) -> QlResult<Volatility> {
            Ok(self.vol)
        }

        fn black_variance_impl(&self, t: Time, strike: Real) -> QlResult<Real> {
            match self.variance_override {
                Some(f) => Ok(f(t)),
                None => self.variance_from_vol(t, strike),
            }
        }
    }

    #[test]
    fn variance_defaults_to_vol_squared_times_time() {
        let curve = MockVolCurve::flat(0.25);
        let var = curve.black_variance(2.0, 100.0, false).unwrap();
        assert!((var - 0.25 * 0.25 * 2.0).abs() < 1e-15);
    }

    #[test]
    fn spot_variance_rejects_invalid_variance() {
        let mut curve = MockVolCurve::flat(0.2);
        curve.variance_override = Some(|_| Real::INFINITY);
        assert!(curve.black_variance(1.0, 100.0, false).is_err());

        curve.variance_override = Some(|_| -1.0);
        assert!(curve.black_variance(1.0, 100.0, false).is_err());

        let maturity = curve.reference_date().unwrap() + 30;
        assert!(curve.black_variance_date(maturity, 100.0, false).is_err());
    }

    #[test]
    fn forward_vol_of_a_flat_curve_is_the_flat_vol() {
        let curve = MockVolCurve::flat(0.2);
        for (t1, t2) in [(0.5, 1.5), (0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] {
            let fwd = curve.black_forward_vol(t1, t2, 100.0, false).unwrap();
            assert!((fwd - 0.2).abs() < 1e-12, "t1={t1} t2={t2} fwd={fwd}");
        }
    }

    #[test]
    fn decreasing_variances_are_errors() {
        let mut curve = MockVolCurve::flat(0.2);
        curve.variance_override = Some(|t| 0.1 * (10.0 - t));
        let err = curve.black_forward_vol(1.0, 2.0, 100.0, false).unwrap_err();
        assert!(err.message().contains("non-decreasing"));
        let err = curve
            .black_forward_variance(1.0, 2.0, 100.0, false)
            .unwrap_err();
        assert!(err.message().contains("non-decreasing"));
    }

    #[test]
    fn zero_time_forward_vol_rejects_invalid_variance() {
        let mut curve = MockVolCurve::flat(0.2);
        curve.variance_override = Some(|_| Real::INFINITY);
        assert!(curve.black_forward_vol(0.0, 0.0, 100.0, false).is_err());

        curve.variance_override = Some(|_| -1.0);
        assert!(curve.black_forward_vol(0.0, 0.0, 100.0, false).is_err());
    }

    #[test]
    fn strike_checks_gate_the_curve_domain() {
        let mut curve = MockVolCurve::flat(0.2);
        curve.strike_domain = (90.0, 110.0);

        assert!(curve.black_vol(1.0, 100.0, false).is_ok());
        let err = curve.black_vol(1.0, 80.0, false).unwrap_err();
        assert!(err.message().contains("outside the curve domain"));
        assert!(curve.black_vol(1.0, 80.0, true).is_ok());
        curve.enable_extrapolation();
        assert!(curve.black_vol(1.0, 80.0, false).is_ok());
        curve.disable_extrapolation();
        assert!(curve.black_vol(1.0, Rate::NAN, false).is_err());
    }

    #[test]
    fn non_finite_times_and_strikes_are_rejected_even_when_extrapolating() {
        let curve = MockVolCurve::flat(0.2);

        assert!(curve.black_vol(Time::INFINITY, 100.0, true).is_err());
        assert!(
            curve
                .black_forward_vol(0.5, Time::INFINITY, 100.0, true)
                .is_err()
        );
        assert!(
            curve
                .black_forward_variance(0.5, Time::INFINITY, 100.0, true)
                .is_err()
        );
        assert!(curve.black_vol(1.0, Real::INFINITY, true).is_err());
        assert!(curve.black_vol(1.0, Real::NAN, true).is_err());
    }

    #[test]
    fn variance_from_vol_rejects_non_finite_volatility() {
        let curve = MockVolCurve::flat(Volatility::INFINITY);

        assert!(curve.black_vol(1.0, 100.0, false).is_err());
        assert!(curve.black_variance(1.0, 100.0, false).is_err());
    }

    #[test]
    fn forward_variance_of_a_flat_curve_is_additive() {
        let curve = MockVolCurve::flat(0.2);
        let fwd = curve
            .black_forward_variance(1.0, 3.0, 100.0, false)
            .unwrap();
        assert!((fwd - 0.04 * 2.0).abs() < 1e-15);
    }

    #[test]
    fn reversed_times_and_dates_are_errors() {
        let curve = MockVolCurve::flat(0.2);
        let err = curve.black_forward_vol(2.0, 1.0, 100.0, false).unwrap_err();
        assert!(err.message().contains("later than"));

        let reference = Date::new(15, Month::June, 2026);
        let err = curve
            .black_forward_variance_dates(reference + 30, reference + 10, 100.0, false)
            .unwrap_err();
        assert!(err.message().contains("later than"));
    }

    #[test]
    fn range_checks_gate_time_and_date() {
        let curve = MockVolCurve::flat(0.2);
        assert!(curve.black_vol(-0.5, 100.0, false).is_err());
        let before = Date::new(14, Month::June, 2026);
        assert!(curve.black_vol_date(before, 100.0, false).is_err());
        assert!(curve.black_variance_date(before, 100.0, false).is_err());
    }

    #[test]
    fn option_date_from_tenor_advances_swaption_style() {
        let curve = MockVolCurve::flat(0.2);
        let expected = Target::new().advance(
            Date::new(15, Month::June, 2026),
            3,
            TimeUnit::Months,
            BusinessDayConvention::Following,
            false,
        );
        assert_eq!(
            curve
                .option_date_from_tenor(Period::new(3, TimeUnit::Months))
                .unwrap(),
            expected
        );
    }
}