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
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
//! Bond rate helpers for the yield-curve bootstrap.
//!
//! Port of `ql/termstructures/yield/bondhelpers.{hpp,cpp}`: [`BondHelper`], a
//! bootstrap helper that fits a bond's quoted clean or dirty price, and
//! [`FixedRateBondHelper`], the fixed-coupon constructor over it.
//!
//! Unlike the schedule-derived helpers of
//! [`ratehelpers`](super::ratehelpers), a bond helper is a *fixed*-date helper
//! (the C++ `BondHelper : public RateHelper`, not a `RelativeDateRateHelper`):
//! its bond and its dates are built once, and the hpp warns that "the reference
//! date does not change between calls of `setTermStructure()`". So it uses
//! [`BootstrapHelperBase::new`] and does not observe the evaluation date.
//!
//! The C++ ctor clones the passed bond (`ext::make_shared<Bond>(*bond)`) so the
//! helper has sole ownership of it, guarding against external pricing-engine
//! installs corrupting the bootstrap. This port takes the [`Bond`] by value:
//! the move gives the same sole ownership structurally, with no clone.
//!
//! [`CPIBondHelper`](https://www.quantlib.org) (`bondhelpers.cpp:116`) is not
//! ported: the inflation sibling needs the CPI-bond machinery, which is not on
//! main. The C++ `accept`/`AcyclicVisitor` hooks are dropped, as on every other
//! helper.

use std::cell::RefCell;

use crate::errors::QlResult;
use crate::handle::{Handle, RelinkableHandle};
use crate::instrument::Instrument;
use crate::instruments::{Bond, BondPriceType, FixedRateBond};
use crate::patterns::observable::{AsObservable, Observable};
use crate::pricingengine::PricingEngine;
use crate::pricingengines::DiscountingBondEngine;
use crate::quotes::Quote;
use crate::settings::Settings;
use crate::shared::{Shared, SharedMut, shared, shared_mut};
use crate::termstructures::bootstraphelper::{BootstrapHelperBase, RateHelper};
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::time::businessdayconvention::BusinessDayConvention;
use crate::time::calendar::Calendar;
use crate::time::date::Date;
use crate::time::daycounter::DayCounter;
use crate::time::period::Period;
use crate::time::schedule::Schedule;
use crate::types::{Natural, Rate, Real};

/// Bootstrap helper over a bond's quoted price (`BondHelper`).
///
/// The helper fits the fixed clean (or dirty) price of a bond on the
/// bootstrapping curve. It owns its bond and prices it through a
/// [`DiscountingBondEngine`] installed on the helper's own relinkable handle
/// (`bondhelpers.cpp:40`), so the bond discounts against the curve it is being
/// bootstrapped against.
///
/// [`implied_quote`](RateHelper::implied_quote) forces the bond to recalculate
/// before reading its price (`bondhelpers.cpp:61`): the helper deliberately does
/// not observe the curve (its handle is weak-linked, unobserved), so the bond's
/// cached settlement value would otherwise go stale when the bootstrap moves the
/// curve.
pub struct BondHelper {
    base: BootstrapHelperBase,
    bond: RefCell<Bond>,
    term_structure_handle: RelinkableHandle<dyn YieldTermStructure>,
    price_type: BondPriceType,
}

impl BondHelper {
    /// A bond helper fitting `price` (a clean- or dirty-price handle per
    /// `price_type`) with the schedule of `bond`, which the helper takes sole
    /// ownership of.
    ///
    /// The latest date is the bond's last cash-flow date (later than maturity
    /// when the last coupon is date-adjusted), the earliest date its next
    /// cash-flow date (`bondhelpers.cpp:36-38`).
    ///
    /// # Errors
    ///
    /// The bond's next-cash-flow date resolves the settlement date off the
    /// evaluation date, which must be set (D5/D10).
    pub fn new(
        price: Handle<dyn Quote>,
        bond: Bond,
        price_type: BondPriceType,
    ) -> QlResult<Shared<BondHelper>> {
        let latest = bond
            .cashflows()
            .last()
            .map_or_else(Date::null, |flow| flow.date());
        let earliest = bond.next_cash_flow_date(None)?.unwrap_or_else(Date::null);

        let term_structure_handle = RelinkableHandle::<dyn YieldTermStructure>::empty();
        let engine: SharedMut<dyn PricingEngine> = shared_mut(DiscountingBondEngine::new(
            term_structure_handle.handle(),
            None,
            bond.settings_handle(),
        ));
        let mut bond = bond;
        bond.base_mut().set_pricing_engine(engine);

        let base = BootstrapHelperBase::new(price);
        base.set_earliest_date(earliest);
        base.set_latest_date(latest);

        Ok(shared(BondHelper {
            base,
            bond: RefCell::new(bond),
            term_structure_handle,
            price_type,
        }))
    }

