libitofin 0.14.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
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! Standard market year-on-year inflation cap/floor builder
//! (`MakeYoYInflationCapFloor`).
//!
//! Port of `ql/instruments/makeyoyinflationcapfloor.{hpp,cpp}`: the comfortable
//! way to instantiate a standard market [`YoYInflationCapFloor`]. It derives an
//! annual year-on-year leg from a length in years, a [`YoYInflationIndex`] and a
//! forward start, trims that leg to the optionlets asked for, and strikes it
//! either at an explicit rate or at the money off a nominal curve
//! (`makeyoyinflationcapfloor.cpp:46-89`).
//!
//! ## Trimming happens before the at-the-money fill
//!
//! [`build`](MakeYoYInflationCapFloor::build) drops coupons *before* it resolves
//! an at-the-money strike (`cpp:69-83`):
//! [`with_first_caplet_excluded`](MakeYoYInflationCapFloor::with_first_caplet_excluded)
//! drops the front optionlet, [`as_optionlet`](MakeYoYInflationCapFloor::as_optionlet)
//! keeps only the last, and the strike is then the rate that reprices whatever
//! survives. Filling the strike first would strike a one-coupon optionlet at the
//! whole leg's rate, which is a different instrument on any curve with slope.
//!
//! ## Divergences from QuantLib
//!
//! - The explicit-strike/at-the-money conflict is a *build*-time error rather
//!   than a setter error. C++ guards it at both setters (`cpp:133` "ATM strike
//!   already given", `cpp:141` "explicit strike already given"), which a
//!   consumed-self fluent setter returning `Self` cannot do. [`build`] refuses
//!   the both-given case instead, and also the neither-given case, which C++
//!   reaches as a dereference of its empty nominal-curve handle. The two agree
//!   on which builders are legal; they differ only in when the refusal lands.
//! - `withFirstCapletExcluded` is *declared* upstream (`hpp:49`) and defined in
//!   no translation unit, so calling it in C++ fails to link, even though
//!   `build` reads the flag it would have set (`cpp:69-70`). The port implements
//!   a working setter.
//!
//! [`build`]: MakeYoYInflationCapFloor::build

use crate::cashflow::{CashFlow, Leg};
use crate::cashflows::{CashFlows, YoYInflationLeg};
use crate::errors::QlResult;
use crate::handle::Handle;
use crate::indexes::inflationindex::{CpiInterpolationType, YoYInflationIndex};
use crate::instrument::Instrument;
use crate::instruments::capfloor::CapFloorType;
use crate::instruments::inflationcapfloor::YoYInflationCapFloor;
use crate::pricingengine::PricingEngine;
use crate::settings::Settings;
use crate::shared::{Shared, SharedMut};
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::time::businessdayconvention::BusinessDayConvention;
use crate::time::calendar::Calendar;
use crate::time::date::Date;
use crate::time::dategenerationrule::DateGeneration;
use crate::time::daycounter::DayCounter;
use crate::time::daycounters::thirty360::{Convention, Thirty360};
use crate::time::frequency::Frequency;
use crate::time::period::Period;
use crate::time::schedule::MakeSchedule;
use crate::time::timeunit::TimeUnit;
use crate::types::{Integer, Natural, Rate, Real, Size};

/// Builder for a standard market year-on-year inflation cap or floor.
pub struct MakeYoYInflationCapFloor {
    cap_floor_type: CapFloorType,
    index: Shared<YoYInflationIndex>,
    length: Size,
    calendar: Calendar,
    observation_lag: Period,
    interpolation: CpiInterpolationType,
    strike: Option<Rate>,
    nominal: Real,
    roll: BusinessDayConvention,
    day_counter: DayCounter,
    fixing_days: Natural,
    first_caplet_excluded: bool,
    as_optionlet: bool,
    effective_date: Option<Date>,
    forward_start: Period,
    nominal_term_structure: Handle<dyn YieldTermStructure>,
    engine: Option<SharedMut<dyn PricingEngine>>,
    settings: Shared<Settings<Date>>,
}

