libitofin 0.9.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
//! Bootstrap helpers for default-probability term structures.
//!
//! Port of the two typedefs at the head of
//! `ql/termstructures/credit/defaultprobabilityhelpers.hpp:41-44`:
//! `DefaultProbabilityHelper` is `BootstrapHelper<DefaultProbabilityTermStructure>`
//! and `RelativeDateDefaultProbabilityHelper` is
//! `RelativeDateBootstrapHelper<DefaultProbabilityTermStructure>`. They are the
//! credit twins of
//! [`RateHelper`](crate::termstructures::bootstraphelper::RateHelper) and
//! [`RelativeDateRateHelper`](crate::termstructures::bootstraphelper::RelativeDateRateHelper),
//! and they carry no behaviour of their own: everything is inherited from the
//! shared [`BootstrapHelperBase`], instantiated here over
//! [`DefaultProbabilityTermStructure`] instead of the yield curve.
//!
//! Where C++ gets both families from one class template, this port needs two
//! traits, because the yield layer is typed on the bare `dyn RateHelper` object
//! and a trait generic over its term structure cannot be made into one. The
//! shared driver reaches both through [`BootstrapHelperShared`], implemented
//! below on `dyn DefaultProbabilityHelper`.
//!
//! [`SpreadCdsHelper`] follows them: the running-spread CDS helper the credit
//! bootstrap is driven by. `UpfrontCdsHelper` (`defaultprobabilityhelpers.hpp:170`)
//! is not here yet and follows within EPIC Credit (#676).

use std::cell::{Cell, RefCell};
use std::rc::Weak;

use crate::errors::{QlError, QlResult};
use crate::handle::{Handle, RelinkableHandle};
use crate::instrument::Instrument;
use crate::instruments::{CdsTerms, CreditDefaultSwap, ProtectionSide};
use crate::patterns::observable::{AsObservable, Observable};
use crate::pricingengine::PricingEngine;
use crate::pricingengines::credit::MidPointCdsEngine;
use crate::quotes::Quote;
use crate::require;
use crate::settings::Settings;
use crate::shared::{Shared, SharedMut, shared_mut};
use crate::termstructures::bootstraphelper::{BootstrapHelperBase, BootstrapHelperShared};
use crate::termstructures::credit::defaulttermstructure::DefaultProbabilityTermStructure;
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::schedule::{MakeSchedule, Schedule};
use crate::types::{Integer, Real};

/// The shared state of a credit bootstrap helper: a
/// [`BootstrapHelperBase`] whose back-pointer is a default-probability curve.
pub type DefaultProbabilityHelperBase = BootstrapHelperBase<dyn DefaultProbabilityTermStructure>;

/// Bootstrap helper for the credit-curve bootstrap
/// (`DefaultProbabilityHelper`).
///
/// Mirrors [`RateHelper`](crate::termstructures::bootstraphelper::RateHelper)
/// exactly, over [`DefaultProbabilityTermStructure`]: a concrete helper embeds
/// a [`DefaultProbabilityHelperBase`], returns it from [`base`](Self::base) and
/// supplies [`implied_quote`](Self::implied_quote); the rest of the interface is
/// derived from the base. The same ownership contract holds - the curve is held
/// [`Weak`](std::rc::Weak) and never observed - since it is the one base that
/// enforces it.
pub trait DefaultProbabilityHelper: AsObservable {
    /// The embedded shared state.
    fn base(&self) -> &DefaultProbabilityHelperBase;

    /// The quote implied by the current curve, computed by the concrete helper.
    ///
    /// The helper does not observe the curve, so this must force any
    /// recalculation it needs itself rather than trusting a cached value.
    fn implied_quote(&self) -> QlResult<Real>;

    /// The market quote the helper fits the curve to.
    fn quote(&self) -> &Handle<dyn Quote> {
        self.base().quote()
    }

    /// The bootstrap's root: market quote minus implied quote, driven to zero.
    fn quote_error(&self) -> QlResult<Real> {
        Ok(self.base().quote_value()? - self.implied_quote()?)
    }

