libitofin 0.5.0

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
//! Piecewise-bootstrapped yield term structure.
//!
//! Port of `ql/termstructures/yield/piecewiseyieldcurve.hpp`. A
//! [`PiecewiseYieldCurve`] is built from a set of rate helpers whose maturities
//! mark the segment boundaries; each node is solved so the helper reprices its
//! quote off the curve (see [`iterativebootstrap`](crate::termstructures::iterativebootstrap)).
//!
//! ## Laziness (bootstrap in `perform_calculations`, not the constructor)
//!
//! The curve embeds a [`LazyObject`], exactly as C++ inherits one
//! (`piecewiseyieldcurve.hpp:63`). Construction is cheap: it lays out no nodes
//! and runs no solver. The first read that needs the curve
//! ([`discount`](YieldTermStructure::discount) or [`max_date`](TermStructure::max_date))
//! calls [`calculate`](PiecewiseYieldCurve::calculate), which runs the bootstrap
//! once and caches it. A helper-quote or evaluation-date change notifies the
//! curve, invalidates the cache, and the next read re-bootstraps. Bootstrapping
//! in the constructor would break that observability contract, so it is done in
//! `perform_calculations` (here, [`calculate`](Self::calculate)'s closure).
//!
//! The `LazyObject`'s pre-set `calculated` flag is what breaks bootstrap
//! recursion: while the bootstrap runs, a helper reads the curve's discount,
//! which re-enters `calculate`; the flag is already set, so the re-entrant call
//! returns immediately and reads the partially built curve, mirroring the C++
//! `calculated_ = true` guard.
//!
//! ## Scope and deferrals
//!
//! - Generic over the interpolator; the traits are a type parameter. This
//!   ticket ports `Discount` with `LogLinear`/`Linear`; `ZeroYield`/`ForwardRate`
//!   and the spline interpolators are deferred with their traits.
//! - `MultiCurveBootstrapProvider` (`ql/termstructures/multicurve.hpp:36`), a
//!   marker base used only for a `dynamic_pointer_cast`, is dropped.
//! - Jump quotes (`jumps`/`jumpDates`) are not ported, following the
//!   [`YieldTermStructure`] precedent.

use std::cell::RefCell;
use std::marker::PhantomData;
use std::rc::Weak;

use crate::errors::QlResult;
use crate::math::interpolations::Interpolator;
use crate::patterns::lazyobject::LazyObject;
use crate::patterns::observable::{AsObservable, Observable, Observer};
use crate::require;
use crate::shared::{Shared, SharedMut, shared_mut};
use crate::termstructures::bootstraphelper::RateHelper;
use crate::termstructures::bootstraptraits::{BootstrapTraits, CurveData};
use crate::termstructures::iterativebootstrap::{IterativeBootstrap, PiecewiseCurve};
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::termstructures::{TermStructure, TermStructureBase};
use crate::time::date::Date;
use crate::time::daycounter::DayCounter;
use crate::types::{DiscountFactor, Real, Time};

/// Feeds a helper-quote or evaluation-date notification into the curve's lazy
/// core: it invalidates the bootstrap cache and re-broadcasts to the curve's
/// own observers (the port of `registerWithObservables` + `LazyObject::update`).
struct CurveUpdater {
    lazy: SharedMut<LazyObject>,
}

impl Observer for CurveUpdater {
    fn update(&mut self) {
        if let Some(update) = LazyObject::deferred_update(&self.lazy) {
            update.notify_observers();
        }
    }
}

/// Yield term structure bootstrapped from rate helpers.
///
/// `T` is the curve-shape traits (`Discount`); `I` is the interpolation factory
/// (`LogLinear`, `Linear`). The node data lives in a `RefCell` the bootstrap
/// mutates and the discount lookup reads back.
pub struct PiecewiseYieldCurve<T: BootstrapTraits, I: Interpolator> {
    base: TermStructureBase,
    instruments: Vec<Shared<dyn RateHelper>>,
    interpolator: I,
    data: RefCell<CurveData<I>>,
    lazy: SharedMut<LazyObject>,
    observable: Shared<Observable>,
    updater: SharedMut<CurveUpdater>,
    bootstrap: IterativeBootstrap,
    accuracy: Real,
    self_weak: Weak<dyn YieldTermStructure>,
    _traits: PhantomData<fn() -> T>,
}