impl MakeYoYInflationCapFloor {
    /// Starts a builder for a `cap_floor_type` cap/floor of `length` years on
    /// `index`, observed `observation_lag` back under `interpolation` and paying
    /// on `calendar` (`makeyoyinflationcapfloor.cpp:29-38`).
    ///
    /// The defaults are the C++ member initialisers (`hpp:72-80`): a 1,000,000
    /// nominal, a `ModifiedFollowing` payment roll, a 30/360 bond-basis day
    /// counter, no fixing days, every optionlet kept, and no strike - so a
    /// builder left as it comes needs either
    /// [`with_strike`](Self::with_strike) or
    /// [`with_atm_strike`](Self::with_atm_strike) before it will build.
    /// `settings` carries the evaluation date (D5).
    pub fn new(
        cap_floor_type: CapFloorType,
        index: Shared<YoYInflationIndex>,
        length: Size,
        calendar: Calendar,
        observation_lag: Period,
        interpolation: CpiInterpolationType,
        settings: Shared<Settings<Date>>,
    ) -> MakeYoYInflationCapFloor {
        MakeYoYInflationCapFloor {
            cap_floor_type,
            index,
            length,
            calendar,
            observation_lag,
            interpolation,
            strike: None,
            nominal: 1_000_000.0,
            roll: BusinessDayConvention::ModifiedFollowing,
            day_counter: Thirty360::with_convention(Convention::BondBasis),
            fixing_days: 0,
            first_caplet_excluded: false,
            as_optionlet: false,
            effective_date: None,
            forward_start: Period::new(0, TimeUnit::Days),
            nominal_term_structure: Handle::<dyn YieldTermStructure>::empty(),
            engine: None,
            settings,
        }
    }

    /// Sets the nominal every coupon carries (`withNominal`, `cpp:91-94`).
    pub fn with_nominal(mut self, nominal: Real) -> MakeYoYInflationCapFloor {
        self.nominal = nominal;
        self
    }

    /// Sets the start date outright, bypassing the spot-plus-forward-start
    /// derivation (`withEffectiveDate`, `cpp:96-100`).
    pub fn with_effective_date(mut self, effective_date: Date) -> MakeYoYInflationCapFloor {
        self.effective_date = Some(effective_date);
        self
    }

    /// Sets the day counter the coupons accrue with
    /// (`withPaymentDayCounter`, `cpp:108-112`).
    pub fn with_payment_day_counter(mut self, day_counter: DayCounter) -> MakeYoYInflationCapFloor {
        self.day_counter = day_counter;
        self
    }

    /// Sets the convention the payment dates are adjusted with
    /// (`withPaymentAdjustment`, `cpp:102-106`).
    pub fn with_payment_adjustment(
        mut self,
        convention: BusinessDayConvention,
    ) -> MakeYoYInflationCapFloor {
        self.roll = convention;
        self
    }

    /// Sets how many business days after the evaluation date the leg starts
    /// (`withFixingDays`, `cpp:114-118`). Only the start date reads this; the
    /// coupons keep their own fixing-days default.
    pub fn with_fixing_days(mut self, fixing_days: Natural) -> MakeYoYInflationCapFloor {
        self.fixing_days = fixing_days;
        self
    }

    /// Sets the engine installed on the built cap/floor
    /// (`withPricingEngine`, `cpp:124-128`).
    pub fn with_pricing_engine(
        mut self,
        engine: SharedMut<dyn PricingEngine>,
    ) -> MakeYoYInflationCapFloor {
        self.engine = Some(engine);
        self
    }

    /// Keeps only the last optionlet when `as_optionlet` is set
    /// (`asOptionlet`, `cpp:120-123`).
    pub fn as_optionlet(mut self, as_optionlet: bool) -> MakeYoYInflationCapFloor {
        self.as_optionlet = as_optionlet;
        self
    }

    /// Sets how long after spot the leg starts (`withForwardStart`,
    /// `cpp:146-150`).
    pub fn with_forward_start(mut self, forward_start: Period) -> MakeYoYInflationCapFloor {
        self.forward_start = forward_start;
        self
    }

    /// Drops the front optionlet (`cpp:69-70`; see the module docs for the
    /// upstream setter that is declared but never defined).
    pub fn with_first_caplet_excluded(mut self) -> MakeYoYInflationCapFloor {
        self.first_caplet_excluded = true;
        self
    }