    /// Sets the curve being bootstrapped (non-owning, unobserved).
    ///
    /// A concrete helper that hands the curve to a pricing engine overrides
    /// this to relink that handle first, then delegates here.
    fn set_term_structure(&self, term_structure: &Shared<dyn DefaultProbabilityTermStructure>) {
        self.base().set_term_structure(term_structure);
    }

    /// The earliest date data are needed at.
    fn earliest_date(&self) -> Date {
        self.base().earliest_date()
    }

    /// The instrument's maturity date.
    fn maturity_date(&self) -> Date {
        self.base().maturity_date()
    }

    /// The latest date data are needed at.
    fn latest_relevant_date(&self) -> Date {
        self.base().latest_relevant_date()
    }

    /// The pillar date, at which the curve node this helper sets sits.
    fn pillar_date(&self) -> Date {
        self.base().pillar_date()
    }

    /// The latest date, equal to the pillar date.
    fn latest_date(&self) -> Date {
        self.base().latest_date()
    }
}

/// Credit bootstrap helper whose date schedule is relative to the evaluation
/// date (`RelativeDateDefaultProbabilityHelper`).
///
/// `CdsHelper` derives from this: a CDS schedule is rebuilt whenever the
/// evaluation date moves. The concrete helper builds its base with
/// [`BootstrapHelperBase::new_relative`], passing a closure that calls
/// [`initialize_dates`](Self::initialize_dates).
pub trait RelativeDateDefaultProbabilityHelper: DefaultProbabilityHelper {
    /// Rebuilds the helper's date schedule off the current evaluation date.
    fn initialize_dates(&self);
}

/// The credit half of the driver bound. Like the yield impl, every method
/// routes through the [`DefaultProbabilityHelper`] trait rather than straight
/// to the base, so a concrete helper's override still runs.
impl BootstrapHelperShared for dyn DefaultProbabilityHelper {
    type TS = dyn DefaultProbabilityTermStructure;

    fn set_term_structure(&self, term_structure: &Shared<dyn DefaultProbabilityTermStructure>) {
        DefaultProbabilityHelper::set_term_structure(self, term_structure);
    }

    fn quote_value(&self) -> QlResult<Real> {
        self.base().quote_value()
    }

    fn quote_error(&self) -> QlResult<Real> {
        DefaultProbabilityHelper::quote_error(self)
    }

    fn pillar_date(&self) -> Date {
        DefaultProbabilityHelper::pillar_date(self)
    }

    fn latest_relevant_date(&self) -> Date {
        DefaultProbabilityHelper::latest_relevant_date(self)
    }

    fn maturity_date(&self) -> Date {
        DefaultProbabilityHelper::maturity_date(self)
    }
}

/// The terms a [`SpreadCdsHelper`] defaults when they are not quoted.
///
/// One field per defaulted argument of the C++ `CdsHelper` constructor
/// (`defaultprobabilityhelpers.hpp:90-94`); [`Default`] carries their C++
/// values. The `model` argument has no field: only
/// [`Midpoint`](crate::pricingengines::credit::MidPointCdsEngine) is ported, the
/// ISDA arm of `resetEngine` (`defaultprobabilityhelpers.cpp:143-148`) staying
/// deferred within EPIC Credit (#676).
pub struct CdsHelperTerms {
    /// Whether the accrued coupon is due on a default.
    pub settles_accrual: bool,
    /// Whether a default pays at default time rather than at the end of the
    /// accrual period.
    pub pays_at_default_time: bool,
    /// An explicit schedule start, for an off-the-run contract; the protection
    /// start when absent.
    pub start_date: Option<Date>,
    /// The day counter the last coupon accrues with, overriding the spread's.
    pub last_period_day_counter: Option<DayCounter>,
    /// Whether the protection seller rebates the accrued current coupon.
    pub rebates_accrual: bool,
}

impl Default for CdsHelperTerms {
    fn default() -> CdsHelperTerms {
        CdsHelperTerms {
            settles_accrual: true,
            pays_at_default_time: true,
            start_date: None,
            last_period_day_counter: None,
            rebates_accrual: true,
        }
    }
}

