libitofin 0.18.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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
//! The Inter-Bank-Offered-Rate index.
//!
//! Port of `ql/indexes/iborindex.{hpp,cpp}`. [`IborIndex`] is the concrete
//! [`InterestRateIndex`] behind the floating leg: an
//! [`InterestRateIndexBase`] plus a business-day convention, an end-of-month
//! flag, and a [`Handle`] to the forwarding [`YieldTermStructure`] it reads
//! fixings off.
//!
//! It supplies the two members the base leaves abstract:
//! [`maturity_date`](InterestRateIndex::maturity_date) advances the value date
//! by the tenor under the index convention, and
//! [`forecast_fixing`](InterestRateIndex::forecast_fixing) derives the simple
//! forward rate from the curve's discount factors between the value and
//! maturity dates. The index registers its forwarding observer with the curve
//! handle, so a relinked or changed curve notifies the index's observers.
//!
//! [`OvernightIndex`] lives here too, as it does in `iborindex.hpp`: an
//! [`IborIndex`] pinned to the overnight configuration (one-day tenor,
//! `Following`, no end-of-month).

use crate::errors::QlResult;
use crate::handle::Handle;
use crate::indexes::index::Index;
use crate::indexes::interestrateindex::{InterestRateIndex, InterestRateIndexBase};
use crate::settings::Settings;
use crate::shared::{Shared, shared};
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::timeunit::TimeUnit;
use crate::types::{Integer, Natural, Rate, Time};
use crate::{currency::Currency, require};

/// Which calendar the fixing and value rolls advance on.
///
/// C++ splits the two shapes across subclasses: `Libor::valueDate` advances on
/// the fixing calendar (`libor.cpp:98`), while `CustomIborIndex` advances on a
/// separate value calendar and pulls the fixing date `Preceding` back onto the
/// fixing calendar (`custom.cpp:23-36`). Carrying the choice as data keeps the
/// roll dispatching through every site holding a concrete [`IborIndex`], where
/// a newtype override would be bypassed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CalendarRollRule {
    /// Advance on the fixing calendar: plain [`IborIndex`] and `Libor`.
    SingleCalendar,
    /// Advance on the value calendar, then adjust the fixing date `Preceding`
    /// on the fixing calendar: `CustomIborIndex` and `EURLibor`.
    SeparateCalendars,
}

/// A concrete Inter-Bank-Offered-Rate index (e.g. Libor, Euribor).
///
/// Wraps an [`InterestRateIndexBase`] with the forwarding curve and the
/// convention the maturity calculation needs. Built with a possibly empty curve
/// handle, exactly as the C++ default `Handle<YieldTermStructure> h = {}`
/// allows; a fixing forecast on an empty handle is an error, not a panic (D4).
///
/// The value and maturity calendars carry the C++ `Libor` subclass's joint
/// date roll (`libor.cpp:86-113`) as data rather than as a subtype: both
/// default to the fixing calendar (making the rolls byte-identical to the
/// single-calendar index), and the Libor constructor points the maturity
/// calendar at the UK-plus-financial-center joint calendar. Folding the
/// calendars in keeps the roll dispatching through every site holding a
/// concrete `IborIndex` (`makevanillaswap.rs:440`), where a newtype override
/// would be bypassed.
///
/// The internal `CalendarRollRule` extends that fold to the
/// `CustomIborIndex` three-calendar roll (`custom.cpp:23-41`): it selects
/// which of the two calendars the fixing and value advances run on, and
/// [`with_separate_calendars`](Self::with_separate_calendars) is the only way
/// to leave the single-calendar default, so a Libor-style calendar assignment
/// cannot flip it by accident.
pub struct IborIndex {
    base: InterestRateIndexBase,
    convention: BusinessDayConvention,
    end_of_month: bool,
    term_structure: Handle<dyn YieldTermStructure>,
    value_calendar: Calendar,
    maturity_calendar: Calendar,
    roll_rule: CalendarRollRule,
}