    /// Strikes the cap/floor at `strike` (`withStrike`, `cpp:130-135`).
    ///
    /// Conflicts with [`with_atm_strike`](Self::with_atm_strike); the two
    /// together are refused by [`build`](Self::build), not here.
    pub fn with_strike(mut self, strike: Rate) -> MakeYoYInflationCapFloor {
        self.strike = Some(strike);
        self
    }

    /// Strikes the cap/floor at the money on `nominal_term_structure`
    /// (`withAtmStrike`, `cpp:137-144`).
    ///
    /// The rate is the one that reprices the *trimmed* leg; see the module docs.
    /// Conflicts with [`with_strike`](Self::with_strike); the two together are
    /// refused by [`build`](Self::build), not here.
    pub fn with_atm_strike(
        mut self,
        nominal_term_structure: Handle<dyn YieldTermStructure>,
    ) -> MakeYoYInflationCapFloor {
        self.nominal_term_structure = nominal_term_structure;
        self
    }

    /// Builds the cap/floor (C++ `operator shared_ptr<YoYInflationCapFloor>()`,
    /// `cpp:46-89`).
    ///
    /// Derives the start date from the evaluation date, the fixing days and the
    /// forward start unless [`with_effective_date`](Self::with_effective_date)
    /// set it; runs an annual unadjusted schedule out to `length` years; builds
    /// the year-on-year leg; trims it; resolves the strike on what is left; and
    /// installs the pricing engine when one was set.
    ///
    /// # Errors
    ///
    /// When the start date has to be derived and no evaluation date is set;
    /// when both or neither of an explicit strike and an at-the-money curve were
    /// given; and as the leg construction, the at-the-money rate and the
    /// [`YoYInflationCapFloor`] construction do.
    pub fn build(self) -> QlResult<YoYInflationCapFloor> {
        let start_date = match self.effective_date {
            Some(effective_date) => effective_date,
            None => {
                let reference_date = match self.settings.evaluation_date() {
                    Some(today) => today,
                    None => crate::fail!(
                        "no evaluation date set: MakeYoYInflationCapFloor needs a reference date to derive the start date"
                    ),
                };
                let spot_date = self.calendar.advance(
                    reference_date,
                    self.fixing_days as Integer,
                    TimeUnit::Days,
                    BusinessDayConvention::Following,
                    false,
                );
                spot_date + self.forward_start
            }
        };

        let end_date = self.calendar.advance(
            start_date,
            self.length as Integer,
            TimeUnit::Years,
            BusinessDayConvention::Unadjusted,
            false,
        );
        let schedule = MakeSchedule::new()
            .from(start_date)
            .to(end_date)
            .with_frequency(Frequency::Annual)
            .with_calendar(self.calendar.clone())
            .with_convention(BusinessDayConvention::Unadjusted)
            .with_termination_date_convention(BusinessDayConvention::Unadjusted)
            .with_rule(DateGeneration::Forward)
            .build();

        let mut coupons = YoYInflationLeg::new(
            schedule,
            self.calendar,
            self.index,
            self.observation_lag,
            self.interpolation,
        )
        .with_payment_adjustment(self.roll)
        .with_payment_day_counter(self.day_counter)
        .with_notional(self.nominal)
        .coupons()?;

        if self.first_caplet_excluded && !coupons.is_empty() {
            coupons.remove(0);
        }
        if self.as_optionlet && coupons.len() > 1 {
            coupons.drain(..coupons.len() - 1);
        }

        let strikes = match (self.strike, self.nominal_term_structure.is_empty()) {
            (Some(_), false) => {
                crate::fail!("explicit strike and ATM curve both given")
            }
            (Some(strike), true) => vec![strike],
            (None, false) => {
                let curve = self.nominal_term_structure.current_link()?;
                let reference = curve.reference_date()?;
                let leg: Leg = coupons
                    .iter()
                    .map(|coupon| Shared::clone(coupon) as Shared<dyn CashFlow>)
                    .collect();
                vec![CashFlows::atm_rate(
                    &leg,
                    curve.as_ref(),
                    &self.settings,
                    Some(false),
                    Some(reference),
                    None,
                    None,
                )?]
            }
            (None, true) => crate::fail!("no strike and no ATM curve given"),
        };

        let mut cap_floor = YoYInflationCapFloor::with_strikes(
            self.cap_floor_type,
            coupons,
            strikes,
            self.settings,
        )?;
        if let Some(engine) = self.engine {
            cap_floor.base_mut().set_pricing_engine(engine);
        }
        Ok(cap_floor)
    }
}