impl<T: BootstrapTraits + 'static, I: Interpolator + 'static> PiecewiseYieldCurve<T, I> {
    /// Builds a curve over `instruments` with a fixed `reference_date` (the C++
    /// reference-date constructor). Construction is cheap; the bootstrap runs
    /// on first use.
    pub fn new(
        reference_date: Date,
        instruments: Vec<Shared<dyn RateHelper>>,
        day_counter: DayCounter,
        interpolator: I,
    ) -> QlResult<Shared<PiecewiseYieldCurve<T, I>>> {
        require!(!instruments.is_empty(), "no bootstrap helpers given");

        let curve = Shared::new_cyclic(|weak: &Weak<PiecewiseYieldCurve<T, I>>| {
            let self_weak: Weak<dyn YieldTermStructure> = weak.clone();
            let lazy = shared_mut(LazyObject::new(true));
            let observable = lazy.borrow().observable_handle();
            let updater = shared_mut(CurveUpdater {
                lazy: SharedMut::clone(&lazy),
            });
            PiecewiseYieldCurve {
                base: TermStructureBase::with_reference_date(
                    reference_date,
                    None,
                    Some(day_counter),
                ),
                instruments,
                interpolator,
                data: RefCell::new(CurveData::new()),
                lazy,
                observable,
                updater,
                bootstrap: IterativeBootstrap::new(),
                accuracy: 1.0e-12,
                self_weak,
                _traits: PhantomData,
            }
        });

        // Register the curve as an observer of every helper, so a quote or
        // evaluation-date change invalidates the bootstrap (C++'s
        // `bootstrap_.setup(this)` -> `registerWithObservables`).
        let observer = SharedMut::clone(&curve.updater) as SharedMut<dyn Observer>;
        for helper in &curve.instruments {
            helper.observable().register_observer(&observer);
        }
        Ok(curve)
    }

    /// Runs the bootstrap if the cache is stale, caching the result. The lazy
    /// core is not borrowed while the bootstrap runs, so a helper reading the
    /// curve mid-bootstrap re-enters here and returns on the pre-set flag.
    pub fn calculate(&self) -> QlResult<()> {
        if self.lazy.borrow().is_calculated() {
            return Ok(());
        }
        if !self.lazy.borrow_mut().start_calculation() {
            return Ok(());
        }
        let result = self.bootstrap.calculate(self);
        self.lazy.borrow_mut().finish_calculation(&result);
        result
    }

    /// The node times, after bootstrapping.
    pub fn times(&self) -> QlResult<Vec<Time>> {
        self.calculate()?;
        Ok(self.data.borrow().times().to_vec())
    }

    /// The node dates, after bootstrapping.
    pub fn dates(&self) -> QlResult<Vec<Date>> {
        self.calculate()?;
        Ok(self.data.borrow().dates().to_vec())
    }

    /// The node values (discount factors for `Discount`), after bootstrapping.
    pub fn data(&self) -> QlResult<Vec<Real>> {
        self.calculate()?;
        Ok(self.data.borrow().data().to_vec())
    }

    /// The (date, value) nodes, after bootstrapping.
    pub fn nodes(&self) -> QlResult<Vec<(Date, Real)>> {
        self.calculate()?;
        Ok(self.data.borrow().nodes())
    }

    /// Registers a downstream observer of the curve's notifications.
    pub fn register_observer(&self, observer: &SharedMut<dyn Observer>) -> bool {
        self.observable.register_observer(observer)
    }
}

impl<T: BootstrapTraits, I: Interpolator> AsObservable for PiecewiseYieldCurve<T, I> {
    fn observable(&self) -> &Observable {
        &self.observable
    }
}

