libitofin 0.7.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
//! Coupons: cash flows that accrue over a period.
//!
//! Port of `ql/cashflows/coupon.{hpp,cpp}`. A [`Coupon`] is a
//! [`CashFlow`] whose amount accrues over `[accrual_start_date,
//! accrual_end_date]` against a nominal, measured by a [`DayCounter`] over an
//! optional reference period. It is the base of `FixedRateCoupon` and
//! `FloatingRateCoupon`.
//!
//! ## Shape
//!
//! C++ inherits the coupon's dates and nominal from an abstract `Coupon` base.
//! Rust splits that into the [`Coupon`] trait (the interface, plus the accrual
//! algebra as provided methods) and [`CouponBase`] (the state). An implementor
//! holds a `CouponBase` and hands it out through [`Coupon::coupon_base`]; the
//! provided methods read the dates from there. Both are public, so a concrete
//! coupon can be written outside this crate.
//!
//! [`Coupon`] is *not* a subtrait of [`CashFlow`], though C++ derives one from
//! the other. It restates the surface it needs and the blanket
//! `impl<T: Coupon> CashFlow for T` below gives every coupon its
//! [`CashFlow`] and [`Event`] faces, deriving them from [`CouponBase`] and from
//! [`Coupon::amount`]. A coupon therefore cannot forget - or get wrong -
//! [`Event::has_occurred`], [`CashFlow::ex_coupon_date`] or
//! [`CashFlow::as_coupon`], the three whose wrong-but-compiling answers are
//! plausible numbers rather than diagnostics.
//!
//! The subtrait shape cannot do this. A blanket impl for `Coupon: CashFlow`
//! *provides* [`CashFlow::amount`], so [`FixedRateCoupon`] would silently
//! inherit a generic body in place of its compounded one, and could not
//! override it: a competing `impl CashFlow for FixedRateCoupon` is a
//! conflicting implementation. Hence the sever, and hence `amount` moves onto
//! [`Coupon`].
//!
//! The blanket takes an implicitly [`Sized`] `T`, because the `Some(self)` of
//! [`CashFlow::as_coupon`] is an unsizing coercion. So `dyn Coupon` does not
//! itself implement [`CashFlow`]; `+ ?Sized` would restore that and forbid
//! `Some(self)`, and nothing needs it. The analytics of
//! [`CashFlows`](crate::cashflows::CashFlows) hold a `&dyn CashFlow` already and
//! read only this trait's own methods through the coupon view.
//!
//! ## Divergences from QuantLib
//!
//! `Coupon` caches [`accrual_period`](Coupon::accrual_period) in a `mutable`
//! member seeded with `Null<Real>`. The cache has no behavioural effect and is
//! omitted here, in keeping with [`CashFlow`] leaving `LazyObject` caching to
//! the concrete flows.
//!
//! [`accrued_period`](Coupon::accrued_period) needs to know whether the coupon
//! trades ex-coupon at the date it is given. C++ calls
//! `tradingExCoupon(d)`, which resolves a null date against the evaluation date;
//! here the date is always explicit, so the check reduces to
//! [`trades_ex_coupon_on`](Coupon::trades_ex_coupon_on), and no
//! [`Settings`](crate::settings::Settings) is threaded through.
//!
//! C++ reads the ex-coupon date off a single member (`coupon.hpp:57`), shared
//! by the accrual and by `CashFlow::exCouponDate()`. The port keeps that single
//! reader: [`trades_ex_coupon_on`](Coupon::trades_ex_coupon_on) and the blanket
//! [`CashFlow::ex_coupon_date`] both go through
//! [`CouponBase::ex_coupon_date`], and neither is an implementor's to write.
//!
//! [`amount`](Coupon::amount), [`rate`](Coupon::rate) and
//! [`accrued_amount`](Coupon::accrued_amount) return [`QlResult`]: a
//! floating-rate coupon reads an index fixing that may be missing. The
//! `accept(AcyclicVisitor&)` override has no counterpart in the port;
//! `coupon_cast` becomes [`CashFlow::as_coupon`], which the blanket answers.
//!
//! [`FixedRateCoupon`]: crate::cashflows::FixedRateCoupon

use crate::cashflow::{CashFlow, cash_flow_has_occurred};
use crate::event::Event;
use crate::patterns::observable::AsObservable;
use crate::settings::Settings;
use crate::time::date::{Date, SerialNumber};
use crate::time::daycounter::DayCounter;
use crate::types::{Rate, Real, Time};

use crate::errors::QlResult;