#[cfg(test)]
mod tests {
    //! QuantLib covers neither this factory nor `YoYInflationCapFloor::atmRate`
    //! (no test-suite case constructs either), so the oracle is self-authored:
    //! a factory-built cap has to match the cap the same leg builds by hand, and
    //! an at-the-money strike has to be the rate that reprices the leg it ends
    //! up written on.
    //!
    //! The curve is deliberately steep - year-on-year swaps quoted 2 % to 4 %
    //! across 1y to 5y - so that the whole leg's at-the-money rate and the last
    //! coupon's are far apart. On a flat curve the two coincide and the
    //! trim-before-fill order (`cpp:69-83`) would be unpinnable.

    use super::*;
    use crate::cashflows::{Coupon, YoYInflationCoupon};
    use crate::event::Event;
    use crate::handle::RelinkableHandle;
    use crate::indexes::index::Index;
    use crate::indexes::inflation::UkRpi;
    use crate::indexes::inflationindex::InflationIndex;
    use crate::instruments::inflationcapfloor::YoYInflationCapFloor;
    use crate::interestrate::Compounding;
    use crate::math::interpolations::linear::Linear;
    use crate::quotes::SimpleQuote;
    use crate::shared::shared;
    use crate::termstructures::inflation::inflationhelpers::{
        YearOnYearInflationSwapHelper, YoYInflationHelper,
    };
    use crate::termstructures::inflation::inflationtermstructure::YoYInflationTermStructure;
    use crate::termstructures::inflation::piecewiseyoyinflationcurve::PiecewiseYoYInflationCurve;
    use crate::termstructures::yields::{FlatForward, Pillar};
    use crate::time::calendars::unitedkingdom::{self, UnitedKingdom};
    use crate::time::date::Month;
    use crate::time::daycounters::actual365fixed::Actual365Fixed;
    use crate::time::daycounters::actualactual::{
        ActualActual, Convention as ActualActualConvention,
    };

    /// Deliberately not the factory's own 1,000,000 default, so that the
    /// structural round-trip can tell `with_nominal` from a no-op.
    const NOTIONAL: Real = 2_500_000.0;
    const LENGTH: Size = 5;
    /// The last point of the quoted 2 % to 4 % year-on-year ramp, which is also
    /// the maturity a `LENGTH`-year leg runs to.
    const QUOTED_FIVE_YEAR_RATE: Real = 0.04;

    fn uk() -> Calendar {
        UnitedKingdom::new(unitedkingdom::Market::Settlement)
    }

    fn day_counter() -> DayCounter {
        Thirty360::with_convention(Convention::BondBasis)
    }

    fn observation_lag() -> Period {
        Period::new(2, TimeUnit::Months)
    }

    struct Fixture {
        settings: Shared<Settings<Date>>,
        index: Shared<YoYInflationIndex>,
        nominal: Handle<dyn YieldTermStructure>,
        evaluation_date: Date,
        _curve: Shared<PiecewiseYoYInflationCurve<Linear>>,
        _handle: RelinkableHandle<dyn YoYInflationTermStructure>,
    }

