libitofin 0.5.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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
//! Rate helpers for the yield-curve bootstrap.
//!
//! Port of `ql/termstructures/yield/ratehelpers.{hpp,cpp}` plus the overnight
//! helper of `ql/termstructures/yield/oisratehelper.{hpp,cpp}`. This module holds
//! [`DepositRateHelper`], the short end of the curve, [`SwapRateHelper`], the
//! long end over vanilla swaps, and [`OISRateHelper`], the long end over
//! overnight-indexed swaps. The FRA and futures helpers (`FraRateHelper`,
//! `FuturesRateHelper`) and `BMASwapRateHelper` are deferred to a later ticket
//! (#343); the `SwapIndex`-based and explicit-start/end-date `SwapRateHelper`
//! constructors are deferred with the swap-index port. The `OISRateHelper`
//! explicit-start/end-date constructor is deferred likewise.

use std::cell::Cell;
use std::cell::RefCell;
use std::rc::Weak;

use crate::cashflows::RateAveraging;
use crate::errors::QlResult;
use crate::handle::{Handle, RelinkableHandle};
use crate::indexes::OvernightIndex;
use crate::indexes::iborindex::IborIndex;
use crate::indexes::index::Index;
use crate::indexes::interestrateindex::InterestRateIndex;
use crate::instrument::Instrument;
use crate::instruments::{MakeOis, MakeVanillaSwap, OvernightIndexedSwap, VanillaSwap};
use crate::patterns::observable::{AsObservable, Observable};
use crate::quotes::{Quote, SimpleQuote};
use crate::settings::Settings;
use crate::shared::{Shared, shared};
use crate::termstructures::bootstraphelper::{
    BootstrapHelperBase, RateHelper, RelativeDateRateHelper,
};
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::frequency::Frequency;
use crate::time::period::Period;
use crate::time::timeunit::TimeUnit;
use crate::types::{Integer, Natural, Real};

/// Bootstrap helper over a deposit rate (`DepositRateHelper`).
///
/// A deposit borrows at the quoted rate from spot to spot-plus-tenor;
/// [`implied_quote`](RateHelper::implied_quote) re-derives that rate from the
/// bootstrapping curve's discount factors between the value and maturity dates.
///
/// The load-bearing mechanism is the cloned index: the constructor re-curves
/// the supplied index onto the helper's *own* [`RelinkableHandle`] with
/// [`IborIndex::clone_with`] (`ratehelpers.cpp:206`), so the helper forecasts
/// off the curve it is being bootstrapped against rather than whatever curve
/// the index was handed. [`set_term_structure`](RateHelper::set_term_structure)
/// weak-links that handle to the bootstrapping curve, non-owning and unobserved
/// (the `null_deleter`/`observer = false` of `ratehelpers.cpp:217`).
pub struct DepositRateHelper {
    base: BootstrapHelperBase,
    index: IborIndex,
    term_structure_handle: RelinkableHandle<dyn YieldTermStructure>,
    fixing_date: Cell<Date>,
}

impl DepositRateHelper {
    /// A deposit helper fitting `quote`, an explicit market-rate handle, with
    /// its schedule taken from `index` (the C++ `DepositRateHelper(rate, i)`
    /// with `rate` a `Handle<Quote>`, `ratehelpers.cpp:195`).
    pub fn new(quote: Handle<dyn Quote>, index: &IborIndex) -> Shared<DepositRateHelper> {
        Self::build(quote, index)
    }

    /// A deposit helper fitting a fixed `rate`, wrapped in a [`SimpleQuote`]
    /// (the `rate`-as-`Rate` arm of the same C++ variant constructor).
    pub fn from_rate(rate: Real, index: &IborIndex) -> Shared<DepositRateHelper> {
        let quote = Handle::new(shared(SimpleQuote::new(rate)) as Shared<dyn Quote>);
        Self::build(quote, index)
    }

    fn build(quote: Handle<dyn Quote>, source_index: &IborIndex) -> Shared<DepositRateHelper> {
        let settings = source_index.base().settings().clone();
        Shared::new_cyclic(|weak: &Weak<DepositRateHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    helper.initialize_dates();
                }
            });
            let term_structure_handle = RelinkableHandle::<dyn YieldTermStructure>::empty();
            let index = source_index.clone_with(term_structure_handle.handle());
            let base = BootstrapHelperBase::new_relative(quote, settings, true, on_eval_change);
            let helper = DepositRateHelper {
                base,
                index,
                term_structure_handle,
                fixing_date: Cell::new(Date::null()),
            };
            helper.initialize_dates();
            helper
        })
    }
}

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

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

    /// The deposit rate implied by the current curve.
    ///
    /// The forecast flag is forced true (`iborIndex_->fixing(fixingDate_, true)`,
    /// `ratehelpers.cpp:213`): the helper prices off the curve, never off a
    /// stored fixing.
    fn implied_quote(&self) -> QlResult<Real> {
        self.base.term_structure()?;
        self.index.fixing(self.fixing_date.get(), true)
    }

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