/// The dates and nominal every [`Coupon`] carries.
///
/// Mirrors the protected state of QuantLib's `Coupon`. A concrete coupon owns
/// one and exposes it through [`Coupon::coupon_base`].
#[derive(Clone, Debug)]
pub struct CouponBase {
    payment_date: Date,
    nominal: Real,
    accrual_start_date: Date,
    accrual_end_date: Date,
    ref_period_start: Date,
    ref_period_end: Date,
    ex_coupon_date: Option<Date>,
}

impl CouponBase {
    /// A coupon accruing `nominal` over `[accrual_start_date, accrual_end_date]`
    /// and paid on `payment_date`, which must already be a business day: the
    /// coupon does not adjust it.
    ///
    /// A `None` reference-period bound defaults to the matching accrual date,
    /// as a null `Date` does in C++.
    pub fn new(
        payment_date: Date,
        nominal: Real,
        accrual_start_date: Date,
        accrual_end_date: Date,
        ref_period_start: Option<Date>,
        ref_period_end: Option<Date>,
        ex_coupon_date: Option<Date>,
    ) -> CouponBase {
        CouponBase {
            payment_date,
            nominal,
            accrual_start_date,
            accrual_end_date,
            ref_period_start: ref_period_start.unwrap_or(accrual_start_date),
            ref_period_end: ref_period_end.unwrap_or(accrual_end_date),
            ex_coupon_date,
        }
    }

    /// The date the coupon is paid on.
    pub fn payment_date(&self) -> Date {
        self.payment_date
    }

    /// The date from which the coupon trades ex-coupon, when it has one.
    pub fn ex_coupon_date(&self) -> Option<Date> {
        self.ex_coupon_date
    }
}

/// A [`CashFlow`] accruing over a fixed period.
///
/// Mirrors QuantLib's `Coupon`: still abstract, but it gives implementors the
/// accrual-date algebra. Implementors supply the state through
/// [`coupon_base`](Self::coupon_base), the [`amount`](Self::amount) the coupon
/// pays, the [`rate`](Self::rate) and [`day_counter`](Self::day_counter) the
/// accrual is measured with, and the
/// [`accrued_amount`](Self::accrued_amount) that rate implies.
///
/// Implementing it is enough to be a [`CashFlow`]: the blanket impl below
/// supplies that face, so nothing else here is an implementor's to get wrong.
pub trait Coupon: AsObservable {
    /// The coupon's dates and nominal.
    fn coupon_base(&self) -> &CouponBase;

    /// The amount paid at the [`payment_date`](CouponBase::payment_date),
    /// undiscounted.
    ///
    /// The body behind [`CashFlow::amount`] for every coupon.
    fn amount(&self) -> QlResult<Real>;

    /// The rate the coupon accrues at.
    fn rate(&self) -> QlResult<Rate>;

    /// The day counter the accrual is measured with.
    fn day_counter(&self) -> DayCounter;

    /// The amount accrued up to `date`.
    fn accrued_amount(&self, date: Date) -> QlResult<Real>;

    /// The nominal the coupon accrues on.
    ///
    /// Virtual in C++ (`coupon.hpp:61`), though no `Coupon` subclass in
    /// QuantLib overrides it.
    fn nominal(&self) -> Real {
        self.coupon_base().nominal
    }

    /// The start of the accrual period.
    fn accrual_start_date(&self) -> Date {
        self.coupon_base().accrual_start_date
    }

    /// The end of the accrual period.
    fn accrual_end_date(&self) -> Date {
        self.coupon_base().accrual_end_date
    }

    /// The start of the reference period.
    fn reference_period_start(&self) -> Date {
        self.coupon_base().ref_period_start
    }

    /// The end of the reference period.
    fn reference_period_end(&self) -> Date {
        self.coupon_base().ref_period_end
    }

    /// The whole accrual period as a fraction of a year.
    fn accrual_period(&self) -> Time {
        let base = self.coupon_base();
        self.day_counter().year_fraction_ref(
            base.accrual_start_date,
            base.accrual_end_date,
            base.ref_period_start,
            base.ref_period_end,
        )
    }

    /// The whole accrual period in days.
    fn accrual_days(&self) -> SerialNumber {
        let base = self.coupon_base();
        self.day_counter()
            .day_count(base.accrual_start_date, base.accrual_end_date)
    }

    /// Whether the coupon trades ex-coupon on `date`.
    ///
    /// The `tradingExCoupon(d)` of `coupon.hpp` with the date always given.
    /// [`CashFlow::trading_ex_coupon`] is the counterpart that resolves an
    /// absent date against the evaluation date, and reads the same
    /// [`CouponBase::ex_coupon_date`].
    fn trades_ex_coupon_on(&self, date: Date) -> bool {
        self.coupon_base()
            .ex_coupon_date()
            .is_some_and(|ex_coupon| ex_coupon <= date)
    }