    /// A UK RPI index with monthly history, a 5 % nominal curve, and a
    /// year-on-year curve bootstrapped off five steeply rising swap quotes.
    ///
    /// The evaluation date is a UK business day, so a default build's spot date
    /// is the evaluation date itself and the hand-built comparison leg can start
    /// there without re-deriving it.
    fn a_sloped_market() -> Fixture {
        let settings = shared(Settings::<Date>::new());
        let evaluation_date = Date::new(13, Month::August, 2007);
        settings.set_evaluation_date(evaluation_date);

        let rpi_schedule = MakeSchedule::new()
            .from(Date::new(1, Month::January, 2005))
            .to(Date::new(1, Month::August, 2007))
            .with_tenor(Period::new(1, TimeUnit::Months))
            .with_calendar(uk())
            .with_convention(BusinessDayConvention::ModifiedFollowing)
            .with_rule(DateGeneration::Forward)
            .build();
        let rpi = shared(UkRpi::new(Shared::clone(&settings)));
        for (n, date) in rpi_schedule.dates().iter().enumerate() {
            rpi.add_fixing(*date, 190.0 + n as Real)
                .expect("a published figure");
        }

        let handle = RelinkableHandle::<dyn YoYInflationTermStructure>::empty();
        let index = shared(
            YoYInflationIndex::from_underlying(Shared::clone(&rpi))
                .with_term_structure(handle.handle()),
        );
        let nominal = Handle::new(shared(FlatForward::with_rate(
            evaluation_date,
            0.05,
            ActualActual::with_convention(ActualActualConvention::ISDA),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>);

        let helpers: Vec<Shared<dyn YoYInflationHelper>> = (1..=5)
            .map(|year| {
                let rate = 0.02 + 0.005 * (year - 1) as Real;
                YearOnYearInflationSwapHelper::new(
                    Handle::new(shared(SimpleQuote::new(Some(rate)))),
                    observation_lag(),
                    uk().advance(
                        evaluation_date,
                        year,
                        TimeUnit::Years,
                        BusinessDayConvention::Unadjusted,
                        false,
                    ),
                    uk(),
                    BusinessDayConvention::ModifiedFollowing,
                    day_counter(),
                    &index,
                    CpiInterpolationType::Flat,
                    nominal.clone(),
                    Pillar::LastRelevantDate,
                    Shared::clone(&settings),
                )
                .expect("a well-formed helper") as Shared<dyn YoYInflationHelper>
            })
            .collect();

        let curve = PiecewiseYoYInflationCurve::<Linear>::new(
            evaluation_date,
            rpi.last_fixing_date().expect("RPI has history"),
            0.02,
            index.frequency(),
            day_counter(),
            helpers,
            None,
        )
        .expect("five helpers");
        handle.link_to(Shared::clone(&curve) as Shared<dyn YoYInflationTermStructure>);

        Fixture {
            settings,
            index,
            nominal,
            evaluation_date,
            _curve: curve,
            _handle: handle,
        }
    }

    /// A builder with the factory defaults, over `LENGTH` years.
    fn a_builder(fixture: &Fixture) -> MakeYoYInflationCapFloor {
        MakeYoYInflationCapFloor::new(
            CapFloorType::Cap,
            Shared::clone(&fixture.index),
            LENGTH,
            uk(),
            observation_lag(),
            CpiInterpolationType::Flat,
            Shared::clone(&fixture.settings),
        )
    }

    /// The leg `build` should produce for the default settings, assembled by
    /// hand off the same schedule.
    fn a_hand_built_leg(fixture: &Fixture) -> Vec<Shared<YoYInflationCoupon>> {
        let start = fixture.evaluation_date;
        let end = uk().advance(
            start,
            LENGTH as Integer,
            TimeUnit::Years,
            BusinessDayConvention::Unadjusted,
            false,
        );
        let schedule = MakeSchedule::new()
            .from(start)
            .to(end)
            .with_frequency(Frequency::Annual)
            .with_calendar(uk())
            .with_convention(BusinessDayConvention::Unadjusted)
            .with_termination_date_convention(BusinessDayConvention::Unadjusted)
            .with_rule(DateGeneration::Forward)
            .build();
        YoYInflationLeg::new(
            schedule,
            uk(),
            Shared::clone(&fixture.index),
            observation_lag(),
            CpiInterpolationType::Flat,
        )
        .with_payment_adjustment(BusinessDayConvention::ModifiedFollowing)
        .with_payment_day_counter(day_counter())
        .with_notional(NOTIONAL)
        .coupons()
        .expect("a well-formed leg")
    }

    fn pay_dates(cap_floor: &YoYInflationCapFloor) -> Vec<Date> {
        cap_floor.yoy_leg().iter().map(|c| c.date()).collect()
    }

    /// The factory's leg is the leg the same schedule builds by hand, coupon for
    /// coupon (`cpp:58-67`). Structure alone pins this: no engine, no
    /// volatility, no NPV.
    #[test]
    fn the_factory_reproduces_a_hand_built_cap() {
        let fixture = a_sloped_market();
        let built = a_builder(&fixture)
            .with_nominal(NOTIONAL)
            .with_strike(0.03)
            .build()
            .expect("an explicit strike is enough to build");
        let by_hand = YoYInflationCapFloor::cap(
            a_hand_built_leg(&fixture),
            vec![0.03],
            Shared::clone(&fixture.settings),
        )
        .expect("a well-formed cap");

        assert_eq!(built.cap_rates(), by_hand.cap_rates());
        assert_eq!(built.yoy_leg().len(), by_hand.yoy_leg().len());
        for (from_factory, by_hand) in built.yoy_leg().iter().zip(by_hand.yoy_leg()) {
            assert_eq!(from_factory.nominal(), by_hand.nominal());
            assert_eq!(from_factory.accrual_period(), by_hand.accrual_period());
            assert_eq!(from_factory.date(), by_hand.date());
            assert_eq!(from_factory.fixing_date(), by_hand.fixing_date());
        }
    }

    /// `atmRate` (`inflationcapfloor.cpp:214-217`) is [`CashFlows::atm_rate`]
    /// over the instrument's own leg, off the curve's reference date.
    #[test]
    fn atm_rate_is_the_leg_repricing_rate() {
        let fixture = a_sloped_market();
        let cap = a_builder(&fixture)
            .with_strike(0.03)
            .build()
            .expect("a well-formed cap");
        let curve = fixture.nominal.current_link().expect("a linked curve");

        let leg: Leg = cap
            .yoy_leg()
            .iter()
            .map(|coupon| Shared::clone(coupon) as Shared<dyn CashFlow>)
            .collect();
        let by_hand = CashFlows::atm_rate(
            &leg,
            curve.as_ref(),
            &fixture.settings,
            Some(false),
            Some(curve.reference_date().expect("a reference date")),
            None,
            None,
        )
        .expect("a leg with basis-point sensitivity");

        assert_eq!(cap.atm_rate(curve.as_ref()).expect("an atm rate"), by_hand);
    }

    /// An unset strike is filled at the money off the nominal curve
    /// (`cpp:78-83`).
    ///
    /// The filled rate is checked twice: against the instrument's own
    /// `atm_rate`, and against the quoted five-year year-on-year swap rate the
    /// curve was bootstrapped from. The second is the independent one - a par
    /// swap rate *is* the rate that reprices its leg, so a five-year leg struck
    /// at the money has to come back to the five-year quote, off market data
    /// this code never touches on the way through.
    #[test]
    fn an_unset_strike_is_filled_at_the_money() {
        let fixture = a_sloped_market();
        let cap = a_builder(&fixture)
            .with_atm_strike(fixture.nominal.clone())
            .build()
            .expect("an atm curve is enough to build");
        let curve = fixture.nominal.current_link().expect("a linked curve");

        assert!(
            (cap.cap_rates()[0] - cap.atm_rate(curve.as_ref()).expect("an atm rate")).abs() < 1e-12
        );
        assert!(
            (cap.cap_rates()[0] - QUOTED_FIVE_YEAR_RATE).abs() < 1e-12,
            "the atm strike {} missed the five-year quote",
            cap.cap_rates()[0]
        );
    }

    /// The load-bearing order pin: `asOptionlet` trims the leg *before* the
    /// at-the-money fill (`cpp:72-83`), so the strike is the last coupon's rate
    /// and not the whole leg's. On this upward-sloping curve the two sit about
    /// 227 basis points apart (4.00 % against 6.27 %); filling the strike first
    /// would leave the optionlet struck at the full-leg rate.
    #[test]
    fn an_optionlet_strikes_at_the_money_on_the_coupon_it_keeps() {
        let fixture = a_sloped_market();
        let whole_leg = a_builder(&fixture)
            .with_atm_strike(fixture.nominal.clone())
            .build()
            .expect("a well-formed cap");
        let optionlet = a_builder(&fixture)
            .as_optionlet(true)
            .with_atm_strike(fixture.nominal.clone())
            .build()
            .expect("a well-formed optionlet");
        let curve = fixture.nominal.current_link().expect("a linked curve");

        assert_eq!(whole_leg.yoy_leg().len(), LENGTH);
        assert_eq!(optionlet.yoy_leg().len(), 1);
        assert_eq!(
            optionlet.yoy_leg()[0].date(),
            whole_leg.yoy_leg()[LENGTH - 1].date()
        );
        assert!(
            (optionlet.cap_rates()[0] - optionlet.atm_rate(curve.as_ref()).expect("an atm rate"))
                .abs()
                < 1e-12
        );
        assert!(
            (optionlet.cap_rates()[0] - whole_leg.cap_rates()[0]).abs() > 1e-2,
            "the tail rate {} is indistinguishable from the whole leg's {}",
            optionlet.cap_rates()[0],
            whole_leg.cap_rates()[0]
        );
    }

    /// Every trimming flag reaches the leg (`cpp:69-76`).
    #[test]
    fn the_trimming_flags_reach_the_leg() {
        let fixture = a_sloped_market();
        let whole = a_builder(&fixture).with_strike(0.03).build().unwrap();
        let trimmed = a_builder(&fixture)
            .with_first_caplet_excluded()
            .with_strike(0.03)
            .build()
            .unwrap();

        assert_eq!(trimmed.yoy_leg().len(), whole.yoy_leg().len() - 1);
        assert_eq!(pay_dates(&trimmed), pay_dates(&whole)[1..]);
    }

    /// No setter is a silent no-op: each moves the built leg away from the one
    /// the defaults produce.
    #[test]
    fn every_setter_moves_the_built_leg() {
        let fixture = a_sloped_market();
        let default = a_builder(&fixture).with_strike(0.03).build().unwrap();
        let default_dates = pay_dates(&default);

        let shifted = a_builder(&fixture)
            .with_effective_date(fixture.evaluation_date + Period::new(1, TimeUnit::Months))
            .with_strike(0.03)
            .build()
            .unwrap();
        assert_ne!(pay_dates(&shifted), default_dates);

        let unadjusted = a_builder(&fixture)
            .with_payment_adjustment(BusinessDayConvention::Unadjusted)
            .with_strike(0.03)
            .build()
            .unwrap();
        assert_ne!(pay_dates(&unadjusted), default_dates);

        let actual365 = a_builder(&fixture)
            .with_payment_day_counter(Actual365Fixed::new())
            .with_strike(0.03)
            .build()
            .unwrap();
        assert_ne!(
            actual365.yoy_leg()[0].accrual_period(),
            default.yoy_leg()[0].accrual_period()
        );

        let delayed = a_builder(&fixture)
            .with_fixing_days(5)
            .with_strike(0.03)
            .build()
            .unwrap();
        assert_ne!(pay_dates(&delayed), default_dates);

        let forward = a_builder(&fixture)
            .with_forward_start(Period::new(1, TimeUnit::Years))
            .with_strike(0.03)
            .build()
            .unwrap();
        assert_ne!(pay_dates(&forward), default_dates);
    }

    /// The strike/at-the-money exclusion C++ guards at its setters (`cpp:133`,
    /// `cpp:141`) lands at build time here; so does the neither-given case,
    /// which C++ reaches as an empty-handle dereference. See the module docs.
    #[test]
    fn a_strike_and_an_atm_curve_are_mutually_exclusive() {
        let fixture = a_sloped_market();

        let strike_first = a_builder(&fixture)
            .with_strike(0.03)
            .with_atm_strike(fixture.nominal.clone())
            .build()
            .err()
            .expect("both given");
        assert!(
            strike_first.message().contains("both given"),
            "err was: {strike_first}"
        );

        let curve_first = a_builder(&fixture)
            .with_atm_strike(fixture.nominal.clone())
            .with_strike(0.03)
            .build()
            .err()
            .expect("both given");
        assert!(
            curve_first.message().contains("both given"),
            "err was: {curve_first}"
        );

        let neither = a_builder(&fixture).build().err().expect("neither given");
        assert!(
            neither.message().contains("no strike"),
            "err was: {neither}"
        );
    }
}