impl RelativeDateRateHelper for DepositRateHelper {
    /// Rebuilds the schedule off the current evaluation date
    /// (`initializeDates`, `ratehelpers.cpp:228`): the reference date is the
    /// evaluation date rolled to a business day, the earliest (value) date is
    /// spot from there, the fixing date the value date rolled back, and the
    /// maturity the value date advanced by the tenor. Pillar, latest and
    /// latest-relevant dates all equal the maturity.
    ///
    /// The value- and maturity-date arithmetic is calendar rolling on an
    /// already-adjusted business day and so cannot fail; the `expect` documents
    /// that invariant.
    fn initialize_dates(&self) {
        let evaluation_date = self
            .base
            .evaluation_date()
            .expect("a relative-date helper always tracks an evaluation date");
        let reference_date = self
            .index
            .fixing_calendar()
            .adjust(evaluation_date, BusinessDayConvention::Following);
        let earliest = self
            .index
            .value_date(reference_date)
            .expect("value date of an adjusted business day is valid");
        self.fixing_date.set(self.index.fixing_date(earliest));
        let maturity = self
            .index
            .maturity_date(earliest)
            .expect("maturity date of a value date is valid");

        self.base.set_earliest_date(earliest);
        self.base.set_maturity_date(maturity);
        self.base.set_pillar_date(maturity);
        self.base.set_latest_date(maturity);
        self.base.set_latest_relevant_date(maturity);
    }
}

/// The date the curve node a helper fits sits at (`Pillar::Choice`).
///
/// Only the two schedule-derived choices are ported: [`LastRelevantDate`] (the
/// C++ default) and [`MaturityDate`]. `Pillar::CustomDate`, which needs an
/// explicit pillar date threaded through construction plus its bounds check, is
/// deferred to #343 with the constructors that pass one.
///
/// [`LastRelevantDate`]: Pillar::LastRelevantDate
/// [`MaturityDate`]: Pillar::MaturityDate
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pillar {
    /// The instrument's maturity date.
    MaturityDate,
    /// The latest date the instrument needs data at.
    LastRelevantDate,
}

/// Bootstrap helper over a par swap rate (`SwapRateHelper`).
///
/// The helper fits the fixed rate at which a spot-starting vanilla swap of the
/// quoted tenor is worth par on the bootstrapping curve. Its own swap is built
/// through [`MakeVanillaSwap`] (`ratehelpers.cpp:557`) off a cloned index and a
/// relinkable discounting handle, so the helper prices against the curve it is
/// being bootstrapped against.
///
/// [`implied_quote`](RateHelper::implied_quote) is **not** the swap's fair rate:
/// it is the par-rate reconstruction of `ratehelpers.cpp:633-646`, over the
/// floating- and fixed-leg NPV and BPS, carrying the spread term that a bare
/// `fair_rate()` would drop. Because the helper deliberately does not observe
/// the curve (its pricing handles are weak-linked, unobserved), the swap's
/// cached results go stale when the bootstrap moves the curve; the C++
/// `swap_->deepUpdate()` forces a fresh calculation each call, and this port
/// reproduces that with [`Instrument::recalculate`] before reading the legs.
///
/// The indexed-vs-at-par coupon mode is not read from a global singleton: the
/// helper carries the C++ `useIndexedCoupons_` `optional<bool>` (default `None`)
/// and forwards it to [`MakeVanillaSwap::with_indexed_coupons`], which resolves
/// `None` against [`Settings::using_at_par_coupons`] (D5, #315/#342).
pub struct SwapRateHelper {
    base: BootstrapHelperBase,
    swap: RefCell<Option<VanillaSwap>>,
    ibor_index: Shared<IborIndex>,
    term_structure_handle: RelinkableHandle<dyn YieldTermStructure>,
    discount_relinkable_handle: RelinkableHandle<dyn YieldTermStructure>,
    discount_handle: Option<Handle<dyn YieldTermStructure>>,
    spread: Handle<dyn Quote>,
    settings: Shared<Settings<Date>>,
    tenor: Period,
    forward_start: Period,
    calendar: Calendar,
    fixed_frequency: Frequency,
    fixed_convention: BusinessDayConvention,
    fixed_day_count: DayCounter,
    end_of_month: bool,
    use_indexed_coupons: Option<bool>,
    pillar: Pillar,
}