    /// The period accrued up to `date`, as a fraction of a year.
    ///
    /// Zero outside `(accrual_start_date, payment_date]`. Once the coupon
    /// trades ex-coupon the sign flips: the buyer does not receive the coupon,
    /// so what accrues is the *negative* fraction from `date` forward to the
    /// accrual end, and it returns to zero at the accrual end. This is the one
    /// place the two accrual measures disagree: [`accrued_days`](Self::accrued_days)
    /// has no ex-coupon branch and keeps counting forward from the accrual
    /// start.
    fn accrued_period(&self, date: Date) -> Time {
        let base = self.coupon_base();
        if date <= base.accrual_start_date || date > base.payment_date {
            0.0
        } else if self.trades_ex_coupon_on(date) {
            -self.day_counter().year_fraction_ref(
                date,
                date.max(base.accrual_end_date),
                base.ref_period_start,
                base.ref_period_end,
            )
        } else {
            self.day_counter().year_fraction_ref(
                base.accrual_start_date,
                date.min(base.accrual_end_date),
                base.ref_period_start,
                base.ref_period_end,
            )
        }
    }

    /// The days accrued up to `date`.
    ///
    /// Zero outside `(accrual_start_date, payment_date]`, and otherwise the day
    /// count from the accrual start, capped at the accrual end. Unlike
    /// [`accrued_period`](Self::accrued_period) this never goes negative.
    fn accrued_days(&self, date: Date) -> SerialNumber {
        let base = self.coupon_base();
        if date <= base.accrual_start_date || date > base.payment_date {
            0
        } else {
            self.day_counter()
                .day_count(base.accrual_start_date, date.min(base.accrual_end_date))
        }
    }
}

/// Every [`Coupon`] is an [`Event`] on its payment date, under the cash-flow
/// occurrence rule rather than the plain-event one.
impl<T: Coupon> Event for T {
    fn date(&self) -> Date {
        self.coupon_base().payment_date()
    }

    fn has_occurred(
        &self,
        settings: &Settings<Date>,
        ref_date: Option<Date>,
        include_ref_date: Option<bool>,
    ) -> QlResult<bool> {
        cash_flow_has_occurred(
            self.coupon_base().payment_date(),
            settings,
            ref_date,
            include_ref_date,
        )
    }
}

/// Every [`Coupon`] is a [`CashFlow`] paying what it accrues.
impl<T: Coupon> CashFlow for T {
    fn amount(&self) -> QlResult<Real> {
        Coupon::amount(self)
    }

    fn ex_coupon_date(&self) -> Option<Date> {
        self.coupon_base().ex_coupon_date()
    }