/// A spread-quoted CDS as a credit bootstrap helper (`SpreadCdsHelper`,
/// `defaultprobabilityhelpers.hpp:128`).
///
/// The helper prices a par CDS on its own schedule against the curve being
/// bootstrapped and reports that contract's fair spread as
/// [`implied_quote`](DefaultProbabilityHelper::implied_quote); the bootstrap
/// drives `quoted spread - fair spread` to zero.
///
/// The C++ `CdsHelper` base (`defaultprobabilityhelpers.hpp:47-126`) has no
/// separate type here. It exists in C++ only to share state and
/// `initializeDates` with `UpfrontCdsHelper`, and that sibling is deferred
/// (#676), so its state and `initializeDates` live directly in this struct.
/// Porting `UpfrontCdsHelper` means factoring out the fields below plus
/// [`initialize_dates`](RelativeDateDefaultProbabilityHelper::initialize_dates)
/// and [`set_term_structure`](DefaultProbabilityHelper::set_term_structure),
/// leaving only `reset_engine` and `implied_quote` per subclass.
pub struct SpreadCdsHelper {
    base: DefaultProbabilityHelperBase,
    tenor: Period,
    settlement_days: Integer,
    calendar: Calendar,
    frequency: Frequency,
    payment_convention: BusinessDayConvention,
    rule: DateGeneration,
    day_counter: DayCounter,
    recovery_rate: Real,
    discount_curve: Handle<dyn YieldTermStructure>,
    settles_accrual: bool,
    pays_at_default_time: bool,
    start_date: Option<Date>,
    last_period_day_counter: Option<DayCounter>,
    rebates_accrual: bool,
    settings: Shared<Settings<Date>>,
    schedule: RefCell<Schedule>,
    protection_start: Cell<Date>,
    probability: RelinkableHandle<dyn DefaultProbabilityTermStructure>,
    swap: RefCell<QlResult<CreditDefaultSwap>>,
}

/// The state the helper is in before a curve has been handed to it: C++ leaves
/// `swap_` null there and would dereference it, where this reports the reason.
fn engine_not_reset() -> QlError {
    QlError::new(
        "the helper's credit default swap is built when the bootstrapping curve is set",
        file!(),
        line!(),
    )
}

impl SpreadCdsHelper {
    /// A helper on the C++ default terms (`defaultprobabilityhelpers.cpp:109`).
    ///
    /// The C++ quote is a `std::variant<Rate, Handle<Quote>>` (`hpp:129`); a
    /// quoted spread takes the `Rate` arm here as
    /// [`make_quote_handle(spread).handle()`](crate::quotes::make_quote_handle).
    ///
    /// # Errors
    ///
    /// As [`with_terms`](SpreadCdsHelper::with_terms).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        running_spread: Handle<dyn Quote>,
        tenor: Period,
        settlement_days: Integer,
        calendar: Calendar,
        frequency: Frequency,
        payment_convention: BusinessDayConvention,
        rule: DateGeneration,
        day_counter: DayCounter,
        recovery_rate: Real,
        discount_curve: Handle<dyn YieldTermStructure>,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Shared<SpreadCdsHelper>> {
        SpreadCdsHelper::with_terms(
            running_spread,
            tenor,
            settlement_days,
            calendar,
            frequency,
            payment_convention,
            rule,
            day_counter,
            recovery_rate,
            discount_curve,
            CdsHelperTerms::default(),
            settings,
        )
    }