impl IborIndex {
    /// Builds an index over `forwarding`, registering with the curve handle.
    ///
    /// Mirrors the C++ constructor: it composes the base (which normalizes the
    /// tenor and wires evaluation-date and fixing-history observation), stores
    /// the convention and end-of-month flag, and registers the index's
    /// forwarding observer with the curve handle so a relink notifies observers.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        family_name: String,
        tenor: Period,
        settlement_days: Natural,
        currency: Currency,
        fixing_calendar: Calendar,
        convention: BusinessDayConvention,
        end_of_month: bool,
        day_counter: DayCounter,
        forwarding: Handle<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> IborIndex {
        let value_calendar = fixing_calendar.clone();
        let maturity_calendar = fixing_calendar.clone();
        let base = InterestRateIndexBase::new(
            family_name,
            tenor,
            settlement_days,
            currency,
            fixing_calendar,
            day_counter,
            settings,
        );
        forwarding.register_observer(&base.observer());
        IborIndex {
            base,
            convention,
            end_of_month,
            term_structure: forwarding,
            value_calendar,
            maturity_calendar,
            roll_rule: CalendarRollRule::SingleCalendar,
        }
    }

    /// Points the value and maturity rolls at their own calendars and switches
    /// the index to the `CustomIborIndex` three-calendar roll
    /// (`custom.cpp:23-41`).
    ///
    /// The fixing calendar stays the one the constructor took, so the result
    /// carries the C++ subclass's whole configuration as data. The
    /// `Libor` constructor deliberately does not use this: `Libor::valueDate`
    /// advances on the fixing calendar (`libor.cpp:98`), so it points the two
    /// calendars with the crate-internal `set_value_calendar` /
    /// `set_maturity_calendar` and keeps the single-calendar rule.
    #[must_use]
    pub fn with_separate_calendars(
        mut self,
        value_calendar: Calendar,
        maturity_calendar: Calendar,
    ) -> IborIndex {
        self.value_calendar = value_calendar;
        self.maturity_calendar = maturity_calendar;
        self.roll_rule = CalendarRollRule::SeparateCalendars;
        self
    }

    /// The convention applied when rolling the value date to maturity.
    pub fn business_day_convention(&self) -> BusinessDayConvention {
        self.convention
    }

    /// Whether the maturity roll keeps to month ends.
    pub fn end_of_month(&self) -> bool {
        self.end_of_month
    }

    /// The curve used to forecast fixings (`forwardingTermStructure`).
    pub fn forwarding_term_structure(&self) -> &Handle<dyn YieldTermStructure> {
        &self.term_structure
    }

    /// The calendar value dates are computed on (the fixing calendar unless a
    /// Libor-style constructor pointed it elsewhere).
    pub fn value_calendar(&self) -> Calendar {
        self.value_calendar.clone()
    }

    /// The calendar maturity dates are advanced on (the fixing calendar unless
    /// a Libor-style constructor pointed it at a joint calendar).
    pub fn maturity_calendar(&self) -> Calendar {
        self.maturity_calendar.clone()
    }

    /// Points the value roll at `calendar` (used by the Libor constructor).
    pub(crate) fn set_value_calendar(&mut self, calendar: Calendar) {
        self.value_calendar = calendar;
    }

    /// Points the maturity roll at `calendar` (used by the Libor constructor).
    pub(crate) fn set_maturity_calendar(&mut self, calendar: Calendar) {
        self.maturity_calendar = calendar;
    }

    /// Rebuilds this index onto a different forwarding curve, copying every
    /// other configuration field verbatim (`clone`, `iborindex.cpp:85-93`).
    ///
    /// A `DepositRateHelper` clones its index onto its own relinkable handle so
    /// it prices off the curve being bootstrapped rather than the curve the
    /// index was handed (`ratehelpers.cpp:206`). The clone keeps the same family
    /// name and tenor, hence the same D11 fixing-store key, and reuses the same
    /// [`Settings`], so it shares the original's fixing history (keyed on name)
    /// and evaluation date.
    pub fn clone_with(&self, forwarding: Handle<dyn YieldTermStructure>) -> IborIndex {
        let mut clone = IborIndex::new(
            self.family_name().to_string(),
            self.tenor(),
            self.fixing_days(),
            self.currency().clone(),
            self.fixing_calendar(),
            self.convention,
            self.end_of_month,
            self.day_counter().clone(),
            forwarding,
            self.base.settings().clone(),
        );
        clone.value_calendar = self.value_calendar.clone();
        clone.maturity_calendar = self.maturity_calendar.clone();
        clone.roll_rule = self.roll_rule;
        clone
    }