impl SwapRateHelper {
    /// A swap helper fitting `quote` with the schedule of a spot-starting swap
    /// of `tenor`, the form the curve-consistency oracle builds
    /// (`piecewiseyieldcurve.cpp:293`): no spread, no forward start, no exogenous
    /// discounting curve, and the default [`Pillar::LastRelevantDate`].
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        quote: Handle<dyn Quote>,
        tenor: Period,
        calendar: Calendar,
        fixed_frequency: Frequency,
        fixed_convention: BusinessDayConvention,
        fixed_day_count: DayCounter,
        ibor_index: &IborIndex,
    ) -> Shared<SwapRateHelper> {
        Self::build(
            quote,
            tenor,
            calendar,
            fixed_frequency,
            fixed_convention,
            fixed_day_count,
            ibor_index,
            Handle::empty(),
            Period::new(0, TimeUnit::Days),
            None,
            Pillar::LastRelevantDate,
        )
    }

    /// A swap helper fitting a fixed `rate`, wrapped in a [`SimpleQuote`].
    #[allow(clippy::too_many_arguments)]
    pub fn from_rate(
        rate: Real,
        tenor: Period,
        calendar: Calendar,
        fixed_frequency: Frequency,
        fixed_convention: BusinessDayConvention,
        fixed_day_count: DayCounter,
        ibor_index: &IborIndex,
    ) -> Shared<SwapRateHelper> {
        let quote = Handle::new(shared(SimpleQuote::new(rate)) as Shared<dyn Quote>);
        Self::new(
            quote,
            tenor,
            calendar,
            fixed_frequency,
            fixed_convention,
            fixed_day_count,
            ibor_index,
        )
    }

    /// The full constructor of the ported (tenor-based) form: a market `spread`
    /// handle (empty for none), a `forward_start`, an optional exogenous
    /// `discounting_curve`, and the [`Pillar`] choice.
    #[allow(clippy::too_many_arguments)]
    pub fn with_details(
        quote: Handle<dyn Quote>,
        tenor: Period,
        calendar: Calendar,
        fixed_frequency: Frequency,
        fixed_convention: BusinessDayConvention,
        fixed_day_count: DayCounter,
        ibor_index: &IborIndex,
        spread: Handle<dyn Quote>,
        forward_start: Period,
        discounting_curve: Option<Handle<dyn YieldTermStructure>>,
        pillar: Pillar,
    ) -> Shared<SwapRateHelper> {
        Self::build(
            quote,
            tenor,
            calendar,
            fixed_frequency,
            fixed_convention,
            fixed_day_count,
            ibor_index,
            spread,
            forward_start,
            discounting_curve,
            pillar,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn build(
        quote: Handle<dyn Quote>,
        tenor: Period,
        calendar: Calendar,
        fixed_frequency: Frequency,
        fixed_convention: BusinessDayConvention,
        fixed_day_count: DayCounter,
        source_index: &IborIndex,
        spread: Handle<dyn Quote>,
        forward_start: Period,
        discounting_curve: Option<Handle<dyn YieldTermStructure>>,
        pillar: Pillar,
    ) -> Shared<SwapRateHelper> {
        let settings = source_index.base().settings().clone();
        Shared::new_cyclic(|weak: &Weak<SwapRateHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    helper.initialize_dates();
                }
            });
            let term_structure_handle = RelinkableHandle::<dyn YieldTermStructure>::empty();
            let ibor_index = shared(source_index.clone_with(term_structure_handle.handle()));
            let base = BootstrapHelperBase::new_relative(
                quote,
                Shared::clone(&settings),
                true,
                on_eval_change,
            );
            let helper = SwapRateHelper {
                base,
                swap: RefCell::new(None),
                ibor_index,
                term_structure_handle,
                discount_relinkable_handle: RelinkableHandle::<dyn YieldTermStructure>::empty(),
                discount_handle: discounting_curve,
                spread,
                settings,
                tenor,
                forward_start,
                calendar,
                fixed_frequency,
                fixed_convention,
                fixed_day_count,
                end_of_month: false,
                use_indexed_coupons: None,
                pillar,
            };
            helper.initialize_dates();
            helper
        })
    }
}

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

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

    /// The par swap rate implied by the current curve
    /// (`ratehelpers.cpp:633-646`).
    ///
    /// The swap is force-recalculated first (the C++ `swap_->deepUpdate()`,
    /// forced because the helper does not observe the curve); then the rate is
    /// reconstructed from the floating-leg NPV, the spread carried on the
    /// floating-leg BPS, and the fixed-leg BPS, rather than read from
    /// `fair_rate()`.
    fn implied_quote(&self) -> QlResult<Real> {
        self.base.term_structure()?;
        let mut guard = self.swap.borrow_mut();
        let swap = guard
            .as_mut()
            .expect("initialize_dates populates the swap at construction");
        swap.recalculate()?;

        const BASIS_POINT: Real = 1.0e-4;
        let floating_leg_npv = swap.fixed_vs_floating_mut().floating_leg_npv()?;
        let spread = if self.spread.is_empty() {
            0.0
        } else {
            self.spread.current_link()?.value()?
        };
        let spread_npv = swap.fixed_vs_floating_mut().floating_leg_bps()? / BASIS_POINT * spread;
        let total_npv = -(floating_leg_npv + spread_npv);
        let fixed_leg_bps = swap.fixed_vs_floating_mut().fixed_leg_bps()?;
        Ok(total_npv / (fixed_leg_bps / BASIS_POINT))
    }

    /// Weak-links both the forecasting handle (used by the cloned index) and the
    /// discounting handle to the bootstrapping curve - or, when an exogenous
    /// discounting curve was supplied, links the discounting handle to that
    /// instead - then records the curve on the base (`ratehelpers.cpp:614`). All
    /// links are non-owning and unobserved.
    fn set_term_structure(&self, term_structure: &Shared<dyn YieldTermStructure>) {
        self.term_structure_handle
            .link_to_weak(Shared::downgrade(term_structure));
        match &self.discount_handle {
            Some(discount) if !discount.is_empty() => {
                let curve = discount
                    .current_link()
                    .expect("a non-empty discount handle resolves");
                self.discount_relinkable_handle
                    .link_to_weak(Shared::downgrade(&curve));
            }
            _ => self
                .discount_relinkable_handle
                .link_to_weak(Shared::downgrade(term_structure)),
        }
        self.base.set_term_structure(term_structure);
    }
}