    /// A helper on the given `terms` (`defaultprobabilityhelpers.cpp:40-58`).
    ///
    /// The helper observes its quote and its discount curve (the constructor's
    /// `registerWith(discountCurve)`, `cpp:57`) and tracks the evaluation date,
    /// rebuilding its schedule and its contract whenever that date moves.
    ///
    /// # Errors
    ///
    /// Rejects the three CDS date-generation rules. Their maturity comes from
    /// `cdsMaturity` (`cpp:87`), which is not ported, and taking the other arm
    /// for them would silently produce a schedule ending on the wrong date; that
    /// branch is deferred within EPIC Credit (#676).
    #[allow(clippy::too_many_arguments)]
    pub fn with_terms(
        running_spread: Handle<dyn Quote>,
        tenor: Period,
        settlement_days: Integer,
        calendar: Calendar,
        frequency: Frequency,
        payment_convention: BusinessDayConvention,
        rule: DateGeneration,
        day_counter: DayCounter,
        recovery_rate: Real,
        discount_curve: Handle<dyn YieldTermStructure>,
        terms: CdsHelperTerms,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Shared<SpreadCdsHelper>> {
        require!(
            !matches!(
                rule,
                DateGeneration::CDS | DateGeneration::CDS2015 | DateGeneration::OldCDS
            ),
            "the post-Big-Bang date-generation rules need cdsMaturity, which is not ported yet \
             (defaultprobabilityhelpers.cpp:85-88)"
        );
        Ok(Shared::new_cyclic(|weak: &Weak<SpreadCdsHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    helper.initialize_dates();
                    helper.reset_engine();
                }
            });
            let base = BootstrapHelperBase::new_relative(
                running_spread,
                Shared::clone(&settings),
                true,
                on_eval_change,
            );
            discount_curve.register_observer(&base.observer());
            let helper = SpreadCdsHelper {
                base,
                tenor,
                settlement_days,
                calendar,
                frequency,
                payment_convention,
                rule,
                day_counter,
                recovery_rate,
                discount_curve,
                settles_accrual: terms.settles_accrual,
                pays_at_default_time: terms.pays_at_default_time,
                start_date: terms.start_date,
                last_period_day_counter: terms.last_period_day_counter,
                rebates_accrual: terms.rebates_accrual,
                settings,
                schedule: RefCell::new(Schedule::from_dates(Vec::new())),
                protection_start: Cell::new(Date::null()),
                probability: RelinkableHandle::empty(),
                swap: RefCell::new(Err(engine_not_reset())),
            };
            helper.initialize_dates();
            helper
        }))
    }

    /// The date protection starts, `settlement_days` past the evaluation date
    /// (`cpp:79`).
    pub fn protection_start(&self) -> Date {
        self.protection_start.get()
    }

    /// Rebuilds the priced contract and its engine (`resetEngine`, `cpp:137-153`).
    ///
    /// Called from [`set_term_structure`](DefaultProbabilityHelper::set_term_structure)
    /// and, after [`initialize_dates`](RelativeDateDefaultProbabilityHelper::initialize_dates),
    /// on an evaluation-date move - the two C++ call sites (`cpp:67` and
    /// `cpp:72`). The order matters on the second: the contract is built from the
    /// schedule and protection start, so rebuilding it first would price the
    /// stale schedule.
    ///
    /// C++ calls this on *every* notification `update()` carries, where the
    /// evaluation-date guard sits inside `RelativeDateBootstrapHelper::update()`;
    /// this port has that guard in the base and hooks the rebuild to it. The
    /// unconditional arm rebuilds an identical contract - its notional and
    /// spread are the fixed `100.0` and `0.01`, never the quote - and a discount
    /// or curve move still reaches the contract through the engine it observes.
    ///
    /// A contract that cannot be built is stored as the error and surfaces at
    /// [`implied_quote`](DefaultProbabilityHelper::implied_quote), since the C++
    /// signature this mirrors returns nothing.
    fn reset_engine(&self) {
        *self.swap.borrow_mut() = self.build_swap();
    }

    /// The par contract the helper prices: a protection-buyer CDS on a notional
    /// of 100 paying a 1% running spread (`cpp:138-141`), under a fresh midpoint
    /// engine over the helper's own probability handle (`cpp:151-152`).
    ///
    /// C++ passes its `evaluationDate_` as the contract's trade date; this
    /// leaves the trade date to the contract, which deduces `protection start -
    /// 1` for a pre-Big-Bang rule (`creditdefaultswap.rs:365-371`). The two
    /// differ only when `settlement_days` is zero, and only in the accrual
    /// rebate and upfront payment, both zero-amount flows on a contract with no
    /// upfront: the deduced date keeps the helper clear of the rebate
    /// arithmetic deferred by #689, which the C++ date would enter with nothing
    /// to show for it.
    fn build_swap(&self) -> QlResult<CreditDefaultSwap> {
        let mut swap = CreditDefaultSwap::with_terms(
            ProtectionSide::Buyer,
            100.0,
            0.01,
            self.schedule.borrow().clone(),
            self.payment_convention,
            self.day_counter.clone(),
            CdsTerms {
                settles_accrual: self.settles_accrual,
                pays_at_default_time: self.pays_at_default_time,
                protection_start: Some(self.protection_start.get()),
                last_period_day_counter: self.last_period_day_counter.clone(),
                rebates_accrual: self.rebates_accrual,
                ..CdsTerms::default()
            },
            Shared::clone(&self.settings),
        )?;
        let engine = MidPointCdsEngine::new(
            self.probability.handle(),
            self.recovery_rate,
            self.discount_curve.clone(),
            None,
            Shared::clone(&self.settings),
        );
        swap.base_mut()
            .set_pricing_engine(shared_mut(engine) as SharedMut<dyn PricingEngine>);
        Ok(swap)
    }
}

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