    /// The simple forward rate over `[d1, d2]` with year fraction `t`, read off
    /// the forwarding curve (the C++ `forecastFixing(d1, d2, t)`).
    ///
    /// C++ keeps this overload private and declares `IborCoupon` a `friend`
    /// (`iborindex.hpp:81`), so only the coupon may pass cached dates and no
    /// arbitrary caller can ask a 6-month index for a 1-year fixing. The port
    /// mirrors that trust boundary with crate visibility: reachable by
    /// [`IborCoupon`](crate::cashflows::iborcoupon::IborCoupon)'s par/indexed
    /// forecast, closed to the public API.
    pub(crate) fn forecast_fixing_between(&self, d1: Date, d2: Date, t: Time) -> QlResult<Rate> {
        require!(
            !self.term_structure.is_empty(),
            "null term structure set to this instance of {}",
            self.name()
        );
        let curve = self.term_structure.current_link()?;
        let disc1 = curve.discount_date(d1, false)?;
        let disc2 = curve.discount_date(d2, false)?;
        Ok((disc1 / disc2 - 1.0) / t)
    }
}

impl InterestRateIndex for IborIndex {
    fn base(&self) -> &InterestRateIndexBase {
        &self.base
    }

    /// The fixing date for `value_date`, rolled by the index's calendar rule.
    ///
    /// The single-calendar rule reproduces the trait default: back
    /// `fixing_days` business days on the fixing calendar. The
    /// separate-calendar rule is `CustomIborIndex::fixingDate`
    /// (`custom.cpp:23-27`): back on the value calendar, then a `Preceding`
    /// adjust onto the fixing calendar.
    fn fixing_date(&self, value_date: Date) -> Date {
        let days = -(self.fixing_days() as Integer);
        match self.roll_rule {
            CalendarRollRule::SingleCalendar => self.fixing_calendar().advance(
                value_date,
                days,
                TimeUnit::Days,
                BusinessDayConvention::Following,
                false,
            ),
            CalendarRollRule::SeparateCalendars => {
                let d = self.value_calendar.advance(
                    value_date,
                    days,
                    TimeUnit::Days,
                    BusinessDayConvention::Following,
                    false,
                );
                self.fixing_calendar()
                    .adjust(d, BusinessDayConvention::Preceding)
            }
        }
    }

    /// The value date rolled as `Libor::valueDate` (`libor.cpp:86-100`) or, on
    /// the separate-calendar rule, as `CustomIborIndex::valueDate`
    /// (`custom.cpp:29-36`): the advance runs on
    /// the fixing calendar under the single-calendar rule and on the value
    /// calendar under the separate-calendar one, and both then adjust on the
    /// maturity calendar. With the default calendars the adjust lands on the
    /// business day the advance produced, reducing to the trait default.
    fn value_date(&self, fixing_date: Date) -> QlResult<Date> {
        require!(
            self.is_valid_fixing_date(fixing_date),
            "{fixing_date:?} is not a valid fixing date"
        );
        let advance_calendar = match self.roll_rule {
            CalendarRollRule::SingleCalendar => self.fixing_calendar(),
            CalendarRollRule::SeparateCalendars => self.value_calendar.clone(),
        };
        let d = advance_calendar.advance(
            fixing_date,
            self.fixing_days() as Integer,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );
        Ok(self
            .maturity_calendar
            .adjust(d, BusinessDayConvention::Following))
    }

    fn maturity_date(&self, value_date: Date) -> QlResult<Date> {
        Ok(self.maturity_calendar.advance_by_period(
            value_date,
            self.tenor(),
            self.convention,
            self.end_of_month,
        ))
    }

    fn forecast_fixing(&self, fixing_date: Date) -> QlResult<Rate> {
        let d1 = self.value_date(fixing_date)?;
        let d2 = self.maturity_date(d1)?;
        let t = self.day_counter().year_fraction(d1, d2);
        let positive_time = t > 0.0;
        require!(
            positive_time,
            "cannot calculate forward rate between {d1:?} and {d2:?}: non positive time ({t}) using {} daycounter",
            self.day_counter().name()
        );
        self.forecast_fixing_between(d1, d2, t)
    }
}