    fn as_coupon(&self) -> Option<&dyn Coupon> {
        Some(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::patterns::observable::Observable;
    use crate::time::date::Month;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::daycounters::thirty360::{Convention, Thirty360};

    struct TestCoupon {
        base: CouponBase,
        rate: Rate,
        day_counter: DayCounter,
        observable: Observable,
    }

    impl TestCoupon {
        fn new(base: CouponBase, rate: Rate, day_counter: DayCounter) -> TestCoupon {
            TestCoupon {
                base,
                rate,
                day_counter,
                observable: Observable::new(),
            }
        }
    }

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

    impl Coupon for TestCoupon {
        fn coupon_base(&self) -> &CouponBase {
            &self.base
        }

        fn amount(&self) -> QlResult<Real> {
            Ok(self.nominal() * self.rate * self.accrual_period())
        }

        fn rate(&self) -> QlResult<Rate> {
            Ok(self.rate)
        }

        fn day_counter(&self) -> DayCounter {
            self.day_counter.clone()
        }

        fn accrued_amount(&self, date: Date) -> QlResult<Real> {
            Ok(self.nominal() * self.rate * self.accrued_period(date))
        }
    }

    fn start() -> Date {
        Date::new(15, Month::January, 2026)
    }

    fn end() -> Date {
        Date::new(15, Month::July, 2026)
    }

    fn payment() -> Date {
        Date::new(20, Month::July, 2026)
    }

    fn coupon(ex_coupon_date: Option<Date>) -> TestCoupon {
        TestCoupon::new(
            CouponBase::new(payment(), 100.0, start(), end(), None, None, ex_coupon_date),
            0.03,
            Actual360::new(),
        )
    }

    #[test]
    fn an_absent_reference_period_defaults_to_the_accrual_period() {
        let coupon = coupon(None);

        assert_eq!(coupon.reference_period_start(), start());
        assert_eq!(coupon.reference_period_end(), end());
    }

    #[test]
    fn an_explicit_reference_period_is_kept() {
        let ref_start = Date::new(15, Month::December, 2025);
        let ref_end = Date::new(15, Month::June, 2026);
        let coupon = TestCoupon::new(
            CouponBase::new(
                payment(),
                100.0,
                start(),
                end(),
                Some(ref_start),
                Some(ref_end),
                None,
            ),
            0.03,
            Actual360::new(),
        );

        assert_eq!(coupon.reference_period_start(), ref_start);
        assert_eq!(coupon.reference_period_end(), ref_end);
    }

    #[test]
    fn the_accrual_period_spans_the_accrual_dates() {
        let coupon = coupon(None);

        assert_eq!(coupon.accrual_days(), 181);
        assert!((coupon.accrual_period() - 181.0 / 360.0).abs() < 1e-15);
        assert_eq!(coupon.date(), payment());
        assert_eq!(coupon.nominal(), 100.0);
    }

    #[test]
    fn nothing_accrues_before_the_accrual_start() {
        let coupon = coupon(None);

        assert_eq!(coupon.accrued_period(start() - 1), 0.0);
        assert_eq!(coupon.accrued_days(start() - 1), 0);
        assert_eq!(coupon.accrued_period(start()), 0.0);
        assert_eq!(coupon.accrued_days(start()), 0);
        assert_eq!(coupon.accrued_amount(start()).unwrap(), 0.0);
    }

    #[test]
    fn nothing_accrues_after_the_payment_date() {
        let coupon = coupon(None);

        assert_eq!(coupon.accrued_period(payment() + 1), 0.0);
        assert_eq!(coupon.accrued_days(payment() + 1), 0);
    }

    #[test]
    fn accrual_grows_from_the_accrual_start_and_is_capped_at_the_accrual_end() {
        let coupon = coupon(None);
        let mid = Date::new(15, Month::April, 2026);

        assert_eq!(coupon.accrued_days(mid), 90);
        assert!((coupon.accrued_period(mid) - 90.0 / 360.0).abs() < 1e-15);
        assert!((coupon.accrued_amount(mid).unwrap() - 100.0 * 0.03 * 90.0 / 360.0).abs() < 1e-13);

        assert_eq!(coupon.accrued_days(end()), 181);
        assert_eq!(coupon.accrued_days(payment()), 181);
        assert!((coupon.accrued_period(payment()) - 181.0 / 360.0).abs() < 1e-15);
    }

    /// `accruedPeriod` flips sign once the coupon trades ex-coupon, while
    /// `accruedDays` has no such branch and keeps counting forward.
    #[test]
    fn the_accrued_period_goes_negative_ex_coupon_while_the_days_keep_counting() {
        let ex_coupon = Date::new(1, Month::July, 2026);
        let coupon = coupon(Some(ex_coupon));
        let after = Date::new(5, Month::July, 2026);

        assert!(coupon.accrued_period(ex_coupon - 1) > 0.0);
        assert_eq!(coupon.accrued_days(ex_coupon - 1), 166);

        assert!((coupon.accrued_period(ex_coupon) + 14.0 / 360.0).abs() < 1e-15);
        assert_eq!(coupon.accrued_days(ex_coupon), 167);

        assert!((coupon.accrued_period(after) + 10.0 / 360.0).abs() < 1e-15);
        assert_eq!(coupon.accrued_days(after), 171);

        assert!(
            (coupon.accrued_amount(ex_coupon).unwrap() + 100.0 * 0.03 * 14.0 / 360.0).abs() < 1e-13
        );
    }

    /// From the accrual end on, `max(d, accrualEndDate)` is `d` itself, so the
    /// negative branch measures an empty period.
    #[test]
    fn the_negative_accrual_returns_to_zero_at_the_accrual_end() {
        let coupon = coupon(Some(Date::new(1, Month::July, 2026)));

        assert_eq!(coupon.accrued_period(end()), 0.0);
        assert_eq!(coupon.accrued_period(payment()), 0.0);
        assert_eq!(coupon.accrued_days(end()), 181);
        assert_eq!(coupon.accrued_days(payment()), 181);
    }

    /// An ex-coupon date the accrual never reaches leaves the positive branch
    /// in charge throughout.
    #[test]
    fn an_ex_coupon_date_after_the_payment_date_never_bites() {
        let coupon = coupon(Some(payment() + 1));

        assert!((coupon.accrued_period(payment()) - 181.0 / 360.0).abs() < 1e-15);
    }

    /// The reference period is passed through to the day counter, so a
    /// convention that reads it sees the coupon's own dates.
    #[test]
    fn the_reference_period_reaches_the_day_counter() {
        let coupon = TestCoupon::new(
            CouponBase::new(payment(), 100.0, start(), end(), None, None, None),
            0.03,
            Thirty360::with_convention(Convention::BondBasis),
        );

        assert_eq!(coupon.accrual_days(), 180);
        assert!((coupon.accrual_period() - 0.5).abs() < 1e-15);
    }
}