impl RelativeDateRateHelper for SwapRateHelper {
    /// Rebuilds the swap and its schedule off the current evaluation date
    /// (`initializeDates`, `ratehelpers.cpp:530`): a spot-starting swap of the
    /// helper's tenor, built through [`MakeVanillaSwap`] with a 0% fixed rate so
    /// it does not price at construction. Earliest and maturity come from the
    /// leg schedules; the pillar follows the [`Pillar`] choice.
    ///
    /// The `latest_relevant_date` is set to the maturity. C++ takes the maximum
    /// of the maturity and the last floating coupon's `fixingEndDate`; that
    /// refinement needs an `IborCoupon` fixing-end-date accessor the cash-flow
    /// surface does not yet expose, so it is deferred to the bootstrap ticket
    /// (#341) that exercises pillar ordering.
    fn initialize_dates(&self) {
        let fixed_tenor = if self.fixed_frequency == Frequency::Once {
            self.tenor
        } else {
            Period::try_from(self.fixed_frequency)
                .expect("a swap's fixed frequency maps to a valid period")
        };
        let swap = MakeVanillaSwap::new(
            self.tenor,
            Shared::clone(&self.ibor_index),
            Some(0.0),
            self.forward_start,
            Shared::clone(&self.settings),
        )
        .with_discounting_term_structure(self.discount_relinkable_handle.handle())
        .with_fixed_leg_day_count(self.fixed_day_count.clone())
        .with_fixed_leg_tenor(fixed_tenor)
        .with_fixed_leg_convention(self.fixed_convention)
        .with_fixed_leg_termination_date_convention(self.fixed_convention)
        .with_fixed_leg_calendar(self.calendar.clone())
        .with_fixed_leg_end_of_month(self.end_of_month)
        .with_floating_leg_calendar(self.calendar.clone())
        .with_floating_leg_end_of_month(self.end_of_month)
        .with_indexed_coupons(self.use_indexed_coupons)
        .build()
        .expect("a 0% fixed-rate swap with a valid evaluation date builds without pricing");

        let base = swap.fixed_vs_floating();
        let earliest = base
            .fixed_schedule()
            .start_date()
            .min(base.floating_schedule().start_date());
        let maturity = base
            .fixed_schedule()
            .end_date()
            .max(base.floating_schedule().end_date());

        let latest_relevant = maturity;
        self.base.set_earliest_date(earliest);
        self.base.set_maturity_date(maturity);
        self.base.set_latest_relevant_date(latest_relevant);
        let pillar = match self.pillar {
            Pillar::MaturityDate => maturity,
            Pillar::LastRelevantDate => latest_relevant,
        };
        self.base.set_pillar_date(pillar);
        self.base.set_latest_date(pillar);

        *self.swap.borrow_mut() = Some(swap);
    }
}

/// Bootstrap helper over an overnight-indexed-swap (OIS) rate (`OISRateHelper`).
///
/// The helper fits the fixed rate at which an OIS of the quoted tenor is worth
/// par on the bootstrapping curve. Its own swap is built through [`MakeOis`]
/// (`oisratehelper.cpp:130`) off a cloned overnight index and a relinkable
/// discounting handle, so it prices against the curve it is being bootstrapped
/// against.
///
/// [`implied_quote`](RateHelper::implied_quote) is the par-rate reconstruction
/// of `oisratehelper.cpp:220-232` (the same shape as [`SwapRateHelper`]'s, not
/// `fair_rate()`): over the overnight-leg NPV and BPS and the fixed-leg BPS,
/// carrying the spread term. Because the helper deliberately does not observe
/// the curve (its pricing handles are weak-linked, unobserved), the swap's
/// cached results go stale when the bootstrap moves the curve; the C++
/// `swap_->deepUpdate()` forces a fresh calculation each call, reproduced here
/// with [`Instrument::recalculate`] before reading the legs.
pub struct OISRateHelper {
    base: BootstrapHelperBase,
    swap: RefCell<Option<OvernightIndexedSwap>>,
    overnight_index: Shared<OvernightIndex>,
    term_structure_handle: RelinkableHandle<dyn YieldTermStructure>,
    discount_relinkable_handle: RelinkableHandle<dyn YieldTermStructure>,
    discount_handle: Option<Handle<dyn YieldTermStructure>>,
    overnight_spread: Handle<dyn Quote>,
    settings: Shared<Settings<Date>>,
    settlement_days: Natural,
    tenor: Period,
    forward_start: Period,
    payment_lag: Integer,
    payment_convention: BusinessDayConvention,
    payment_frequency: Frequency,
    averaging_method: RateAveraging,
    pillar: Pillar,
}