/// An overnight index (e.g. SOFR, ESTR): an [`IborIndex`] fixed on a one-day
/// tenor.
///
/// Port of `OvernightIndex` (`ql/indexes/iborindex.hpp:88`), which subclasses
/// [`IborIndex`] and forwards a fixed overnight configuration: a `1*Days`
/// tenor, a [`Following`](BusinessDayConvention::Following) roll, and no
/// end-of-month adjustment. The port keeps that "is-an-`IborIndex`" relation as
/// a newtype embedding the configured [`IborIndex`], re-exposed through
/// [`InterestRateIndex`] (and hence the whole [`Index`] surface) so a
/// downstream overnight coupon can hold a concrete `OvernightIndex` rather than
/// an indistinguishable [`IborIndex`].
///
/// The inner [`IborIndex`] is held behind a [`Shared`] so its identity can be
/// re-exposed through [`ibor_index`](Self::ibor_index). C++ upcasts a single
/// `shared_ptr<OvernightIndex>` into a `shared_ptr<IborIndex>` wherever an
/// overnight index is used as its base (an OIS handing itself to
/// `FixedVsFloatingSwap`, say); the owned newtype cannot project an [`Rc`], so
/// wrapping the inner index restores that single-identity relation.
///
/// The C++ `clone()` override (`iborindex.cpp:85`) re-curves the index onto a
/// different forwarding handle. [`IborIndex`] ports it as
/// [`clone_with`](IborIndex::clone_with) for rate-helper bootstrapping;
/// `OvernightIndex` does not override it, as no overnight helper needs the
/// overnight-typed clone yet.
pub struct OvernightIndex(Shared<IborIndex>);

impl OvernightIndex {
    /// Builds an overnight index over `forwarding`.
    ///
    /// Mirrors the C++ constructor (`iborindex.cpp:76`): an [`IborIndex`] with a
    /// `1*Days` tenor, a [`Following`](BusinessDayConvention::Following) roll,
    /// and `end_of_month = false`, leaving family name, settlement days,
    /// currency, fixing calendar, and day counter to the caller.
    pub fn new(
        family_name: String,
        settlement_days: Natural,
        currency: Currency,
        fixing_calendar: Calendar,
        day_counter: DayCounter,
        forwarding: Handle<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> OvernightIndex {
        OvernightIndex(shared(IborIndex::new(
            family_name,
            Period::new(1, TimeUnit::Days),
            settlement_days,
            currency,
            fixing_calendar,
            BusinessDayConvention::Following,
            false,
            day_counter,
            forwarding,
            settings,
        )))
    }

    /// The inner [`IborIndex`] this overnight index is a `1*Days` configuration
    /// of, sharing its identity (the C++ upcast of the same `shared_ptr`).
    pub fn ibor_index(&self) -> Shared<IborIndex> {
        self.0.clone()
    }

    /// Re-curves the overnight index onto a different forwarding handle,
    /// preserving its configuration (the C++ `clone(h)` override that
    /// `OISRateHelper::initialize` calls, `oisratehelper.cpp:114`). The result
    /// stays overnight-typed, so it can be handed back to [`MakeOis`], mirroring
    /// C++'s `dynamic_pointer_cast<OvernightIndex>(clone(...))`.
    ///
    /// [`MakeOis`]: crate::instruments::MakeOis
    pub fn clone_with(&self, forwarding: Handle<dyn YieldTermStructure>) -> Shared<OvernightIndex> {
        shared(OvernightIndex(shared(self.0.clone_with(forwarding))))
    }

    /// The convention applied when rolling the value date to maturity (always
    /// [`Following`](BusinessDayConvention::Following)).
    pub fn business_day_convention(&self) -> BusinessDayConvention {
        self.0.business_day_convention()
    }

    /// Whether the maturity roll keeps to month ends (always `false`).
    pub fn end_of_month(&self) -> bool {
        self.0.end_of_month()
    }

    /// The curve used to forecast fixings (`forwardingTermStructure`).
    pub fn forwarding_term_structure(&self) -> &Handle<dyn YieldTermStructure> {
        self.0.forwarding_term_structure()
    }
}

impl InterestRateIndex for OvernightIndex {
    fn base(&self) -> &InterestRateIndexBase {
        self.0.base()
    }

    fn maturity_date(&self, value_date: Date) -> QlResult<Date> {
        self.0.maturity_date(value_date)
    }

    fn forecast_fixing(&self, fixing_date: Date) -> QlResult<Rate> {
        self.0.forecast_fixing(fixing_date)
    }
}

#[cfg(test)]
mod tests {
    //! Oracles for the plain single-calendar `IborIndex`.
    //!
    //! `indexes.cpp testCustomIborIndex` (:152) exercises `CustomIborIndex`, the
    //! three-calendar variant ported in
    //! [`ibor::custom`](crate::indexes::ibor::custom), whose tests carry that
    //! oracle's date assertions. Plain `IborIndex` has one calendar, so these
    //! tests cover only the single-calendar subset.