impl DefaultProbabilityHelper for SpreadCdsHelper {
    fn base(&self) -> &DefaultProbabilityHelperBase {
        &self.base
    }

    /// The contract's fair spread (`impliedQuote`, `cpp:132-135`).
    ///
    /// The recalculation is forced rather than left to the cache: the helper
    /// weak-links the curve handle the engine prices over, so a node the
    /// bootstrap has just moved does not notify the contract, and a plain
    /// `fair_spread` would answer from the previous iteration's results.
    fn implied_quote(&self) -> QlResult<Real> {
        let mut swap = self.swap.borrow_mut();
        let swap = swap.as_mut().map_err(|error| error.clone())?;
        swap.recalculate()?;
        swap.fair_spread()
    }

    /// Records the curve, hands it to the engine, and rebuilds the contract
    /// (`setTermStructure`, `cpp:60-68`).
    ///
    /// The engine's handle is linked weakly, the port of the C++
    /// `linkTo(..., false)` at `cpp:63-65`: the curve owns this helper, which
    /// owns the contract, which owns the engine, and a strong link would close
    /// that ring.
    fn set_term_structure(&self, term_structure: &Shared<dyn DefaultProbabilityTermStructure>) {
        self.base.set_term_structure(term_structure);
        self.probability
            .link_to_weak(Shared::downgrade(term_structure));
        self.reset_engine();
    }
}