impl OISRateHelper {
    /// An OIS helper fitting `quote` with the schedule of a swap of `tenor`
    /// starting `settlement_days` after the evaluation date, the form the
    /// bootstrap oracle builds (`overnightindexedswap.cpp:236-256`).
    ///
    /// `discounting_curve` is the exogenous discounting curve (empty `None` to
    /// discount off the bootstrapping curve). `overnight_spread` is the market
    /// spread handle (empty for none). The deferred knobs the C++ constructor
    /// carries past `averaging_method` (telescopic value dates, lookback,
    /// lockout, observation shift, custom pillar, per-leg calendars) take their
    /// benign defaults, mirroring the oracle's positional construction.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        settlement_days: Natural,
        tenor: Period,
        quote: Handle<dyn Quote>,
        overnight_index: &OvernightIndex,
        discounting_curve: Option<Handle<dyn YieldTermStructure>>,
        payment_lag: Integer,
        payment_convention: BusinessDayConvention,
        payment_frequency: Frequency,
        forward_start: Period,
        overnight_spread: Handle<dyn Quote>,
        pillar: Pillar,
        averaging_method: RateAveraging,
        settings: Shared<Settings<Date>>,
    ) -> Shared<OISRateHelper> {
        Shared::new_cyclic(|weak: &Weak<OISRateHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    helper.initialize_dates();
                }
            });
            let term_structure_handle = RelinkableHandle::<dyn YieldTermStructure>::empty();
            let cloned_index = overnight_index.clone_with(term_structure_handle.handle());
            let base = BootstrapHelperBase::new_relative(
                quote,
                Shared::clone(&settings),
                true,
                on_eval_change,
            );
            let helper = OISRateHelper {
                base,
                swap: RefCell::new(None),
                overnight_index: cloned_index,
                term_structure_handle,
                discount_relinkable_handle: RelinkableHandle::<dyn YieldTermStructure>::empty(),
                discount_handle: discounting_curve,
                overnight_spread,
                settings,
                settlement_days,
                tenor,
                forward_start,
                payment_lag,
                payment_convention,
                payment_frequency,
                averaging_method,
                pillar,
            };
            helper.initialize_dates();
            helper
        })
    }
}

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

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

    /// The par OIS rate implied by the current curve (`oisratehelper.cpp:220-232`).
    ///
    /// The swap is force-recalculated first (the C++ `swap_->deepUpdate()`,
    /// forced because the helper does not observe the curve); then the rate is
    /// reconstructed from the overnight-leg NPV, the spread carried on the
    /// overnight-leg BPS, and the fixed-leg BPS, rather than read from
    /// `fair_rate()`.
    fn implied_quote(&self) -> QlResult<Real> {
        self.base.term_structure()?;
        let mut guard = self.swap.borrow_mut();
        let swap = guard
            .as_mut()
            .expect("initialize_dates populates the swap at construction");
        swap.recalculate()?;

        const BASIS_POINT: Real = 1.0e-4;
        let overnight_leg_npv = swap.overnight_leg_npv()?;
        let spread = if self.overnight_spread.is_empty() {
            0.0
        } else {
            self.overnight_spread.current_link()?.value()?
        };
        let spread_npv = swap.overnight_leg_bps()? / BASIS_POINT * spread;
        let total_npv = -(overnight_leg_npv + spread_npv);
        let fixed_leg_bps = swap.fixed_vs_floating_mut().fixed_leg_bps()?;
        Ok(total_npv / (fixed_leg_bps / BASIS_POINT))
    }

    /// Weak-links the forecasting handle (used by the cloned overnight index) and
    /// the discounting handle to the bootstrapping curve - or, when an exogenous
    /// discounting curve was supplied, links the discounting handle to that
    /// instead - then records the curve on the base (`oisratehelper.cpp:198-210`).
    /// All links are non-owning and unobserved.
    fn set_term_structure(&self, term_structure: &Shared<dyn YieldTermStructure>) {
        self.term_structure_handle
            .link_to_weak(Shared::downgrade(term_structure));
        match &self.discount_handle {
            Some(discount) if !discount.is_empty() => {
                let curve = discount
                    .current_link()
                    .expect("a non-empty discount handle resolves");
                self.discount_relinkable_handle
                    .link_to_weak(Shared::downgrade(&curve));
            }
            _ => self
                .discount_relinkable_handle
                .link_to_weak(Shared::downgrade(term_structure)),
        }
        self.base.set_term_structure(term_structure);
    }
}