    use super::*;
    use crate::handle::RelinkableHandle;
    use crate::interestrate::Compounding;
    use crate::patterns::observable::Observer;
    use crate::shared::{SharedMut, shared, shared_mut};
    use crate::termstructures::yields::FlatForward;
    use crate::time::calendars::bespokecalendar::BespokeCalendar;
    use crate::time::calendars::target::Target;
    use crate::time::calendars::unitedstates::{Market, UnitedStates};
    use crate::time::date::Month;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::frequency::Frequency;
    use crate::time::timeunit::TimeUnit;

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

    /// A `foo` index on TARGET, Actual/360, two settlement days - the shape
    /// `indexes.cpp`'s `IborIndex("foo", ...)` cases use.
    fn ibor(
        tenor: Period,
        forwarding: Handle<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> IborIndex {
        IborIndex::new(
            "foo".into(),
            tenor,
            2,
            Currency::eur(),
            Target::new(),
            BusinessDayConvention::Following,
            false,
            Actual360::new(),
            forwarding,
            settings,
        )
    }

    /// A three-month index on `fixing_calendar`, the shape the roll-rule teeth
    /// point at three bespoke calendars.
    fn bespoke_ibor(fixing_calendar: Calendar) -> IborIndex {
        IborIndex::new(
            "bespoke".into(),
            Period::new(3, TimeUnit::Months),
            2,
            Currency::new("", "", 0, "", "", 0),
            fixing_calendar,
            BusinessDayConvention::ModifiedFollowing,
            true,
            Actual360::new(),
            Handle::empty(),
            shared(Settings::<Date>::new()),
        )
    }

    /// The roll-rule teeth: no single C++ test discriminates the two subclass
    /// bodies against each other, so this pits them on one fixture. Two
    /// [`BespokeCalendar`]s (no weekends, so the placed holiday is the only
    /// variable) differ on Saturday 11 January 2025 alone, which sits inside
    /// the two-day settlement window off the 10th and the 13th.
    ///
    /// The single-calendar index points its value calendar at that holiday
    /// calendar too, so only the rule - not the stored calendars - can move
    /// the dates: it must roll 10 -> 12 January and 13 -> 11 January, ignoring
    /// the value calendar entirely, where the separate-calendar rule rolls
    /// through the holiday to 13 and 10 January.
    #[test]
    fn the_roll_rule_selects_the_calendar_the_advances_run_on() {
        let fix_cal = BespokeCalendar::new("Fixings").calendar();
        let val_cal = BespokeCalendar::new("Value").calendar();
        val_cal.add_holiday(Date::new(11, Month::January, 2025));
        let mat_cal = BespokeCalendar::new("Maturity").calendar();

        let mut single = bespoke_ibor(fix_cal.clone());
        single.set_value_calendar(val_cal.clone());
        single.set_maturity_calendar(mat_cal.clone());
        let separate = bespoke_ibor(fix_cal).with_separate_calendars(val_cal, mat_cal);

        let fixing = Date::new(10, Month::January, 2025);
        assert_eq!(
            single.value_date(fixing).unwrap(),
            Date::new(12, Month::January, 2025)
        );
        assert_eq!(
            separate.value_date(fixing).unwrap(),
            Date::new(13, Month::January, 2025)
        );

        let value = Date::new(13, Month::January, 2025);
        assert_eq!(
            single.fixing_date(value),
            Date::new(11, Month::January, 2025)
        );
        assert_eq!(
            separate.fixing_date(value),
            Date::new(10, Month::January, 2025)
        );
    }

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

    /// `testTenorNormalization` (indexes.cpp:124): a 12-month index and a
    /// 1-year index normalize to the same name.
    #[test]
    fn twelve_months_and_one_year_yield_the_same_name() {
        let settings = shared(Settings::<Date>::new());
        let i12m = ibor(
            Period::new(12, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let i1y = ibor(Period::new(1, TimeUnit::Years), Handle::empty(), settings);
        assert_eq!(i12m.name(), i1y.name());
    }

    /// `testTenorNormalization` (indexes.cpp:124): the 6-day index matures
    /// before the 7-day index off the same date.
    #[test]
    fn six_day_index_matures_before_seven_day_index() {
        let settings = shared(Settings::<Date>::new());
        let i6d = ibor(
            Period::new(6, TimeUnit::Days),
            Handle::empty(),
            settings.clone(),
        );
        let i7d = ibor(Period::new(7, TimeUnit::Days), Handle::empty(), settings);
        let test_date = Date::new(28, Month::April, 2023);
        assert!(i6d.maturity_date(test_date).unwrap() < i7d.maturity_date(test_date).unwrap());
    }

    /// `testFixingHasHistoricalFixing` (indexes.cpp:83) through the index: a
    /// fixing added on one index is seen by another instance of the same name
    /// (the store keys on name), not by a differently-tenored index, and clears.
    #[test]
    fn historical_fixing_is_shared_by_name_and_cleared() {
        let today = Date::new(15, Month::June, 2026);
        let settings = settings_on(today);
        let ibor6m = ibor(
            Period::new(6, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let ibor3m = ibor(
            Period::new(3, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let ibor6m_a = ibor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);

        let mut day = today;
        while !ibor6m.is_valid_fixing_date(day) {
            day -= 1;
        }
        ibor6m.add_fixing(day, 0.01).unwrap();

        assert!(!ibor3m.has_historical_fixing(day));
        assert!(ibor6m.has_historical_fixing(day));
        assert!(ibor6m_a.has_historical_fixing(day));

        ibor6m.clear_fixings();
        assert!(!ibor6m.has_historical_fixing(day));
        assert!(!ibor6m_a.has_historical_fixing(day));
    }

    /// `forecastFixing` (iborindex.cpp:44) reads the simple forward
    /// `(disc1/disc2 - 1)/t` off the curve between the value and maturity dates.
    ///
    /// The simple-forward formula is `iborindex.hpp`'s private `forecastFixing`
    /// overload (:112-120); no C++ suite test pins it directly for a plain
    /// `IborIndex` (`testCdiIndex` :206 asserts a Brazil CDI *compounded*
    /// forecast, a different formula on a different index). So this checks two
    /// independent things: the implementation matches the discount-factor
    /// formula (a plumbing pin), and it matches the closed form of a simple
    /// forward on a continuously-compounded flat curve, `(exp(r*t) - 1)/t`,
    /// computed here without touching the curve.
    #[test]
    fn forecast_fixing_reads_the_simple_forward_off_the_curve() {
        let today = Date::new(15, Month::June, 2026);
        let settings = settings_on(today);
        let rate = 0.05;
        let curve = flat_curve(today, rate);
        let index = ibor(Period::new(6, TimeUnit::Months), curve.clone(), settings);

        let fixing_date = Date::new(15, Month::July, 2026);
        let d1 = index.value_date(fixing_date).unwrap();
        let d2 = index.maturity_date(d1).unwrap();
        let t = Actual360::new().year_fraction(d1, d2);
        let forecast = index.forecast_fixing(fixing_date).unwrap();

        let link = curve.current_link().unwrap();
        let disc1 = link.discount_date(d1, false).unwrap();
        let disc2 = link.discount_date(d2, false).unwrap();
        assert!((forecast - (disc1 / disc2 - 1.0) / t).abs() < 1e-12);

        let analytic = ((rate * t).exp() - 1.0) / t;
        assert!((forecast - analytic).abs() < 1e-12);
        assert!(forecast > 0.0);
    }

    /// The `iborindex.hpp` private-overload guard: forecasting off an empty
    /// forwarding handle is an error carrying the C++ message, not a panic.
    #[test]
    fn forecast_on_an_empty_curve_is_an_error() {
        let today = Date::new(15, Month::June, 2026);
        let settings = settings_on(today);
        let index = ibor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);
        let err = index
            .forecast_fixing(Date::new(15, Month::July, 2026))
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("null term structure set to this instance of")
        );
    }

    struct Flag {
        up: bool,
    }

    impl Observer for Flag {
        fn update(&mut self) {
            self.up = true;
        }
    }

    /// `registerWith(termStructure_)` (iborindex.cpp:39): relinking the
    /// forwarding curve notifies the index's observers.
    #[test]
    fn relinking_the_forwarding_curve_notifies_the_index() {
        let today = Date::new(15, Month::June, 2026);
        let settings = settings_on(today);
        let handle: RelinkableHandle<dyn YieldTermStructure> = RelinkableHandle::empty();
        let index = ibor(Period::new(6, TimeUnit::Months), handle.handle(), settings);

        let flag = shared_mut(Flag { up: false });
        index
            .base()
            .observable()
            .register_observer(&(flag.clone() as SharedMut<dyn Observer>));

        handle.link_to(shared(FlatForward::with_rate(
            today,
            0.05,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>);

        assert!(flag.borrow().up);
    }

    /// `clone` (`iborindex.cpp:85`) re-curves onto a new handle while copying
    /// every other field verbatim: the clone forecasts off its own curve (the
    /// original untouched), and - keyed on the same name - shares the
    /// original's fixing history.
    #[test]
    fn clone_with_recurves_and_shares_fixing_history() {
        let today = Date::new(15, Month::June, 2026);
        let settings = settings_on(today);
        let original = ibor(
            Period::new(6, TimeUnit::Months),
            flat_curve(today, 0.05),
            settings,
        );

        let cloned_handle: RelinkableHandle<dyn YieldTermStructure> = RelinkableHandle::empty();
        let clone = original.clone_with(cloned_handle.handle());

        assert_eq!(clone.name(), original.name());
        assert_eq!(clone.tenor(), original.tenor());
        assert_eq!(clone.fixing_days(), original.fixing_days());
        assert_eq!(
            clone.business_day_convention(),
            original.business_day_convention()
        );
        assert_eq!(clone.end_of_month(), original.end_of_month());

        let fixing_date = Date::new(15, Month::July, 2026);
        assert!(
            clone.forecast_fixing(fixing_date).is_err(),
            "clone starts on its own empty handle"
        );
        cloned_handle.link_to(shared(FlatForward::with_rate(
            today,
            0.02,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>);

        let d1 = clone.value_date(fixing_date).unwrap();
        let d2 = clone.maturity_date(d1).unwrap();
        let t = Actual360::new().year_fraction(d1, d2);
        let clone_forecast = clone.forecast_fixing(fixing_date).unwrap();
        assert!((clone_forecast - ((0.02 * t).exp() - 1.0) / t).abs() < 1e-12);
        let original_forecast = original.forecast_fixing(fixing_date).unwrap();
        assert!(
            (original_forecast - ((0.05 * t).exp() - 1.0) / t).abs() < 1e-12,
            "the original still forecasts off its own curve"
        );

        let mut day = today;
        while !original.is_valid_fixing_date(day) {
            day -= 1;
        }
        original.add_fixing(day, 0.01).unwrap();
        assert!(
            clone.has_historical_fixing(day),
            "a clone shares the original's fixing history by name"
        );
    }

    /// `OvernightIndex` (`iborindex.cpp:76`) pins the overnight configuration:
    /// a one-day tenor named `ON` at zero fixing days, a `Following` roll, and
    /// no end-of-month adjustment.
    #[test]
    fn overnight_index_carries_the_overnight_configuration() {
        let settings = shared(Settings::<Date>::new());
        let index = OvernightIndex::new(
            "SOFR".into(),
            0,
            Currency::usd(),
            UnitedStates::new(Market::Sofr),
            Actual360::new(),
            Handle::empty(),
            settings,
        );

        assert_eq!(index.tenor(), Period::new(1, TimeUnit::Days));
        assert_eq!(index.fixing_days(), 0);
        assert_eq!(
            index.business_day_convention(),
            BusinessDayConvention::Following
        );
        assert!(!index.end_of_month());
        assert_eq!(index.name(), "SOFRON Actual/360");
        assert_eq!(index.fixing_calendar().name(), "SOFR fixing calendar");
    }

    /// The overnight index forecasts through the inherited [`IborIndex`]
    /// machinery: over a flat continuously-compounded curve its one-day forward
    /// matches the closed form `(exp(r*t) - 1)/t`.
    #[test]
    fn overnight_index_forecasts_through_the_ibor_machinery() {
        let today = Date::new(15, Month::June, 2026);
        let settings = settings_on(today);
        let rate = 0.05;
        let index = OvernightIndex::new(
            "ESTR".into(),
            0,
            Currency::eur(),
            Target::new(),
            Actual360::new(),
            flat_curve(today, rate),
            settings,
        );

        let fixing_date = Date::new(15, Month::July, 2026);
        let d1 = index.value_date(fixing_date).unwrap();
        let d2 = index.maturity_date(d1).unwrap();
        let t = Actual360::new().year_fraction(d1, d2);
        let forecast = index.forecast_fixing(fixing_date).unwrap();
        let analytic = ((rate * t).exp() - 1.0) / t;
        assert!((forecast - analytic).abs() < 1e-12);
    }
}