    /// The price convention the helper fits.
    pub fn price_type(&self) -> BondPriceType {
        self.price_type
    }
}

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

impl RateHelper for BondHelper {
    fn base(&self) -> &BootstrapHelperBase {
        &self.base
    }

    /// The bond price implied by the current curve (`bondhelpers.cpp:53-71`).
    ///
    /// The bond is force-recalculated first (the C++ `bond_->recalculate()`,
    /// forced because the helper does not observe the curve); then the clean or
    /// dirty price is returned per the helper's price type.
    fn implied_quote(&self) -> QlResult<Real> {
        self.base.term_structure()?;
        let mut bond = self.bond.borrow_mut();
        bond.recalculate()?;
        match self.price_type {
            BondPriceType::Clean => bond.clean_price(),
            BondPriceType::Dirty => bond.dirty_price(),
        }
    }

    /// Weak-links the helper's own pricing handle to the bootstrapping curve,
    /// then records the curve on the base - both non-owning and unobserved (the
    /// `null_deleter`/`observer = false` of `bondhelpers.cpp:44-51`).
    fn set_term_structure(&self, term_structure: &Shared<dyn YieldTermStructure>) {
        self.term_structure_handle
            .link_to_weak(Shared::downgrade(term_structure));
        self.base.set_term_structure(term_structure);
    }
}

/// Fixed-coupon bond helper for curve bootstrap (`FixedRateBondHelper`).
///
/// The C++ `FixedRateBondHelper` subclasses [`BondHelper`], adding only a
/// constructor that builds a [`FixedRateBond`] internally and an
/// `accept`/visitor override the port drops. With no behaviour to carry, this is
/// a bare constructor returning a [`BondHelper`] over the built bond.
pub struct FixedRateBondHelper;