impl RelativeDateRateHelper for OISRateHelper {
    /// Rebuilds the OIS and its schedule off the current evaluation date
    /// (`initializeDates`, `oisratehelper.cpp:128-193`): a swap of the helper's
    /// tenor built through [`MakeOis`]' whole builder chain with a 0% fixed rate
    /// so it does not price at construction.
    ///
    /// The `latest_relevant_date` is `max(maturity, lastPaymentDate)`.  C++ also
    /// maxes in `fixingEndDate = overnightIndex.maturityDate(valueDate(
    /// lastFixingDate))` (`oisratehelper.cpp:170-172`); that term is dominated by
    /// `lastPaymentDate` whenever the payment lag is at least one business day
    /// (the bootstrap oracle uses lag 2), and reaching the last coupon's fixing
    /// date needs a typed accessor the `dyn CashFlow` leg does not expose, so it
    /// is deferred with the arithmetic-averaging leg.
    fn initialize_dates(&self) {
        let swap = MakeOis::new(
            self.tenor,
            Shared::clone(&self.overnight_index),
            Some(0.0),
            self.forward_start,
            Shared::clone(&self.settings),
        )
        .with_discounting_term_structure(self.discount_relinkable_handle.handle())
        .with_telescopic_value_dates(false)
        .with_payment_lag(self.payment_lag)
        .with_payment_adjustment(self.payment_convention)
        .with_payment_frequency(self.payment_frequency)
        .with_averaging_method(self.averaging_method)
        .with_lookback_days(None)
        .with_lockout_days(0)
        .with_rule(DateGeneration::Backward)
        .with_convention(BusinessDayConvention::ModifiedFollowing)
        .with_termination_date_convention(BusinessDayConvention::ModifiedFollowing)
        .with_observation_shift(false)
        .with_settlement_days(self.settlement_days)
        .build()
        .expect("a 0% fixed-rate OIS with benign deferred knobs builds without pricing");

        let base_swap = swap.fixed_vs_floating();
        let earliest = swap
            .overnight_schedule()
            .start_date()
            .min(base_swap.fixed_schedule().start_date());
        let maturity = swap
            .overnight_schedule()
            .end_date()
            .max(base_swap.fixed_schedule().end_date());

        let last_overnight_payment = swap.overnight_leg().last().map_or(maturity, |cf| cf.date());
        let last_fixed_payment = base_swap
            .fixed_leg()
            .last()
            .map_or(maturity, |cf| cf.date());
        let latest_relevant = maturity.max(last_overnight_payment).max(last_fixed_payment);

        self.base.set_earliest_date(earliest);
        self.base.set_maturity_date(maturity);
        self.base.set_latest_relevant_date(latest_relevant);
        self.base.set_latest_date(latest_relevant);
        let pillar = match self.pillar {
            Pillar::MaturityDate => maturity,
            Pillar::LastRelevantDate => latest_relevant,
        };
        self.base.set_pillar_date(pillar);

        *self.swap.borrow_mut() = Some(swap);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::interestrate::Compounding;
    use crate::settings::Settings;
    use crate::termstructures::yields::FlatForward;
    use crate::test_support::{Flag, as_observer};
    use crate::time::calendars::target::Target;
    use crate::time::date::{Date, Month};
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::frequency::Frequency;
    use crate::time::period::Period;
    use crate::time::timeunit::TimeUnit;
    use crate::{currency::Currency, types::Rate};

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

    fn euribor(
        tenor: Period,
        forwarding: Handle<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> IborIndex {
        IborIndex::new(
            "Euribor".into(),
            tenor,
            2,
            Currency::eur(),
            Target::new(),
            BusinessDayConvention::Following,
            false,
            Actual360::new(),
            forwarding,
            settings,
        )
    }

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

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

    /// Standalone oracle: off a flat continuously-compounded curve the implied
    /// deposit rate is the closed-form simple forward `(exp(r*t) - 1)/t` over
    /// the helper's value-to-maturity window, and equals the index fixing path.
    #[test]
    fn implied_quote_matches_closed_form_deposit_rate() {
        let settings = settings_on(today());
        let source = euribor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);
        let helper = DepositRateHelper::from_rate(0.02, &source);

        let rate = 0.03;
        let curve = flat_curve(today(), rate);
        helper.set_term_structure(&curve);

        let d1 = helper.earliest_date();
        let d2 = helper.maturity_date();
        let t = Actual360::new().year_fraction(d1, d2);
        let implied = helper.implied_quote().unwrap();

        let closed_form = ((rate * t).exp() - 1.0) / t;
        assert!((implied - closed_form).abs() < 1e-12);
    }

    /// `initializeDates` derives earliest/maturity/pillar from the index
    /// conventions off the evaluation date (`ratehelpers.cpp:228`).
    #[test]
    fn initialize_dates_follows_the_index_conventions() {
        let settings = settings_on(today());
        let source = euribor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);
        let helper = DepositRateHelper::from_rate(0.02, &source);

        let reference = source
            .fixing_calendar()
            .adjust(today(), BusinessDayConvention::Following);
        let earliest = source.value_date(reference).unwrap();
        let maturity = source.maturity_date(earliest).unwrap();

        assert_eq!(helper.earliest_date(), earliest);
        assert!(earliest > today(), "the value date is spot, past today");
        assert_eq!(helper.maturity_date(), maturity);
        assert_eq!(helper.pillar_date(), maturity);
        assert_eq!(helper.latest_relevant_date(), maturity);
    }