impl<T: BootstrapTraits + 'static, I: Interpolator + 'static> TermStructure
    for PiecewiseYieldCurve<T, I>
{
    fn base(&self) -> &TermStructureBase {
        &self.base
    }

    fn max_date(&self) -> Date {
        // Trigger the bootstrap so the maximum reflects the solved curve; a
        // bootstrap failure is surfaced by `discount`, so fall back here.
        let _ = self.calculate();
        self.data
            .borrow()
            .max_date()
            .or_else(|| self.base.reference_date().ok())
            .unwrap_or_else(Date::null)
    }
}

impl<T: BootstrapTraits + 'static, I: Interpolator + 'static> YieldTermStructure
    for PiecewiseYieldCurve<T, I>
{
    /// Runs the bootstrap before the range check, so `max_date` reflects the
    /// solved curve (the C++ `discountImpl`/`maxDate` both call `calculate`).
    fn discount(&self, t: Time, extrapolate: bool) -> QlResult<DiscountFactor> {
        self.calculate()?;
        self.check_range_time(t, extrapolate)?;
        self.discount_impl(t)
    }

    fn discount_impl(&self, t: Time) -> QlResult<DiscountFactor> {
        self.data.borrow().discount(t)
    }
}

impl<T: BootstrapTraits + 'static, I: Interpolator + 'static> PiecewiseCurve
    for PiecewiseYieldCurve<T, I>
{
    type Traits = T;
    type Interp = I;

    fn instruments(&self) -> &[Shared<dyn RateHelper>] {
        &self.instruments
    }

    fn interpolator(&self) -> &I {
        &self.interpolator
    }

    fn curve_data(&self) -> &RefCell<CurveData<I>> {
        &self.data
    }

    fn accuracy(&self) -> Real {
        self.accuracy
    }

    fn reference_date(&self) -> QlResult<Date> {
        self.base.reference_date()
    }

    fn time_from_reference(&self, date: Date) -> QlResult<Time> {
        TermStructure::time_from_reference(self, date)
    }

    fn term_structure_shared(&self) -> QlResult<Shared<dyn YieldTermStructure>> {
        match self.self_weak.upgrade() {
            Some(curve) => Ok(curve),
            None => crate::fail!("curve dropped before bootstrap"),
        }
    }
}

#[cfg(test)]
mod tests {
    //! Oracle: `piecewiseyieldcurve.cpp` `testCurveConsistency` (tolerance
    //! 1e-9), the **deposits** (`:364-378`) and **swaps** (`:379-403`) sections
    //! only. The round-trip is self-consistent: each instrument is repriced off
    //! the bootstrapped curve and must reproduce its input quote, so there are
    //! no external numbers. The bond, FRA and futures sections and the
    //! `testBMACurveConsistency` half need helpers deferred to #343 and are not
    //! ported here.

    use super::*;
    use crate::handle::Handle;
    use crate::indexes::ibor::euribor::Euribor;
    use crate::indexes::iborindex::IborIndex;
    use crate::indexes::index::Index;
    use crate::instruments::MakeVanillaSwap;
    use crate::math::interpolations::linear::Linear;
    use crate::math::interpolations::loglinear::LogLinear;
    use crate::quotes::{Quote, SimpleQuote};
    use crate::settings::Settings;
    use crate::shared::shared;
    use crate::termstructures::bootstraptraits::Discount;
    use crate::termstructures::yields::{DepositRateHelper, SwapRateHelper};
    use crate::time::businessdayconvention::BusinessDayConvention;
    use crate::time::calendars::target::Target;
    use crate::time::date::Month;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::daycounters::thirty360::{Convention, Thirty360};
    use crate::time::frequency::Frequency;
    use crate::time::period::Period;
    use crate::time::timeunit::TimeUnit;
    use crate::types::Rate;