impl RelativeDateDefaultProbabilityHelper for SpreadCdsHelper {
    /// Rebuilds the schedule off the current evaluation date (`initializeDates`,
    /// `cpp:75-108`).
    ///
    /// Protection starts `settlement_days` past the evaluation date and, absent
    /// an explicit start, the schedule starts there too, rolled to a business
    /// day. The maturity is the tenor past that same reference date - the
    /// `cdsMaturity` arm above it (`cpp:86-88`) covers only the three CDS rules,
    /// which the constructor rejects; `TwentiethIMM` takes this arm.
    ///
    /// The earliest date is the schedule's first date and the latest its last,
    /// rolled. C++ then adds a day under the ISDA model (`cpp:105-106`); the
    /// midpoint model, the only one ported, does not.
    fn initialize_dates(&self) {
        let evaluation_date = self
            .base
            .evaluation_date()
            .expect("a relative-date helper always tracks an evaluation date");
        let protection_start = evaluation_date + self.settlement_days;
        self.protection_start.set(protection_start);

        let mut start_date = self.start_date.unwrap_or(protection_start);
        if self.rule != DateGeneration::CDS && self.rule != DateGeneration::CDS2015 {
            start_date = self.calendar.adjust(start_date, self.payment_convention);
        }
        let reference_date = match self.start_date {
            Some(date) => date + self.settlement_days,
            None => protection_start,
        };
        let end_date = reference_date + self.tenor;

        let schedule = MakeSchedule::new()
            .from(start_date)
            .to(end_date)
            .with_frequency(self.frequency)
            .with_calendar(self.calendar.clone())
            .with_convention(self.payment_convention)
            .with_termination_date_convention(BusinessDayConvention::Unadjusted)
            .with_rule(self.rule)
            .build();

        self.base.set_earliest_date(schedule.date(0));
        self.base.set_latest_date(
            self.calendar
                .adjust(schedule.date(schedule.len() - 1), self.payment_convention),
        );
        *self.schedule.borrow_mut() = schedule;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The credit family satisfies the bound the bootstrap driver puts on
    /// `PiecewiseCurve::Helper`, so a credit piecewise curve can name
    /// `dyn DefaultProbabilityHelper` there against a
    /// `dyn DefaultProbabilityTermStructure` curve. The two associated types
    /// must agree, which is the whole point of the generalization, and only a
    /// paired instantiation checks it. This is a compile-time assertion: the
    /// credit bootstrap itself ports no behaviour yet.
    #[test]
    fn credit_helpers_satisfy_the_driver_bound() {
        fn accepts_driver_helper<H>()
        where
            H: BootstrapHelperShared<TS = dyn DefaultProbabilityTermStructure> + ?Sized,
        {
        }
        accepts_driver_helper::<dyn DefaultProbabilityHelper>();
    }

    use crate::interestrate::Compounding;
    use crate::quotes::SimpleQuote;
    use crate::shared::shared;
    use crate::termstructures::credit::flathazardrate::FlatHazardRate;
    use crate::termstructures::yields::FlatForward;
    use crate::test_support::{Flag, as_observer};
    use crate::time::calendars::target::Target;
    use crate::time::date::Month;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::daycounters::actual365fixed::Actual365Fixed;
    use crate::time::timeunit::TimeUnit;

    /// A Monday, so the schedule's start is a business day and the roll the
    /// helper applies to it is visible as the identity it is.
    fn today() -> Date {
        Date::new(15, Month::June, 2026)
    }

    fn five_years() -> Period {
        Period::new(5, TimeUnit::Years)
    }

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

    fn discount(settlement: Date) -> Handle<dyn YieldTermStructure> {
        Handle::new(shared(FlatForward::with_rate(
            settlement,
            0.03,
            Actual365Fixed::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>)
    }

    /// A one-settlement-day helper on a five-year `TwentiethIMM` schedule, the
    /// pre-Big-Bang convention the ported date arm serves.
    fn helper(settings: &Shared<Settings<Date>>, terms: CdsHelperTerms) -> Shared<SpreadCdsHelper> {
        SpreadCdsHelper::with_terms(
            Handle::new(shared(SimpleQuote::new(0.01)) as Shared<dyn Quote>),
            five_years(),
            1,
            Target::new(),
            Frequency::Quarterly,
            BusinessDayConvention::Following,
            DateGeneration::TwentiethIMM,
            Actual360::new(),
            0.4,
            discount(today()),
            terms,
            Shared::clone(settings),
        )
        .unwrap()
    }

    /// The schedule `initialize_dates` is expected to have built, derived from
    /// the two dates the C++ arm computes rather than read back off the helper.
    fn expected_schedule(start_date: Date, end_date: Date) -> Schedule {
        MakeSchedule::new()
            .from(Target::new().adjust(start_date, BusinessDayConvention::Following))
            .to(end_date)
            .with_frequency(Frequency::Quarterly)
            .with_calendar(Target::new())
            .with_convention(BusinessDayConvention::Following)
            .with_termination_date_convention(BusinessDayConvention::Unadjusted)
            .with_rule(DateGeneration::TwentiethIMM)
            .build()
    }

    fn last_date(schedule: &Schedule) -> Date {
        schedule.date(schedule.len() - 1)
    }

    /// `initializeDates` (`defaultprobabilityhelpers.cpp:75-108`): protection
    /// starts `settlementDays` past the evaluation date, the schedule starts
    /// there rolled, and the maturity is the tenor past the protection start -
    /// the `cdsMaturity` arm (`cpp:86-88`) covers only the rejected CDS rules,
    /// so `TwentiethIMM` reaches this one.
    #[test]
    fn initialize_dates_spans_protection_start_to_the_tenor() {
        let settings = settings_at(today());
        let helper = helper(&settings, CdsHelperTerms::default());
        let calendar = Target::new();

        let protection_start = today() + 1;
        assert_eq!(helper.protection_start(), protection_start);

        let schedule = expected_schedule(protection_start, protection_start + five_years());
        assert_eq!(
            helper.earliest_date(),
            calendar.adjust(protection_start, BusinessDayConvention::Following)
        );
        assert_eq!(helper.earliest_date(), schedule.date(0));
        assert_eq!(
            helper.latest_date(),
            calendar.adjust(last_date(&schedule), BusinessDayConvention::Following)
        );
    }

    /// The latest date is the rolled last coupon date and nothing more: C++ adds
    /// a day only under the ISDA model (`cpp:105-106`), which is not ported.
    /// Pillar and latest-relevant date follow it, which is what the bootstrap
    /// driver orders the helpers on.
    #[test]
    fn the_node_sits_on_the_rolled_maturity() {
        let settings = settings_at(today());
        let helper = helper(&settings, CdsHelperTerms::default());

        let schedule = expected_schedule(today() + 1, today() + 1 + five_years());
        let rolled = Target::new().adjust(last_date(&schedule), BusinessDayConvention::Following);
        assert_eq!(helper.latest_date(), rolled);
        assert_eq!(helper.pillar_date(), rolled);
        assert_eq!(helper.latest_relevant_date(), rolled);
        assert_eq!(helper.maturity_date(), rolled);
    }

    /// An explicit start date replaces the protection start on both sides of the
    /// schedule, but the maturity is measured from `startDate + settlementDays`
    /// rather than from the start date itself (`cpp:90`) - the one place the two
    /// arms of that ternary differ by more than the branch they take.
    #[test]
    fn an_explicit_start_date_offsets_the_maturity_by_the_settlement_days() {
        let settings = settings_at(today());
        let start_date = Date::new(20, Month::March, 2026);
        let helper = helper(
            &settings,
            CdsHelperTerms {
                start_date: Some(start_date),
                ..CdsHelperTerms::default()
            },
        );

        let schedule = expected_schedule(start_date, start_date + 1 + five_years());
        assert_eq!(helper.earliest_date(), schedule.date(0));
        assert_eq!(
            helper.latest_date(),
            Target::new().adjust(last_date(&schedule), BusinessDayConvention::Following)
        );
        assert_eq!(helper.protection_start(), today() + 1);
    }

    /// The relative-date rebuild (`cpp:70-73`): a moved evaluation date reruns
    /// `initialize_dates` through the base's `new_relative` closure, so the whole
    /// schedule shifts with it.
    #[test]
    fn an_evaluation_date_move_rebuilds_the_schedule() {
        let settings = settings_at(today());
        let helper = helper(&settings, CdsHelperTerms::default());
        let (earliest, latest) = (helper.earliest_date(), helper.latest_date());

        let moved = Date::new(15, Month::December, 2026);
        settings.set_evaluation_date(moved);

        assert_eq!(helper.protection_start(), moved + 1);
        assert!(helper.earliest_date() > earliest);
        assert!(helper.latest_date() > latest);
        assert_eq!(
            helper.earliest_date(),
            Target::new().adjust(moved + 1, BusinessDayConvention::Following)
        );
    }

    /// The three CDS rules need `cdsMaturity`, which is not ported; taking the
    /// other arm for them would build a schedule ending on the wrong date, so
    /// they are refused rather than silently mispriced (#676).
    #[test]
    fn the_post_big_bang_rules_are_refused() {
        let settings = settings_at(today());
        for rule in [
            DateGeneration::CDS,
            DateGeneration::CDS2015,
            DateGeneration::OldCDS,
        ] {
            let result = SpreadCdsHelper::new(
                Handle::new(shared(SimpleQuote::new(0.01)) as Shared<dyn Quote>),
                five_years(),
                1,
                Target::new(),
                Frequency::Quarterly,
                BusinessDayConvention::Following,
                rule,
                Actual360::new(),
                0.4,
                discount(today()),
                Shared::clone(&settings),
            );
            assert!(
                result
                    .err()
                    .is_some_and(|error| { error.message().contains("cdsMaturity") })
            );
        }
    }

    /// `impliedQuote` (`cpp:132-135`) prices the helper's own contract against
    /// the curve it was handed, which `set_term_structure` weak-links into the
    /// engine and rebuilds the contract for (`cpp:60-68`).
    ///
    /// The forced recalculation is load-bearing, and this is what shows it: the
    /// weak link registers no observer on the curve
    /// ([`Link::link_weak`](crate::handle)), so moving the curve leaves the
    /// contract still flagged as calculated. A plain `fair_spread` would answer
    /// from that stale cache; the fresh number can only come from the
    /// `recalculate` this makes first. During the bootstrap it is the solver
    /// moving a curve node, which reaches the contract the same way: not at all.
    #[test]
    fn implied_quote_reprices_a_curve_it_does_not_observe() {
        let settings = settings_at(today());
        let helper = helper(&settings, CdsHelperTerms::default());

        let hazard = shared(SimpleQuote::new(0.02));
        let curve: Shared<dyn DefaultProbabilityTermStructure> = shared(FlatHazardRate::new(
            today(),
            Handle::new(Shared::clone(&hazard) as Shared<dyn Quote>),
            Actual365Fixed::new(),
        ));
        helper.set_term_structure(&curve);

        let first = helper.implied_quote().unwrap();
        assert!(first.is_finite() && first > 0.0);
        assert_eq!(helper.implied_quote().unwrap(), first);

        hazard.set_value(0.05);
        assert!(
            helper
                .swap
                .borrow()
                .as_ref()
                .unwrap()
                .base()
                .is_calculated(),
            "the weak link must leave the contract unnotified by the curve"
        );

        let second = helper.implied_quote().unwrap();
        assert!(
            second > first,
            "a higher hazard rate must widen the fair spread, not repeat {first}"
        );
    }

    /// The second `resetEngine` call site (`cpp:72`): the contract is rebuilt
    /// after the schedule is, so the helper prices the moved dates rather than
    /// the ones it was handed the curve on. Nothing else in the type system
    /// enforces that ordering, and a contract left behind still prices - just
    /// against the wrong schedule.
    #[test]
    fn an_evaluation_date_move_rebuilds_the_contract_too() {
        let settings = settings_at(today());
        let helper = helper(&settings, CdsHelperTerms::default());
        let curve: Shared<dyn DefaultProbabilityTermStructure> = shared(FlatHazardRate::with_rate(
            today(),
            0.02,
            Actual365Fixed::new(),
        ));
        helper.set_term_structure(&curve);
        helper.implied_quote().unwrap();

        let moved = Date::new(15, Month::December, 2026);
        settings.set_evaluation_date(moved);

        let schedule = expected_schedule(moved + 1, moved + 1 + five_years());
        let swap = helper.swap.borrow();
        let swap = swap.as_ref().unwrap();
        assert_eq!(swap.protection_start_date(), moved + 1);
        assert_eq!(swap.maturity(), last_date(&schedule));
    }

    /// `registerWith(discountCurve)` (`cpp:57`): the discount curve is the one
    /// input the helper prices against that it does observe - unlike the
    /// bootstrapping curve - so a move there re-broadcasts and reaches the curve
    /// being built. This is what makes it safe for the rebuild to hang off the
    /// evaluation date alone.
    #[test]
    fn a_discount_curve_move_notifies_the_helper() {
        let settings = settings_at(today());
        let rate = shared(SimpleQuote::new(0.03));
        let discount_curve = Handle::new(shared(FlatForward::new(
            today(),
            Handle::new(Shared::clone(&rate) as Shared<dyn Quote>),
            Actual365Fixed::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>);
        let helper = SpreadCdsHelper::new(
            Handle::new(shared(SimpleQuote::new(0.01)) as Shared<dyn Quote>),
            five_years(),
            1,
            Target::new(),
            Frequency::Quarterly,
            BusinessDayConvention::Following,
            DateGeneration::TwentiethIMM,
            Actual360::new(),
            0.4,
            discount_curve,
            Shared::clone(&settings),
        )
        .unwrap();

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

        rate.set_value(0.04);
        assert!(Flag::is_up(&flag));
    }

    /// Before a curve arrives there is no contract to price, where C++ would
    /// dereference its null `swap_`.
    #[test]
    fn implied_quote_without_a_curve_reports_the_missing_contract() {
        let settings = settings_at(today());
        let helper = helper(&settings, CdsHelperTerms::default());
        assert!(
            helper
                .implied_quote()
                .err()
                .is_some_and(|error| error.message().contains("bootstrapping curve is set"))
        );
    }
}