libitofin 0.52.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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Cap, floor and collar instruments.
//!
//! Port of `ql/instruments/capfloor.{hpp,cpp}`. A [`CapFloor`] is an
//! [`Instrument`] over a floating leg plus per-coupon cap and/or floor strike
//! vectors and a [`CapFloorType`]; [`CapFloor::cap`], [`CapFloor::floor`] and
//! [`CapFloor::collar`] are the thin constructors the C++ `Cap`/`Floor`/`Collar`
//! subclasses provide. [`setup_arguments`](Instrument::setup_arguments) fills the
//! [`CapFloorArguments`] a `CapFloor::engine` reads.
//!
//! ## Leg shape
//!
//! Ibor and overnight constructors retain their concrete coupons. Both feed the
//! same engine arguments using `(rate - spread) / gearing`; overnight coupons
//! supply their last fixing date. Legacy Ibor coupon inspectors remain unchanged.
//!
//! ## Divergences from QuantLib
//!
//! - Arbitrary user-defined floating coupon types are not accepted.
//! - [`MakeCapFloor`](super::MakeCapFloor) builds the market cap/floor and
//!   [`CapFloor::last_floating_rate_coupon`] exposes the trailing coupon the
//!   optionlet stripper reads; `impliedVolatility` and `deepUpdate` remain unported.
//!   [`CapFloor::optionlet`] retains a shared coupon without inheriting an engine.
//! - The `CapFloor::arguments` bundle carries `start_dates` (read by the analytic
//!   Hull-White engine to form each optionlet's exercise maturity, #438); the C++
//!   `spreads` and `indexes` are filled but unread by any ported engine, so they
//!   remain omitted.
//! - The D5 `Settings` handle replaces `Settings::instance()` for the evaluation
//!   date the expiry check and the forward guard read.

use std::any::Any;

use crate::cashflow::{CashFlow, Leg};
use crate::cashflows::{CashFlows, Coupon, IborCoupon, OvernightIndexedCoupon};
use crate::errors::QlResult;
use crate::event::Event;
use crate::instrument::{Instrument, InstrumentBase};
use crate::patterns::observable::AsObservable;
use crate::pricingengine::Arguments;
use crate::settings::Settings;
use crate::shared::Shared;
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::time::date::Date;
use crate::types::{Rate, Real, Time};
use crate::{fail, require};

/// Whether the instrument caps, floors or collars its floating leg
/// (`CapFloor::Type`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CapFloorType {
    /// A cap: long a call on each coupon's rate at the cap strike.
    Cap,
    /// A floor: long a put on each coupon's rate at the floor strike.
    Floor,
    /// A collar: long the cap, short the floor.
    Collar,
}

/// Argument bundle a `CapFloor::engine` prices (`CapFloor::arguments`).
///
/// Per optionlet: the payment date (`end_dates`), fixing date, accrual time,
/// nominal, gearing, the coupon's adjusted forward (`None` for a past-fixing
/// coupon, the C++ `Null<Rate>`), and the de-spread cap and floor strikes
/// (`None` where the type has none).
#[derive(Default)]
pub struct CapFloorArguments {
    /// The instrument type, set by `setup_arguments`.
    pub cap_floor_type: Option<CapFloorType>,
    /// Each coupon's accrual start date (the C++ `startDates`), the exercise
    /// maturity the analytic Hull-White engine forms its bond option from.
    pub start_dates: Vec<Date>,
    /// Each coupon's fixing date.
    pub fixing_dates: Vec<Date>,
    /// Each coupon's payment date (the C++ `endDates`).
    pub end_dates: Vec<Date>,
    /// Each coupon's accrual period as a year fraction.
    pub accrual_times: Vec<Time>,
    /// Each coupon's de-spread cap strike, `None` for a pure floor.
    pub cap_rates: Vec<Option<Rate>>,
    /// Each coupon's de-spread floor strike, `None` for a pure cap.
    pub floor_rates: Vec<Option<Rate>>,
    /// Each coupon's adjusted forward, `None` when its fixing has passed.
    pub forwards: Vec<Option<Rate>>,
    /// Each coupon's gearing.
    pub gearings: Vec<Real>,
    /// Each coupon's nominal.
    pub nominals: Vec<Real>,
}