    // (n, units, rate-in-percent), transcribed from piecewiseyieldcurve.cpp.
    const DEPOSIT_DATA: [(i32, TimeUnit, Rate); 6] = [
        (1, TimeUnit::Weeks, 4.559),
        (1, TimeUnit::Months, 4.581),
        (2, TimeUnit::Months, 4.573),
        (3, TimeUnit::Months, 4.557),
        (6, TimeUnit::Months, 4.496),
        (9, TimeUnit::Months, 4.490),
    ];

    const SWAP_DATA: [(i32, TimeUnit, Rate); 15] = [
        (1, TimeUnit::Years, 4.54),
        (2, TimeUnit::Years, 4.63),
        (3, TimeUnit::Years, 4.75),
        (4, TimeUnit::Years, 4.86),
        (5, TimeUnit::Years, 4.99),
        (6, TimeUnit::Years, 5.11),
        (7, TimeUnit::Years, 5.23),
        (8, TimeUnit::Years, 5.33),
        (9, TimeUnit::Years, 5.41),
        (10, TimeUnit::Years, 5.47),
        (12, TimeUnit::Years, 5.60),
        (15, TimeUnit::Years, 5.75),
        (20, TimeUnit::Years, 5.89),
        (25, TimeUnit::Years, 5.95),
        (30, TimeUnit::Years, 5.96),
    ];

    const TOLERANCE: Real = 1.0e-9;

    struct CommonVars {
        settings: Shared<Settings<Date>>,
        today: Date,
        settlement: Date,
        instruments: Vec<Shared<dyn RateHelper>>,
    }

    fn common_vars() -> CommonVars {
        let calendar = Target::new();
        let today = calendar.adjust(
            Date::new(15, Month::June, 2026),
            BusinessDayConvention::Following,
        );
        let settings = shared(Settings::<Date>::new());
        settings.set_evaluation_date(today);
        let settlement = calendar.advance(
            today,
            2,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );

        let mut instruments: Vec<Shared<dyn RateHelper>> = Vec::new();
        for (n, units, rate) in DEPOSIT_DATA {
            let quote = Handle::new(shared(SimpleQuote::new(rate / 100.0)) as Shared<dyn Quote>);
            let index = Euribor::new(Period::new(n, units), Handle::empty(), settings.clone())
                .expect("deposit tenor is valid");
            instruments.push(DepositRateHelper::new(quote, &index) as Shared<dyn RateHelper>);
        }
        for (n, units, rate) in SWAP_DATA {
            let quote = Handle::new(shared(SimpleQuote::new(rate / 100.0)) as Shared<dyn Quote>);
            let euribor6m = Euribor::six_months(Handle::empty(), settings.clone());
            instruments.push(SwapRateHelper::new(
                quote,
                Period::new(n, units),
                calendar.clone(),
                Frequency::Annual,
                BusinessDayConvention::Unadjusted,
                Thirty360::with_convention(Convention::BondBasis),
                &euribor6m,
            ) as Shared<dyn RateHelper>);
        }

        CommonVars {
            settings,
            today,
            settlement,
            instruments,
        }
    }