impl FixedRateBondHelper {
    /// Builds a [`FixedRateBond`] from the coupon schedule and wraps it in a
    /// [`BondHelper`] (`bondhelpers.cpp:81-99`).
    ///
    /// # Errors
    ///
    /// Propagates [`FixedRateBond::new`] and [`BondHelper::new`].
    #[allow(clippy::too_many_arguments)]
    #[allow(clippy::new_ret_no_self)]
    pub fn new(
        price: Handle<dyn Quote>,
        settlement_days: Natural,
        face_amount: Real,
        schedule: Schedule,
        coupons: Vec<Rate>,
        day_counter: DayCounter,
        payment_convention: BusinessDayConvention,
        redemption: Real,
        issue_date: Option<Date>,
        payment_calendar: Option<Calendar>,
        ex_coupon_period: Option<Period>,
        ex_coupon_calendar: Calendar,
        ex_coupon_convention: BusinessDayConvention,
        ex_coupon_end_of_month: bool,
        price_type: BondPriceType,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Shared<BondHelper>> {
        let bond = FixedRateBond::new(
            settlement_days,
            face_amount,
            schedule,
            coupons,
            day_counter,
            payment_convention,
            redemption,
            issue_date,
            payment_calendar,
            ex_coupon_period,
            ex_coupon_calendar,
            ex_coupon_convention,
            ex_coupon_end_of_month,
            None,
            settings,
        )?;
        BondHelper::new(price, bond.into_bond(), price_type)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::interestrate::Compounding;
    use crate::quotes::SimpleQuote;
    use crate::termstructures::yields::FlatForward;
    use crate::test_support::{Flag, as_observer};
    use crate::time::businessdayconvention::BusinessDayConvention;
    use crate::time::calendars::nullcalendar::NullCalendar;
    use crate::time::calendars::target::Target;
    use crate::time::date::Month;
    use crate::time::dategenerationrule::DateGeneration;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::daycounters::actualactual::{ActualActual, Convention};
    use crate::time::frequency::Frequency;

    fn today() -> Date {
        Date::new(15, Month::June, 2026)
    }

    fn settings_on(today: Date) -> Shared<Settings<Date>> {
        let settings = shared(Settings::<Date>::new());
        settings.set_evaluation_date(today);
        settings
    }

    fn flat_curve(reference: Date, rate: Rate) -> Shared<dyn YieldTermStructure> {
        shared(FlatForward::with_rate(
            reference,
            rate,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>
    }

    /// A five-year semiannual 5% bond issued a year before the evaluation date.
    fn bond_schedule() -> Schedule {
        Schedule::new(
            Date::new(15, Month::June, 2025),
            Date::new(15, Month::June, 2030),
            Period::try_from(Frequency::Semiannual).unwrap(),
            Target::new(),
            BusinessDayConvention::Following,
            BusinessDayConvention::Following,
            DateGeneration::Backward,
            false,
            Date::null(),
            Date::null(),
        )
    }

    fn a_helper(
        price: Handle<dyn Quote>,
        price_type: BondPriceType,
        settings: Shared<Settings<Date>>,
    ) -> Shared<BondHelper> {
        FixedRateBondHelper::new(
            price,
            3,
            100.0,
            bond_schedule(),
            vec![0.05],
            ActualActual::with_convention(Convention::ISDA),
            BusinessDayConvention::Following,
            100.0,
            Some(Date::new(15, Month::June, 2025)),
            None,
            None,
            NullCalendar::new(),
            BusinessDayConvention::Unadjusted,
            false,
            price_type,
            settings,
        )
        .unwrap()
    }

    /// An independently built copy of the same bond, priced over `curve` by its
    /// own engine, for a cross-implementation identity against the helper.
    fn independent_bond(
        curve: &Shared<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> FixedRateBond {
        let mut bond = FixedRateBond::new(
            3,
            100.0,
            bond_schedule(),
            vec![0.05],
            ActualActual::with_convention(Convention::ISDA),
            BusinessDayConvention::Following,
            100.0,
            Some(Date::new(15, Month::June, 2025)),
            None,
            None,
            NullCalendar::new(),
            BusinessDayConvention::Unadjusted,
            false,
            None,
            Shared::clone(&settings),
        )
        .unwrap();
        let handle = Handle::new(Shared::clone(curve));
        let engine = shared_mut(DiscountingBondEngine::new(handle, None, settings))
            as SharedMut<dyn PricingEngine>;
        bond.bond_mut().base_mut().set_pricing_engine(engine);
        bond
    }

    /// The helper's implied quote is the clean price the same bond fetches from
    /// an independent engine over the same curve - the helper prices its own
    /// bond off the curve it is bootstrapped against.
    #[test]
    fn implied_quote_matches_the_independent_clean_price() {
        let settings = settings_on(today());
        let helper = a_helper(
            Handle::new(shared(SimpleQuote::new(100.0)) as Shared<dyn Quote>),
            BondPriceType::Clean,
            Shared::clone(&settings),
        );
        let curve = flat_curve(today(), 0.04);
        helper.set_term_structure(&curve);

        let implied = helper.implied_quote().unwrap();
        let mut independent = independent_bond(&curve, settings);
        let clean = independent.bond_mut().clean_price().unwrap();
        assert!(
            (implied - clean).abs() < 1e-10,
            "implied {implied} vs clean {clean}"
        );
    }

    /// The dirty price type folds in the accrued interest, so it exceeds the
    /// clean quote by exactly the bond's accrued amount at settlement.
    #[test]
    fn dirty_price_type_adds_the_accrued_amount() {
        let settings = settings_on(today());
        let curve = flat_curve(today(), 0.04);

        let clean_helper = a_helper(
            Handle::new(shared(SimpleQuote::new(100.0)) as Shared<dyn Quote>),
            BondPriceType::Clean,
            Shared::clone(&settings),
        );
        clean_helper.set_term_structure(&curve);
        let clean = clean_helper.implied_quote().unwrap();

        let dirty_helper = a_helper(
            Handle::new(shared(SimpleQuote::new(100.0)) as Shared<dyn Quote>),
            BondPriceType::Dirty,
            Shared::clone(&settings),
        );
        dirty_helper.set_term_structure(&curve);
        let dirty = dirty_helper.implied_quote().unwrap();

        let independent = independent_bond(&curve, settings);
        let settlement = independent.bond().settlement_date(None).unwrap();
        let accrued = independent.bond().accrued_amount(Some(settlement)).unwrap();
        assert!(accrued > 0.0, "the bond is mid-coupon and accruing");
        assert!(
            (dirty - (clean + accrued)).abs() < 1e-10,
            "dirty {dirty} vs clean+accrued {}",
            clean + accrued
        );
    }

    /// Moving the curve (mutating its quote, not relinking) changes the implied
    /// quote though the helper never observes the curve and gets no
    /// notification - proving `implied_quote` forces a fresh calculation rather
    /// than reading the bond's stale settlement value.
    #[test]
    fn moving_the_curve_updates_the_quote_without_notifying_the_helper() {
        let settings = settings_on(today());
        let helper = a_helper(
            Handle::new(shared(SimpleQuote::new(100.0)) as Shared<dyn Quote>),
            BondPriceType::Clean,
            settings,
        );

        let quote = shared(SimpleQuote::new(0.03));
        let curve: Shared<dyn YieldTermStructure> = shared(FlatForward::new(
            today(),
            Handle::new(Shared::clone(&quote) as Shared<dyn Quote>),
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        ));
        helper.set_term_structure(&curve);
        let before = helper.implied_quote().unwrap();

        let flag = Flag::new();
        helper.observable().register_observer(&as_observer(&flag));

        quote.set_value(0.06);
        assert!(
            !Flag::is_up(&flag),
            "the helper must not observe the bootstrapping curve"
        );

        let after = helper.implied_quote().unwrap();
        assert!(
            (after - before).abs() > 1e-6,
            "the forced recalculation must surface the curve move without a notification"
        );
    }

    /// The helper's dates come from the bond: the earliest is the next
    /// cash-flow date, the latest the last cash-flow date (later than the
    /// 2030-06-15 maturity because that Saturday redemption rolls to Monday
    /// under `Following`, the `bondhelpers.cpp:36` adjustment), and (with no
    /// pillar set) the pillar falls back to the latest.
    #[test]
    fn dates_follow_the_bond_cashflows() {
        let settings = settings_on(today());
        let helper = a_helper(
            Handle::new(shared(SimpleQuote::new(100.0)) as Shared<dyn Quote>),
            BondPriceType::Clean,
            settings,
        );

        assert_eq!(
            helper.latest_date(),
            Date::new(17, Month::June, 2030),
            "the last cash flow is the redemption rolled off the 2030-06-15 maturity"
        );
        assert!(
            helper.latest_date() > Date::new(15, Month::June, 2030),
            "the adjusted last-payment date is later than the maturity date"
        );
        assert!(
            helper.earliest_date() > today(),
            "the next cash flow after settlement is in the future"
        );
        assert_eq!(
            helper.pillar_date(),
            helper.latest_date(),
            "with no pillar set, the pillar falls back to the latest date"
        );
    }

    /// `piecewiseyieldcurve.cpp testCurveConsistency` bonds section (`:405-439`):
    /// a discount curve bootstrapped purely from [`FixedRateBondHelper`]s
    /// reprices every bond to its quoted clean price. This is a round-trip - the
    /// helpers solve the curve to fit the quotes, and repricing recovers them -
    /// so it holds for any evaluation date; a fixed one is chosen for
    /// determinism, standing in for the C++ `Date::todaysDate()`.
    ///
    /// The three date bases are kept distinct, as in `CommonVars`: `today =
    /// TARGET.adjust(evalDate)`, the curve reference `settlement = today + 2`
    /// business days, and `bondSettlementDays = 3`. Each bond is seasoned -
    /// `maturity = today + n`, `issue = maturity - length years` - so its
    /// schedule starts in the past. The curve traits and interpolation are the
    /// `<Discount, LogLinear, IterativeBootstrap>` of `piecewiseyieldcurve.cpp:683`.
    ///
    /// This is one of the seven `testCurveConsistency` checks; the deposits and
    /// swaps sections landed with their helpers, and the FRA / futures / BMA
    /// sections stay deferred (#343).
    #[test]
    fn bond_bootstrap_reprices_the_quotes() {
        use crate::math::interpolations::loglinear::LogLinear;
        use crate::termstructures::bootstraptraits::Discount;
        use crate::termstructures::yields::PiecewiseYieldCurve;
        use crate::time::timeunit::TimeUnit;

        const BOND_DATA: [(i32, TimeUnit, i32, Real, Real); 5] = [
            (6, TimeUnit::Months, 5, 4.75, 101.320),
            (1, TimeUnit::Years, 3, 2.75, 100.590),
            (2, TimeUnit::Years, 5, 5.00, 105.650),
            (5, TimeUnit::Years, 11, 5.50, 113.610),
            (10, TimeUnit::Years, 11, 3.75, 104.070),
        ];
        const BOND_SETTLEMENT_DAYS: Natural = 3;
        const TOLERANCE: Real = 1.0e-9;

        let calendar = Target::new();
        let today = calendar.adjust(
            Date::new(15, Month::June, 2026),
            BusinessDayConvention::Following,
        );
        let settings = settings_on(today);
        let settlement = calendar.advance(
            today,
            2,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );
        let bond_day_counter = ActualActual::with_convention(Convention::ISDA);

        let schedule_for = |n: i32, unit: TimeUnit, length: i32| -> (Schedule, Date) {
            let maturity =
                calendar.advance(today, n, unit, BusinessDayConvention::Following, false);
            let issue = calendar.advance(
                maturity,
                -length,
                TimeUnit::Years,
                BusinessDayConvention::Following,
                false,
            );
            let schedule = Schedule::new(
                issue,
                maturity,
                Period::try_from(Frequency::Semiannual).unwrap(),
                calendar.clone(),
                BusinessDayConvention::Following,
                BusinessDayConvention::Following,
                DateGeneration::Backward,
                false,
                Date::null(),
                Date::null(),
            );
            (schedule, issue)
        };

        let mut helpers: Vec<Shared<dyn RateHelper>> = Vec::new();
        for (n, unit, length, coupon, price) in BOND_DATA {
            let (schedule, issue) = schedule_for(n, unit, length);
            let quote = Handle::new(shared(SimpleQuote::new(price)) as Shared<dyn Quote>);
            let helper = FixedRateBondHelper::new(
                quote,
                BOND_SETTLEMENT_DAYS,
                100.0,
                schedule,
                vec![coupon / 100.0],
                bond_day_counter.clone(),
                BusinessDayConvention::Following,
                100.0,
                Some(issue),
                None,
                None,
                NullCalendar::new(),
                BusinessDayConvention::Unadjusted,
                false,
                BondPriceType::Clean,
                settings.clone(),
            )
            .unwrap();
            helpers.push(helper as Shared<dyn RateHelper>);
        }

        let curve = PiecewiseYieldCurve::<Discount, LogLinear>::new(
            settlement,
            helpers,
            Actual360::new(),
            LogLinear,
        )
        .unwrap();
        let handle: Handle<dyn YieldTermStructure> =
            Handle::new(Shared::clone(&curve) as Shared<dyn YieldTermStructure>);

        for (n, unit, length, coupon, price) in BOND_DATA {
            let (schedule, issue) = schedule_for(n, unit, length);
            let mut bond = FixedRateBond::new(
                BOND_SETTLEMENT_DAYS,
                100.0,
                schedule,
                vec![coupon / 100.0],
                bond_day_counter.clone(),
                BusinessDayConvention::Following,
                100.0,
                Some(issue),
                None,
                None,
                NullCalendar::new(),
                BusinessDayConvention::Unadjusted,
                false,
                None,
                settings.clone(),
            )
            .unwrap();
            let engine = shared_mut(DiscountingBondEngine::new(
                handle.clone(),
                None,
                settings.clone(),
            )) as SharedMut<dyn PricingEngine>;
            bond.bond_mut().base_mut().set_pricing_engine(engine);

            let estimated = bond.bond_mut().clean_price().unwrap();
            assert!(
                (estimated - price).abs() < TOLERANCE,
                "{n} {unit:?} bond: estimated {estimated} vs expected {price} (error {})",
                (estimated - price).abs()
            );
        }
    }
}