    /// The clone mechanism: the helper forecasts off its OWN handle (the curve
    /// it is bootstrapped against), leaving the source index - here on an empty
    /// handle - untouched.
    #[test]
    fn helper_prices_off_its_own_handle_not_the_source_index() {
        let settings = settings_on(today());
        let source = euribor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);
        let helper = DepositRateHelper::from_rate(0.02, &source);

        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);
        let implied_low = helper.implied_quote().unwrap();

        let curve_high = flat_curve(today(), 0.06);
        helper.set_term_structure(&curve_high);
        let implied_high = helper.implied_quote().unwrap();

        assert!(
            implied_high > implied_low,
            "relinking the helper's handle moves its implied quote"
        );
        assert!(
            source.forecast_fixing(helper.earliest_date()).is_err(),
            "the source index's own empty handle is untouched"
        );
    }

    /// `quote_error` is market minus implied.
    #[test]
    fn quote_error_is_market_minus_implied() {
        let settings = settings_on(today());
        let source = euribor(Period::new(6, TimeUnit::Months), Handle::empty(), settings);
        let helper = DepositRateHelper::from_rate(0.05, &source);

        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);

        let implied = helper.implied_quote().unwrap();
        assert!((helper.quote_error().unwrap() - (0.05 - implied)).abs() < 1e-15);
    }

    /// An evaluation-date change reruns `initializeDates` and notifies observers.
    #[test]
    fn evaluation_date_change_reinitializes_dates() {
        let settings = settings_on(today());
        let source = euribor(
            Period::new(6, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        let helper = DepositRateHelper::from_rate(0.02, &source);
        let before = helper.earliest_date();

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

        let moved = today() + 30;
        settings.set_evaluation_date(moved);

        assert!(Flag::is_up(&flag), "date change must notify observers");
        assert!(
            helper.earliest_date() > before,
            "date change must rerun initialize_dates"
        );
    }

    fn swap_setup() -> (Shared<Settings<Date>>, IborIndex) {
        let settings = settings_on(today());
        let source = euribor(
            Period::new(6, TimeUnit::Months),
            Handle::empty(),
            settings.clone(),
        );
        (settings, source)
    }

    /// Builds the same spot-starting swap the helper builds, directly on `curve`,
    /// for a cross-implementation identity: a separate [`MakeVanillaSwap`]
    /// instance priced by its own [`DiscountingSwapEngine`].
    fn independent_swap(
        source: &IborIndex,
        tenor: Period,
        calendar: Calendar,
        convention: BusinessDayConvention,
        curve: &Shared<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> VanillaSwap {
        let curve_handle = Handle::new(Shared::clone(curve));
        let index = shared(source.clone_with(curve_handle.clone()));
        MakeVanillaSwap::new(
            tenor,
            index,
            Some(0.0),
            Period::new(0, TimeUnit::Days),
            settings,
        )
        .with_discounting_term_structure(curve_handle)
        .with_fixed_leg_day_count(Actual360::new())
        .with_fixed_leg_tenor(Period::try_from(Frequency::Annual).unwrap())
        .with_fixed_leg_convention(convention)
        .with_fixed_leg_termination_date_convention(convention)
        .with_fixed_leg_calendar(calendar.clone())
        .with_fixed_leg_end_of_month(false)
        .with_floating_leg_calendar(calendar)
        .with_floating_leg_end_of_month(false)
        .build()
        .unwrap()
    }

    /// With no spread, the reconstructed `implied_quote` equals the fair rate of
    /// the same swap computed independently - the par-rate formula reduces to the
    /// fair rate exactly.
    #[test]
    fn implied_quote_matches_fair_rate_of_the_same_swap() {
        let (settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let calendar = Target::new();
        let convention = BusinessDayConvention::ModifiedFollowing;
        let helper = SwapRateHelper::from_rate(
            0.02,
            tenor,
            calendar.clone(),
            Frequency::Annual,
            convention,
            Actual360::new(),
            &source,
        );
        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);

        let implied = helper.implied_quote().unwrap();
        let mut independent =
            independent_swap(&source, tenor, calendar, convention, &curve, settings);
        let fair = independent.fixed_vs_floating_mut().fair_rate().unwrap();
        assert!(
            (implied - fair).abs() < 1e-12,
            "implied {implied} vs fair {fair}"
        );
    }

    /// A nonzero spread shifts the implied quote off the fair rate by exactly
    /// `spread * floatingLegBPS / fixedLegBPS` (BPS from an independent swap) -
    /// the term a bare `fair_rate()` would drop.
    #[test]
    fn nonzero_spread_shifts_the_implied_quote_by_the_bps_ratio() {
        let (settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let calendar = Target::new();
        let convention = BusinessDayConvention::ModifiedFollowing;
        let curve = flat_curve(today(), 0.03);

        let helper0 = SwapRateHelper::from_rate(
            0.02,
            tenor,
            calendar.clone(),
            Frequency::Annual,
            convention,
            Actual360::new(),
            &source,
        );
        helper0.set_term_structure(&curve);
        let implied0 = helper0.implied_quote().unwrap();

        let spread = 0.001;
        let spread_handle = Handle::new(shared(SimpleQuote::new(spread)) as Shared<dyn Quote>);
        let helper_s = SwapRateHelper::with_details(
            Handle::new(shared(SimpleQuote::new(0.02)) as Shared<dyn Quote>),
            tenor,
            calendar.clone(),
            Frequency::Annual,
            convention,
            Actual360::new(),
            &source,
            spread_handle,
            Period::new(0, TimeUnit::Days),
            None,
            Pillar::LastRelevantDate,
        );
        helper_s.set_term_structure(&curve);
        let implied_s = helper_s.implied_quote().unwrap();

        assert!(
            (implied_s - implied0).abs() > 1e-8,
            "the spread must move the implied quote"
        );

        let mut independent =
            independent_swap(&source, tenor, calendar, convention, &curve, settings);
        let floating_bps = independent
            .fixed_vs_floating_mut()
            .floating_leg_bps()
            .unwrap();
        let fixed_bps = independent.fixed_vs_floating_mut().fixed_leg_bps().unwrap();
        let expected = implied0 - spread * floating_bps / fixed_bps;
        assert!(
            (implied_s - expected).abs() < 1e-12,
            "implied_s {implied_s} vs expected {expected}"
        );
    }

    /// The forced recalculation: moving the curve (mutating its underlying quote,
    /// not relinking) changes the implied quote even though the helper never
    /// observes the curve and receives no notification - proving `implied_quote`
    /// forces a fresh calculation rather than reading a stale cache.
    #[test]
    fn moving_the_curve_updates_the_quote_without_notifying_the_helper() {
        let (_settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let helper = SwapRateHelper::from_rate(
            0.02,
            tenor,
            Target::new(),
            Frequency::Annual,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            &source,
        );

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

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

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

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

    /// `initialize_dates` builds a spot-starting swap and the pillar follows the
    /// [`Pillar`] choice.
    #[test]
    fn initialize_dates_spot_starts_and_pillar_follows_the_choice() {
        let (_settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let helper = SwapRateHelper::with_details(
            Handle::new(shared(SimpleQuote::new(0.02)) as Shared<dyn Quote>),
            tenor,
            Target::new(),
            Frequency::Annual,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            &source,
            Handle::empty(),
            Period::new(0, TimeUnit::Days),
            None,
            Pillar::MaturityDate,
        );
        assert!(
            helper.earliest_date() > today(),
            "the swap starts spot, past today"
        );
        assert!(helper.maturity_date() > helper.earliest_date());
        assert_eq!(
            helper.pillar_date(),
            helper.maturity_date(),
            "the MaturityDate pillar equals the maturity"
        );
    }

    /// `quote_error` is market minus implied.
    #[test]
    fn swap_quote_error_is_market_minus_implied() {
        let (_settings, source) = swap_setup();
        let tenor = Period::new(5, TimeUnit::Years);
        let helper = SwapRateHelper::from_rate(
            0.05,
            tenor,
            Target::new(),
            Frequency::Annual,
            BusinessDayConvention::ModifiedFollowing,
            Actual360::new(),
            &source,
        );
        let curve = flat_curve(today(), 0.03);
        helper.set_term_structure(&curve);

        let implied = helper.implied_quote().unwrap();
        assert!((helper.quote_error().unwrap() - (0.05 - implied)).abs() < 1e-15);
    }

    /// `overnightindexedswap.cpp estrSwapData` (`:92-125`): the OIS quotes the
    /// bootstrap oracle fits, `(tenor length, unit, rate %)`; all use two
    /// settlement days.
    const ESTR_SWAP_DATA: [(i32, TimeUnit, Real); 33] = [
        (1, TimeUnit::Weeks, 1.245),
        (2, TimeUnit::Weeks, 1.269),
        (3, TimeUnit::Weeks, 1.277),
        (1, TimeUnit::Months, 1.281),
        (2, TimeUnit::Months, 1.18),
        (3, TimeUnit::Months, 1.143),
        (4, TimeUnit::Months, 1.125),
        (5, TimeUnit::Months, 1.116),
        (6, TimeUnit::Months, 1.111),
        (7, TimeUnit::Months, 1.109),
        (8, TimeUnit::Months, 1.111),
        (9, TimeUnit::Months, 1.117),
        (10, TimeUnit::Months, 1.129),
        (11, TimeUnit::Months, 1.141),
        (12, TimeUnit::Months, 1.153),
        (15, TimeUnit::Months, 1.218),
        (18, TimeUnit::Months, 1.308),
        (21, TimeUnit::Months, 1.407),
        (2, TimeUnit::Years, 1.510),
        (3, TimeUnit::Years, 1.916),
        (4, TimeUnit::Years, 2.254),
        (5, TimeUnit::Years, 2.523),
        (6, TimeUnit::Years, 2.746),
        (7, TimeUnit::Years, 2.934),
        (8, TimeUnit::Years, 3.092),
        (9, TimeUnit::Years, 3.231),
        (10, TimeUnit::Years, 3.380),
        (11, TimeUnit::Years, 3.457),
        (12, TimeUnit::Years, 3.544),
        (15, TimeUnit::Years, 3.702),
        (20, TimeUnit::Years, 3.703),
        (25, TimeUnit::Years, 3.541),
        (30, TimeUnit::Years, 3.369),
    ];

    /// `overnightindexedswap.cpp testBaseBootstrap` (`:397` ->
    /// `testBootstrap(false, RateAveraging::Compound)`, `:208`): an Estr
    /// discounting curve bootstrapped purely from [`OISRateHelper`]s reprices
    /// every OIS quote to 1e-8.
    ///
    /// The deposit helpers of the C++ setup are omitted deliberately: for a zero
    /// spread `implied_quote == fair_rate`, and each swap tenor is self-pinned by
    /// its own OIS node solved so `implied_quote_i == quote_i`, so
    /// `fair_rate_i == quote_i` to solver accuracy independent of the sub-week
    /// short end the deposits shape. `paymentLag = 2` and `today = 5 Feb 2009`
    /// are transcribed from `CommonVars` / `testBootstrap` (`:180-215`).
    ///
    /// The three sibling cases stay deferred: `testBootstrapWithArithmeticAverage`
    /// (`:402`) needs the arithmetic-averaging pricer, and the two telescopic
    /// cases (`:407`/`:413`) need telescopic value dates - neither on main.
    #[test]
    fn ois_bootstrap_reprices_the_quotes() {
        use crate::indexes::ibor::Estr;
        use crate::math::interpolations::loglinear::LogLinear;
        use crate::termstructures::bootstraptraits::Discount;
        use crate::termstructures::yields::PiecewiseYieldCurve;
        use crate::time::daycounters::actual365fixed::Actual365Fixed;

        const PAYMENT_LAG: Integer = 2;
        let today = Date::new(5, Month::February, 2009);
        let settings = settings_on(today);
        let calendar = Target::new();
        let settlement = calendar.advance(
            today,
            2,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );

        let estr = Estr::new(Handle::empty(), settings.clone());
        let mut instruments: Vec<Shared<dyn RateHelper>> = Vec::new();
        for (n, unit, rate) in ESTR_SWAP_DATA {
            let quote = Handle::new(shared(SimpleQuote::new(rate / 100.0)) as Shared<dyn Quote>);
            let helper = OISRateHelper::new(
                2,
                Period::new(n, unit),
                quote,
                &estr,
                None,
                PAYMENT_LAG,
                BusinessDayConvention::Following,
                Frequency::Annual,
                Period::new(0, TimeUnit::Days),
                Handle::empty(),
                Pillar::LastRelevantDate,
                RateAveraging::Compound,
                settings.clone(),
            );
            instruments.push(helper as Shared<dyn RateHelper>);
        }

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

        for (n, unit, rate) in ESTR_SWAP_DATA {
            let priced_estr = shared(Estr::new(handle.clone(), settings.clone()));
            let mut swap = MakeOis::new(
                Period::new(n, unit),
                priced_estr,
                Some(0.0),
                Period::new(0, TimeUnit::Days),
                settings.clone(),
            )
            .with_effective_date(settlement)
            .with_nominal(100.0)
            .with_payment_lag(PAYMENT_LAG)
            .with_discounting_term_structure(handle.clone())
            .with_averaging_method(RateAveraging::Compound)
            .build()
            .unwrap();

            let calculated = swap.fixed_vs_floating_mut().fair_rate().unwrap();
            let expected = rate / 100.0;
            assert!(
                (calculated - expected).abs() < 1.0e-8,
                "{n} {unit:?} OIS: calculated {calculated} vs expected {expected}"
            );
        }
    }
}