impl Arguments for CapFloorArguments {
    fn validate(&self) -> QlResult<()> {
        let n = self.end_dates.len();
        require!(self.cap_floor_type.is_some(), "cap/floor type not set");
        require!(self.start_dates.len() == n, "start-date count mismatch");
        require!(self.fixing_dates.len() == n, "fixing-date count mismatch");
        require!(self.accrual_times.len() == n, "accrual-time count mismatch");
        require!(self.cap_rates.len() == n, "cap-rate count mismatch");
        require!(self.floor_rates.len() == n, "floor-rate count mismatch");
        require!(self.forwards.len() == n, "forward count mismatch");
        require!(self.gearings.len() == n, "gearing count mismatch");
        require!(self.nominals.len() == n, "nominal count mismatch");
        Ok(())
    }
}

/// A cap, floor or collar over an Ibor or overnight leg.
pub struct CapFloor {
    base: InstrumentBase,
    cap_floor_type: CapFloorType,
    coupons: Vec<Shared<IborCoupon>>,
    overnight_coupons: Vec<Shared<OvernightIndexedCoupon>>,
    cap_rates: Vec<Rate>,
    floor_rates: Vec<Rate>,
    settings: Shared<Settings<Date>>,
}

impl CapFloor {
    /// Builds a cap/floor/collar over `coupons`, padding the strike vectors to
    /// the leg length by repeating the last strike (the C++ constructor's
    /// `while (rates.size() < leg.size()) push_back(rates.back())`).
    ///
    /// A `Cap` or `Collar` requires at least one cap rate, a `Floor` or `Collar`
    /// at least one floor rate.
    pub fn new(
        cap_floor_type: CapFloorType,
        coupons: Vec<Shared<IborCoupon>>,
        mut cap_rates: Vec<Rate>,
        mut floor_rates: Vec<Rate>,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CapFloor> {
        let n = coupons.len();
        if matches!(cap_floor_type, CapFloorType::Cap | CapFloorType::Collar) {
            require!(!cap_rates.is_empty(), "no cap rates given");
            while cap_rates.len() < n {
                cap_rates.push(*cap_rates.last().expect("non-empty"));
            }
        }
        if matches!(cap_floor_type, CapFloorType::Floor | CapFloorType::Collar) {
            require!(!floor_rates.is_empty(), "no floor rates given");
            while floor_rates.len() < n {
                floor_rates.push(*floor_rates.last().expect("non-empty"));
            }
        }

        let base = InstrumentBase::new();
        for coupon in &coupons {
            base.register_with(coupon.observable());
        }
        settings.register_eval_date_observer(&base.observer());

        Ok(CapFloor {
            base,
            cap_floor_type,
            coupons,
            overnight_coupons: Vec::new(),
            cap_rates,
            floor_rates,
            settings,
        })
    }

    /// Cap, floor or collar over retained overnight coupons.
    ///
    /// Engine arguments use each coupon's last fixing date and averaged rate,
    /// matching QuantLib's generic floating-coupon cap/floor path.
    pub fn from_overnight(
        kind: CapFloorType,
        coupons: Vec<Shared<OvernightIndexedCoupon>>,
        cap_rates: Vec<Rate>,
        floor_rates: Vec<Rate>,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Self> {
        let mut result = Self::new(kind, Vec::new(), cap_rates, floor_rates, settings)?;
        if result.cap_rates.len() < coupons.len()
            && let Some(&last) = result.cap_rates.last()
        {
            result.cap_rates.resize(coupons.len(), last);
        }
        if result.floor_rates.len() < coupons.len()
            && let Some(&last) = result.floor_rates.last()
        {
            result.floor_rates.resize(coupons.len(), last);
        }
        for coupon in &coupons {
            result.base.register_with(coupon.observable());
        }
        result.overnight_coupons = coupons;
        Ok(result)
    }

    /// Overnight coupons; empty on a legacy Ibor-leg cap/floor.
    pub fn overnight_coupons(&self) -> &[Shared<OvernightIndexedCoupon>] {
        &self.overnight_coupons
    }

    /// A cap over `coupons` struck at `strikes` (the C++ `Cap`).
    pub fn cap(
        coupons: Vec<Shared<IborCoupon>>,
        strikes: Vec<Rate>,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CapFloor> {
        CapFloor::new(CapFloorType::Cap, coupons, strikes, Vec::new(), settings)
    }

    /// A floor over `coupons` struck at `strikes` (the C++ `Floor`).
    pub fn floor(
        coupons: Vec<Shared<IborCoupon>>,
        strikes: Vec<Rate>,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CapFloor> {
        CapFloor::new(CapFloorType::Floor, coupons, Vec::new(), strikes, settings)
    }

    /// A collar over `coupons`, long the cap at `cap_rates` and short the floor
    /// at `floor_rates` (the C++ `Collar`).
    pub fn collar(
        coupons: Vec<Shared<IborCoupon>>,
        cap_rates: Vec<Rate>,
        floor_rates: Vec<Rate>,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<CapFloor> {
        CapFloor::new(
            CapFloorType::Collar,
            coupons,
            cap_rates,
            floor_rates,
            settings,
        )
    }

    /// The instrument type.
    pub fn cap_floor_type(&self) -> CapFloorType {
        self.cap_floor_type
    }

    /// The padded cap strikes.
    pub fn cap_rates(&self) -> &[Rate] {
        &self.cap_rates
    }

    /// The padded floor strikes.
    pub fn floor_rates(&self) -> &[Rate] {
        &self.floor_rates
    }

    /// Number of Ibor or overnight coupons in the instrument.
    pub fn coupon_count(&self) -> usize {
        self.coupons.len() + self.overnight_coupons.len()
    }

    /// Extracts the zero-based optionlet, retaining its shared coupon and settings.
    ///
    /// Only the strikes relevant to this instrument's type are copied. The new
    /// instrument has no pricing engine or cached results, matching QuantLib;
    /// attach an engine explicitly before pricing a live optionlet.
    ///
    /// # Errors
    /// Returns an error when `index` is outside the floating leg, including an
    /// empty leg.
    pub fn optionlet(&self, index: usize) -> QlResult<Self> {
        require!(
            index < self.coupon_count(),
            "optionlet index {index} does not exist, only {} coupons",
            self.coupon_count()
        );
        let cap_rates = if matches!(
            self.cap_floor_type,
            CapFloorType::Cap | CapFloorType::Collar
        ) {
            vec![self.cap_rates[index]]
        } else {
            Vec::new()
        };
        let floor_rates = if matches!(
            self.cap_floor_type,
            CapFloorType::Floor | CapFloorType::Collar
        ) {
            vec![self.floor_rates[index]]
        } else {
            Vec::new()
        };
        if let Some(coupon) = self.coupons.get(index) {
            Self::new(
                self.cap_floor_type,
                vec![Shared::clone(coupon)],
                cap_rates,
                floor_rates,
                Shared::clone(&self.settings),
            )
        } else {
            Self::from_overnight(
                self.cap_floor_type,
                vec![Shared::clone(
                    &self.overnight_coupons[index - self.coupons.len()],
                )],
                cap_rates,
                floor_rates,
                Shared::clone(&self.settings),
            )
        }
    }

    /// The floating coupons.
    pub fn coupons(&self) -> &[Shared<IborCoupon>] {
        &self.coupons
    }

    /// The last floating coupon (`lastFloatingRateCoupon`), the coupon the
    /// optionlet stripper reads its fixing date, payment date and accrual period
    /// off. Returns `None` for an empty Ibor store, including overnight legs.
    /// See [`Self::last_overnight_coupon`] for overnight instruments.
    pub fn last_floating_rate_coupon(&self) -> Option<&Shared<IborCoupon>> {
        self.coupons.last()
    }

    /// The last retained overnight coupon, or `None` on Ibor or empty legs.
    ///
    /// This borrows the same shared coupon held in [`Self::overnight_coupons`].
    pub fn last_overnight_coupon(&self) -> Option<&Shared<OvernightIndexedCoupon>> {
        self.overnight_coupons.last()
    }

    /// The leg's earliest accrual start (`startDate`).
    pub fn start_date(&self) -> QlResult<Date> {
        CashFlows::start_date(&self.cash_flows())
    }

    /// The leg's latest accrual end (`maturityDate`).
    pub fn maturity_date(&self) -> QlResult<Date> {
        CashFlows::maturity_date(&self.cash_flows())
    }

    /// The at-the-money rate: the fixed rate that reprices the floating leg on
    /// `discount_curve` (`atmRate`).
    pub fn atm_rate(&self, discount_curve: &dyn YieldTermStructure) -> QlResult<Rate> {
        let reference = discount_curve.reference_date()?;
        CashFlows::atm_rate(
            &self.cash_flows(),
            discount_curve,
            &self.settings,
            Some(false),
            Some(reference),
            None,
            None,
        )
    }

    /// The concrete coupons erased to a [`Leg`] for the [`CashFlows`] analytics.
    fn cash_flows(&self) -> Leg {
        self.coupons
            .iter()
            .map(|coupon| Shared::clone(coupon) as Shared<dyn CashFlow>)
            .chain(
                self.overnight_coupons
                    .iter()
                    .map(|coupon| Shared::clone(coupon) as Shared<dyn CashFlow>),
            )
            .collect()
    }
}

impl Instrument for CapFloor {
    fn base(&self) -> &InstrumentBase {
        &self.base
    }

    fn base_mut(&mut self) -> &mut InstrumentBase {
        &mut self.base
    }

    fn is_expired(&self) -> QlResult<bool> {
        for coupon in self.cash_flows().iter().rev() {
            if !coupon.has_occurred(&self.settings, None, None)? {
                return Ok(false);
            }
        }
        Ok(true)
    }

    fn setup_arguments(&self, arguments: &mut dyn Arguments) -> QlResult<()> {
        let Some(args) = (arguments as &mut dyn Any).downcast_mut::<CapFloorArguments>() else {
            fail!("wrong argument type");
        };
        let today = match self.settings.evaluation_date() {
            Some(today) => today,
            None => fail!("no evaluation date set: a cap/floor needs a reference date"),
        };

        let n = self.coupons.len() + self.overnight_coupons.len();
        args.cap_floor_type = Some(self.cap_floor_type);
        args.start_dates = Vec::with_capacity(n);
        args.fixing_dates = Vec::with_capacity(n);
        args.end_dates = Vec::with_capacity(n);
        args.accrual_times = Vec::with_capacity(n);
        args.cap_rates = Vec::with_capacity(n);
        args.floor_rates = Vec::with_capacity(n);
        args.forwards = Vec::with_capacity(n);
        args.gearings = Vec::with_capacity(n);
        args.nominals = Vec::with_capacity(n);

        let has_cap = matches!(
            self.cap_floor_type,
            CapFloorType::Cap | CapFloorType::Collar
        );
        let has_floor = matches!(
            self.cap_floor_type,
            CapFloorType::Floor | CapFloorType::Collar
        );

        let coupons = self
            .coupons
            .iter()
            .map(|c| {
                (
                    c.as_ref() as &dyn Coupon,
                    c.fixing_date(),
                    c.spread(),
                    c.gearing(),
                    c.date(),
                )
            })
            .chain(self.overnight_coupons.iter().map(|c| {
                (
                    c.as_ref() as &dyn Coupon,
                    c.fixing_date(),
                    c.spread(),
                    c.gearing(),
                    c.date(),
                )
            }));
        for (i, (coupon, fixing_date, spread, gearing, end_date)) in coupons.enumerate() {
            args.start_dates.push(coupon.accrual_start_date());
            args.fixing_dates.push(fixing_date);
            args.end_dates.push(end_date);
            args.accrual_times.push(coupon.accrual_period());
            args.nominals.push(coupon.nominal());
            args.gearings.push(gearing);

            // Passed explicitly for precision, but only if the coupon can still
            // pay (`capfloor.cpp:245`): a past-fixing coupon has no forward.
            let forward = if end_date >= today {
                Some((coupon.rate()? - spread) / gearing)
            } else {
                None
            };
            args.forwards.push(forward);

            args.cap_rates.push(if has_cap {
                Some((self.cap_rates[i] - spread) / gearing)
            } else {
                None
            });
            args.floor_rates.push(if has_floor {
                Some((self.floor_rates[i] - spread) / gearing)
            } else {
                None
            });
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cashflows::{IborLeg, OvernightLeg};
    use crate::handle::Handle;
    use crate::indexes::ibor::{Euribor, Sofr};
    use crate::shared::shared;
    use crate::termstructures::yieldtermstructure::YieldTermStructure;
    use crate::time::businessdayconvention::BusinessDayConvention;
    use crate::time::calendars::target::Target;
    use crate::time::date::{Date, Month};
    use crate::time::frequency::Frequency;
    use crate::time::schedule::MakeSchedule;

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

    /// A three-coupon 18-month leg over an unlinked Euribor 6M.
    fn leg(settings: Shared<Settings<Date>>) -> Vec<Shared<IborCoupon>> {
        let index = shared(Euribor::six_months(
            Handle::<dyn YieldTermStructure>::empty(),
            settings,
        ));
        let schedule = MakeSchedule::new()
            .from(Date::new(15, Month::January, 2026))
            .to(Date::new(15, Month::July, 2027))
            .with_frequency(Frequency::Semiannual)
            .with_calendar(Target::new())
            .with_convention(BusinessDayConvention::ModifiedFollowing)
            .build();
        IborLeg::new(schedule, index)
            .with_notional(100.0)
            .coupons()
            .unwrap()
    }

    #[test]
    fn a_cap_pads_the_strike_to_the_leg_length() {
        let settings = settings_on(Date::new(2, Month::January, 2026));
        let coupons = leg(settings.clone());
        let n = coupons.len();
        let cap = CapFloor::cap(coupons, vec![0.03], settings).unwrap();

        assert_eq!(cap.cap_floor_type(), CapFloorType::Cap);
        assert_eq!(cap.cap_rates(), vec![0.03; n].as_slice());
        assert!(cap.floor_rates().is_empty());
    }

    #[test]
    fn a_collar_keeps_both_padded_strike_vectors() {
        let settings = settings_on(Date::new(2, Month::January, 2026));
        let coupons = leg(settings.clone());
        let n = coupons.len();
        let collar = CapFloor::collar(coupons, vec![0.06], vec![0.02], settings).unwrap();

        assert_eq!(collar.cap_floor_type(), CapFloorType::Collar);
        assert_eq!(collar.cap_rates(), vec![0.06; n].as_slice());
        assert_eq!(collar.floor_rates(), vec![0.02; n].as_slice());
    }

    #[test]
    fn a_cap_needs_at_least_one_rate() {
        let settings = settings_on(Date::new(2, Month::January, 2026));
        let coupons = leg(settings.clone());
        let err = CapFloor::cap(coupons, Vec::new(), settings).err().unwrap();
        assert_eq!(err.message(), "no cap rates given");
    }

    #[test]
    fn a_floor_needs_at_least_one_rate() {
        let settings = settings_on(Date::new(2, Month::January, 2026));
        let coupons = leg(settings.clone());
        let err = CapFloor::floor(coupons, Vec::new(), settings)
            .err()
            .unwrap();
        assert_eq!(err.message(), "no floor rates given");
    }

    /// `setup_arguments` fills `start_dates` with each coupon's accrual start
    /// (`capfloor.cpp:237`), the maturity the analytic engine forms its bond
    /// option from.
    #[test]
    fn setup_arguments_fills_start_dates_with_the_accrual_starts() {
        // Evaluation date past the whole leg: every forward is `None`, so
        // `setup_arguments` never forecasts off the (unlinked) index curve, yet
        // `start_dates` is still populated unconditionally.
        let settings = settings_on(Date::new(2, Month::January, 2028));
        let coupons = leg(settings.clone());
        let expected: Vec<Date> = coupons.iter().map(|c| c.accrual_start_date()).collect();
        let cap = CapFloor::cap(coupons, vec![0.03], settings).unwrap();

        let mut args = CapFloorArguments::default();
        cap.setup_arguments(&mut args).unwrap();
        assert_eq!(args.start_dates, expected);
        assert_eq!(args.start_dates.len(), args.end_dates.len());
    }

    /// `CapFloor::arguments::validate` rejects a `start_dates` length that has
    /// desynced from `end_dates` (`capfloor.cpp:279`).
    #[test]
    fn validate_rejects_a_desynced_start_date_count() {
        let settings = settings_on(Date::new(2, Month::January, 2028));
        let coupons = leg(settings.clone());
        let cap = CapFloor::cap(coupons, vec![0.03], settings).unwrap();

        let mut args = CapFloorArguments::default();
        cap.setup_arguments(&mut args).unwrap();
        args.start_dates.pop();
        assert_eq!(
            args.validate().err().unwrap().message(),
            "start-date count mismatch"
        );
    }

    /// `CapFloor::isExpired`: expired once every coupon has paid.
    #[test]
    fn a_cap_is_expired_only_once_all_coupons_have_paid() {
        let settings = settings_on(Date::new(2, Month::January, 2026));
        let coupons = leg(settings.clone());
        let cap = CapFloor::cap(coupons, vec![0.03], settings.clone()).unwrap();
        assert!(!cap.is_expired().unwrap());

        settings.set_evaluation_date(Date::new(15, Month::August, 2027));
        assert!(cap.is_expired().unwrap());
    }

    #[test]
    fn last_overnight_coupon_retains_the_trailing_coupon_identity() {
        let settings = settings_on(Date::new(2, Month::January, 2026));
        let index = shared(Sofr::new(Handle::empty(), settings.clone()));
        let schedule = MakeSchedule::new()
            .from(Date::new(15, Month::January, 2026))
            .to(Date::new(15, Month::October, 2026))
            .with_frequency(Frequency::Quarterly)
            .with_calendar(Target::new())
            .with_convention(BusinessDayConvention::ModifiedFollowing)
            .build();
        let coupons = OvernightLeg::new(schedule, index)
            .with_notional(100.0)
            .coupons()
            .unwrap();
        assert_eq!(coupons.len(), 3);
        let cap = CapFloor::from_overnight(
            CapFloorType::Cap,
            coupons.clone(),
            vec![0.03],
            Vec::new(),
            settings,
        )
        .unwrap();
        let last = cap.last_overnight_coupon().unwrap();
        assert!(Shared::ptr_eq(last, &coupons[2]));
        assert!(std::ptr::eq(last, &cap.overnight_coupons()[2]));
        assert!(!Shared::ptr_eq(last, &coupons[0]));
        assert!(cap.last_floating_rate_coupon().is_none());
        assert_eq!(last.accrual_end_date(), Date::new(15, Month::October, 2026));
    }

    #[test]
    fn last_overnight_coupon_is_none_on_ibor_and_empty_legs() {
        let settings = settings_on(Date::new(2, Month::January, 2026));
        let coupons = leg(settings.clone());
        let last = coupons.last().unwrap().clone();
        let cap = CapFloor::cap(coupons, vec![0.03], settings.clone()).unwrap();
        assert!(cap.last_overnight_coupon().is_none());
        assert!(Shared::ptr_eq(
            cap.last_floating_rate_coupon().unwrap(),
            &last
        ));
        let empty = CapFloor::from_overnight(
            CapFloorType::Cap,
            Vec::new(),
            vec![0.03],
            Vec::new(),
            settings,
        )
        .unwrap();
        assert!(empty.last_overnight_coupon().is_none());
        assert!(empty.last_floating_rate_coupon().is_none());
    }
}