    fn euribor6m_on(
        handle: Handle<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> Shared<IborIndex> {
        shared(Euribor::six_months(handle, settings))
    }

    /// The port of `testCurveConsistency<Discount, I, IterativeBootstrap>`,
    /// deposits + swaps only.
    fn check_curve_consistency<I: Interpolator + Default + 'static>() {
        let vars = common_vars();
        let curve = PiecewiseYieldCurve::<Discount, I>::new(
            vars.settlement,
            vars.instruments.clone(),
            Actual360::new(),
            I::default(),
        )
        .unwrap();
        let handle: Handle<dyn YieldTermStructure> =
            Handle::new(Shared::clone(&curve) as Shared<dyn YieldTermStructure>);

        // deposits: a fresh index on the curve handle reprices its own rate
        for (n, units, rate) in DEPOSIT_DATA {
            let index = Euribor::new(Period::new(n, units), handle.clone(), vars.settings.clone())
                .expect("deposit tenor is valid");
            let estimated = index.fixing(vars.today, false).unwrap();
            let expected = rate / 100.0;
            assert!(
                (estimated - expected).abs() <= TOLERANCE,
                "{n} {units:?} deposit: estimated {estimated} vs expected {expected}"
            );
        }

        // swaps: a spot-starting vanilla swap on the curve handle is at par
        let euribor6m = euribor6m_on(handle.clone(), vars.settings.clone());
        for (n, units, rate) in SWAP_DATA {
            let mut swap = MakeVanillaSwap::new(
                Period::new(n, units),
                Shared::clone(&euribor6m),
                Some(0.0),
                Period::new(0, TimeUnit::Days),
                vars.settings.clone(),
            )
            .with_effective_date(vars.settlement)
            .with_discounting_term_structure(handle.clone())
            .with_fixed_leg_day_count(Thirty360::with_convention(Convention::BondBasis))
            .with_fixed_leg_tenor(Period::try_from(Frequency::Annual).unwrap())
            .with_fixed_leg_convention(BusinessDayConvention::Unadjusted)
            .with_fixed_leg_termination_date_convention(BusinessDayConvention::Unadjusted)
            .build()
            .unwrap();

            let estimated = swap.fixed_vs_floating_mut().fair_rate().unwrap();
            let expected = rate / 100.0;
            assert!(
                (estimated - expected).abs() <= TOLERANCE,
                "{n} {units:?} swap: estimated {estimated} vs expected {expected}"
            );
        }
    }

    /// `testLogLinearDiscountConsistency` -> `<Discount, LogLinear>`
    /// (`piecewiseyieldcurve.cpp:676,683`). The `testBMACurveConsistency` half
    /// (`:684`) needs `BMASwapRateHelper` (#343) and is skipped.
    #[test]
    fn log_linear_discount_consistency() {
        check_curve_consistency::<LogLinear>();
    }

    /// `testLinearDiscountConsistency` -> `<Discount, Linear>`
    /// (`piecewiseyieldcurve.cpp:687,694`). The BMA half (`:695`) is skipped.
    #[test]
    fn linear_discount_consistency() {
        check_curve_consistency::<Linear>();
    }

    /// Laziness: constructing the curve runs no bootstrap; the first discount
    /// does; a quote change invalidates and the next read re-bootstraps (the
    /// `testObservability` contract that forbids bootstrapping in the ctor).
    #[test]
    fn bootstrap_is_lazy_and_reruns_on_quote_change() {
        let calendar = Target::new();
        let today = calendar.adjust(
            Date::new(15, Month::June, 2026),
            BusinessDayConvention::Following,
        );
        let settings = shared(Settings::<Date>::new());
        settings.set_evaluation_date(today);
        let settlement = calendar.advance(
            today,
            2,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );

        let quote = shared(SimpleQuote::new(0.04557));
        let index = Euribor::new(
            Period::new(3, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        )
        .unwrap();
        let helper = DepositRateHelper::new(
            Handle::new(Shared::clone(&quote) as Shared<dyn Quote>),
            &index,
        );
        let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
            settlement,
            vec![Shared::clone(&helper) as Shared<dyn RateHelper>],
            Actual360::new(),
            LogLinear,
        )
        .unwrap();

        // cheap construction: no nodes laid out yet
        assert!(!curve.lazy.borrow().is_calculated());

        let df1 = curve.discount_date(helper.maturity_date(), false).unwrap();
        assert!(curve.lazy.borrow().is_calculated());
        assert!(df1 < 1.0 && df1 > 0.0);

        // a quote change invalidates the cache and re-bootstraps to a new curve
        quote.set_value(0.06);
        assert!(!curve.lazy.borrow().is_calculated());
        let df2 = curve.discount_date(helper.maturity_date(), false).unwrap();
        assert!(
            df2 < df1,
            "a higher deposit rate discounts more: {df2} vs {df1}"
        );
    }
}