libitofin 0.14.0

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
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
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
//! 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`.
//!
//! [`CdsHelperBase`] follows them, with the two quoted contracts it serves:
//! [`SpreadCdsHelper`] and [`UpfrontCdsHelper`]. Only the mid-point model is
//! ported; the ISDA arm of `resetEngine`
//! (`defaultprobabilityhelpers.cpp:143-148`) rides the `IsdaCdsEngine` (#783).

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

use crate::errors::{QlError, QlResult};
use crate::handle::{Handle, RelinkableHandle};
use crate::instrument::Instrument;
use crate::instruments::{CdsTerms, CreditDefaultSwap, PricingModel, ProtectionSide, cds_maturity};
use crate::patterns::observable::{AsObservable, Observable};
use crate::pricingengine::PricingEngine;
use crate::pricingengines::credit::MidPointCdsEngine;
use crate::quotes::Quote;
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::time::timeunit::TimeUnit;
use crate::types::{Integer, Natural, Rate, Real};
use crate::{fail, require};

/// 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.
    ///
    /// Fallible where the yield family's is not: a CDS schedule's maturity
    /// comes from [`cds_maturity`], which rejects a tenor it cannot roll, and
    /// the bootstrap must carry that out rather than unwrap it (D4).
    ///
    /// # Errors
    ///
    /// As the concrete helper's date rule.
    fn initialize_dates(&self) -> QlResult<()>;
}

/// 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 CDS bootstrap helper defaults when they are not quoted.
///
/// One field per defaulted argument of the C++ `CdsHelper` constructor
/// (`defaultprobabilityhelpers.hpp:90-95`); [`Default`] carries their C++
/// values.
pub struct CdsHelperTerms {
    /// The model the helper prices its contract under.
    pub model: PricingModel,
    /// 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 {
            model: PricingModel::Midpoint,
            settles_accrual: true,
            pays_at_default_time: true,
            start_date: None,
            last_period_day_counter: None,
            rebates_accrual: true,
        }
    }
}

/// The state and dates every CDS bootstrap helper shares (`CdsHelper`,
/// `defaultprobabilityhelpers.hpp:48-128`).
///
/// C++ makes this an abstract class between the relative-date helper and the
/// two quoted contracts; here it is the state those contracts embed. A concrete
/// helper holds one, reports its [`base`](CdsHelperBase::base) as its own, and
/// supplies the two members C++ leaves virtual: the contract `reset_engine`
/// builds and [`implied_quote`](DefaultProbabilityHelper::implied_quote).
pub struct CdsHelperBase {
    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,
    model: PricingModel,
    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 CdsHelperBase {
    /// The C++ `CdsHelper` constructor (`defaultprobabilityhelpers.cpp:32-58`),
    /// less the `initializeDates` its callers run once the concrete helper
    /// exists to hold this.
    ///
    /// `on_eval_change` is the rebuild the base runs when the evaluation date
    /// moves; it reaches the concrete helper, since the contract it rebuilds is
    /// the subclass's to build.
    #[allow(clippy::too_many_arguments)]
    fn new(
        quote: 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>>,
        on_eval_change: Box<dyn Fn()>,
    ) -> CdsHelperBase {
        let base = BootstrapHelperBase::new_relative(
            quote,
            Shared::clone(&settings),
            true,
            on_eval_change,
        );
        discount_curve.register_observer(&base.observer());
        CdsHelperBase {
            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,
            model: terms.model,
            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())),
        }
    }

    /// The embedded bootstrap-helper state.
    pub fn base(&self) -> &DefaultProbabilityHelperBase {
        &self.base
    }

    /// The contract the helper prices (`swap()`, `hpp:98-100`), or the reason
    /// it could not be built.
    pub fn swap(&self) -> Ref<'_, QlResult<CreditDefaultSwap>> {
        self.swap.borrow()
    }

    /// The schedule the contract pays on (`schedule_`, `hpp:126`).
    pub fn schedule(&self) -> Ref<'_, Schedule> {
        self.schedule.borrow()
    }

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

    /// The evaluation date the schedule is measured from.
    fn evaluation_date(&self) -> Date {
        self.base
            .evaluation_date()
            .expect("a relative-date helper always tracks an evaluation date")
    }

    /// Stores the rebuilt contract, or the reason it could not be built.
    fn set_swap(&self, swap: QlResult<CreditDefaultSwap>) {
        *self.swap.borrow_mut() = swap;
    }

    /// Records the curve and hands it to the engine (`setTermStructure`,
    /// `cpp:60-68`), leaving the contract rebuild to the caller.
    ///
    /// 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));
    }

    /// The terms the priced contract inherits from the helper.
    ///
    /// The trade date is the evaluation date, as C++ passes it
    /// (`cpp:141` and `cpp:201`), rather than the contract's own deduction: it
    /// is what the accrual rebate accrues to, so leaving it to the contract
    /// would rebate a different amount than the quoted market convention.
    fn contract_terms(&self) -> CdsTerms {
        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,
            trade_date: Some(self.evaluation_date()),
            ..CdsTerms::default()
        }
    }

    /// Installs the model's engine over the helper's own probability handle
    /// (`resetEngine`'s switch, `cpp:143-153`).
    ///
    /// # Errors
    ///
    /// [`PricingModel::Isda`] needs the `IsdaCdsEngine` deferred to #783; the
    /// arm is refused rather than silently priced on the mid-point engine.
    fn install_engine(&self, swap: &mut CreditDefaultSwap) -> QlResult<()> {
        require!(
            self.model == PricingModel::Midpoint,
            "the ISDA arm of resetEngine (defaultprobabilityhelpers.cpp:143-148) needs the \
             IsdaCdsEngine, which is not ported yet (#783)"
        );
        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(())
    }

    /// 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 for every rule but the two post-Big-Bang ones. The maturity has two
    /// arms: the three CDS rules roll it off [`cds_maturity`] measured from the
    /// evaluation date (`cpp:86-88`), every other rule measures a tenor from the
    /// protection start (`cpp:90-92`) - a different reference date, not just a
    /// different roll.
    ///
    /// The earliest date is the schedule's first date and the latest its last,
    /// rolled, plus the day the ISDA model adds (`cpp:105-106`).
    ///
    /// # Errors
    ///
    /// If [`cds_maturity`] refuses the tenor, or rolls it to a contract that has
    /// already matured.
    fn initialize_dates(&self) -> QlResult<()> {
        let evaluation_date = self.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 end_date = if matches!(
            self.rule,
            DateGeneration::CDS2015 | DateGeneration::CDS | DateGeneration::OldCDS
        ) {
            let reference_date = self.start_date.unwrap_or(evaluation_date);
            match cds_maturity(reference_date, self.tenor, self.rule)? {
                Some(date) => date,
                None => fail!(
                    "the CDS2015 contract quoted at a zero tenor on {reference_date} has already \
                     matured (creditdefaultswap.cpp:494)"
                ),
            }
        } else {
            let reference_date = match self.start_date {
                Some(date) => date + self.settlement_days,
                None => protection_start,
            };
            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();

        let mut latest_date = self
            .calendar
            .adjust(schedule.date(schedule.len() - 1), self.payment_convention);
        if self.model == PricingModel::Isda {
            latest_date += 1;
        }
        self.base.set_earliest_date(schedule.date(0));
        self.base.set_latest_date(latest_date);
        *self.schedule.borrow_mut() = schedule;
        Ok(())
    }
}

/// A spread-quoted CDS as a credit bootstrap helper (`SpreadCdsHelper`,
/// `defaultprobabilityhelpers.hpp:129`).
///
/// 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.
pub struct SpreadCdsHelper {
    cds: CdsHelperBase,
}

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
    ///
    /// If the date rule cannot roll the tenor to a maturity
    /// ([`initialize_dates`](CdsHelperBase::initialize_dates)).
    #[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>> {
        let helper = Shared::new_cyclic(|weak: &Weak<SpreadCdsHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    match helper.cds.initialize_dates() {
                        Ok(()) => helper.reset_engine(),
                        Err(error) => helper.cds.set_swap(Err(error)),
                    }
                }
            });
            SpreadCdsHelper {
                cds: CdsHelperBase::new(
                    running_spread,
                    tenor,
                    settlement_days,
                    calendar,
                    frequency,
                    payment_convention,
                    rule,
                    day_counter,
                    recovery_rate,
                    discount_curve,
                    terms,
                    settings,
                    on_eval_change,
                ),
            }
        });
        helper.cds.initialize_dates()?;
        Ok(helper)
    }

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

    /// 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.cds.set_swap(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`).
    fn build_swap(&self) -> QlResult<CreditDefaultSwap> {
        let mut swap = CreditDefaultSwap::with_terms(
            ProtectionSide::Buyer,
            100.0,
            0.01,
            self.cds.schedule().clone(),
            self.cds.payment_convention,
            self.cds.day_counter.clone(),
            self.cds.contract_terms(),
            Shared::clone(&self.cds.settings),
        )?;
        self.cds.install_engine(&mut swap)?;
        Ok(swap)
    }
}

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

impl DefaultProbabilityHelper for SpreadCdsHelper {
    fn base(&self) -> &DefaultProbabilityHelperBase {
        self.cds.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.cds.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`).
    fn set_term_structure(&self, term_structure: &Shared<dyn DefaultProbabilityTermStructure>) {
        self.cds.set_term_structure(term_structure);
        self.reset_engine();
    }
}

impl RelativeDateDefaultProbabilityHelper for SpreadCdsHelper {
    fn initialize_dates(&self) -> QlResult<()> {
        self.cds.initialize_dates()
    }
}

/// An upfront-quoted CDS as a credit bootstrap helper (`UpfrontCdsHelper`,
/// `defaultprobabilityhelpers.hpp:158`).
///
/// The market quote is the upfront, paid on a cash-settlement date of its own
/// while the contract runs at a fixed `running_spread`; the bootstrap drives
/// `quoted upfront - fair upfront` to zero. The upfront must be quoted in
/// fractional units (`hpp:159`).
pub struct UpfrontCdsHelper {
    cds: CdsHelperBase,
    running_spread: Rate,
    upfront_settlement_days: Natural,
    upfront_date: Cell<Date>,
}

impl UpfrontCdsHelper {
    /// A helper on the C++ default terms and cash-settlement lag
    /// (`defaultprobabilityhelpers.hpp:171-177`).
    ///
    /// # Errors
    ///
    /// As [`with_terms`](UpfrontCdsHelper::with_terms).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        upfront: Handle<dyn Quote>,
        running_spread: Rate,
        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<UpfrontCdsHelper>> {
        UpfrontCdsHelper::with_terms(
            upfront,
            running_spread,
            tenor,
            settlement_days,
            calendar,
            frequency,
            payment_convention,
            rule,
            day_counter,
            recovery_rate,
            discount_curve,
            3,
            CdsHelperTerms::default(),
            settings,
        )
    }

    /// A helper settling its upfront `upfront_settlement_days` past the
    /// evaluation date, on the given `terms` (`defaultprobabilityhelpers.cpp:159-184`).
    ///
    /// # Errors
    ///
    /// If the date rule cannot roll the tenor to a maturity
    /// ([`initialize_dates`](CdsHelperBase::initialize_dates)).
    #[allow(clippy::too_many_arguments)]
    pub fn with_terms(
        upfront: Handle<dyn Quote>,
        running_spread: Rate,
        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>,
        upfront_settlement_days: Natural,
        terms: CdsHelperTerms,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Shared<UpfrontCdsHelper>> {
        let helper = Shared::new_cyclic(|weak: &Weak<UpfrontCdsHelper>| {
            let weak = weak.clone();
            let on_eval_change = Box::new(move || {
                if let Some(helper) = weak.upgrade() {
                    match helper.initialize_dates() {
                        Ok(()) => helper.reset_engine(),
                        Err(error) => helper.cds.set_swap(Err(error)),
                    }
                }
            });
            UpfrontCdsHelper {
                cds: CdsHelperBase::new(
                    upfront,
                    tenor,
                    settlement_days,
                    calendar,
                    frequency,
                    payment_convention,
                    rule,
                    day_counter,
                    recovery_rate,
                    discount_curve,
                    terms,
                    settings,
                    on_eval_change,
                ),
                running_spread,
                upfront_settlement_days,
                upfront_date: Cell::new(Date::null()),
            }
        });
        helper.initialize_dates()?;
        Ok(helper)
    }

    /// The date the upfront and the accrual rebate settle on (`upfrontDate`,
    /// `cpp:186-188`).
    pub fn upfront_date(&self) -> Date {
        self.upfront_date.get()
    }

    /// The fixed coupon the contract runs at, alongside the quoted upfront.
    pub fn running_spread(&self) -> Rate {
        self.running_spread
    }

    /// Rebuilds the priced contract and its engine (`resetEngine`,
    /// `cpp:195-217`).
    fn reset_engine(&self) {
        self.cds.set_swap(self.build_swap());
    }

    /// The contract the helper prices: the spread helper's par CDS with the
    /// quoted running spread and its own cash-settlement date (`cpp:196-201`).
    fn build_swap(&self) -> QlResult<CreditDefaultSwap> {
        let mut swap = CreditDefaultSwap::with_upfront_and_terms(
            ProtectionSide::Buyer,
            100.0,
            0.01,
            self.running_spread,
            self.cds.schedule().clone(),
            self.cds.payment_convention,
            self.cds.day_counter.clone(),
            CdsTerms {
                upfront_date: Some(self.upfront_date.get()),
                ..self.cds.contract_terms()
            },
            Shared::clone(&self.cds.settings),
        )?;
        self.cds.install_engine(&mut swap)?;
        Ok(swap)
    }

    /// The contract's fair upfront, off a forced recalculation for the reason
    /// [`SpreadCdsHelper`]'s is forced.
    fn fair_upfront(&self) -> QlResult<Real> {
        let mut swap = self.cds.swap.borrow_mut();
        let swap = swap.as_mut().map_err(|error| error.clone())?;
        swap.recalculate()?;
        swap.fair_upfront()
    }
}

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

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

    /// The contract's fair upfront, priced with today's cash flows included
    /// (`impliedQuote`, `cpp:219-224`).
    ///
    /// The flag matters because the quote is a cash-settled amount: dropping a
    /// flow that falls on the evaluation date would leave the bootstrap fitting
    /// a different contract than the one quoted. C++ forces it through the
    /// singleton and unwinds with `SavedSettings`; with the flag on a
    /// [`Settings`] the caller owns (D5), the unwind is explicit and runs on the
    /// error path too, so a contract that fails to price does not leave the
    /// caller's flag flipped.
    fn implied_quote(&self) -> QlResult<Real> {
        let restore = self.cds.settings.include_todays_cash_flows();
        self.cds.settings.set_include_todays_cash_flows(Some(true));
        let quote = self.fair_upfront();
        self.cds.settings.set_include_todays_cash_flows(restore);
        quote
    }

    /// Records the curve, hands it to the engine, and rebuilds the contract
    /// (`setTermStructure`, `cpp:60-68`).
    fn set_term_structure(&self, term_structure: &Shared<dyn DefaultProbabilityTermStructure>) {
        self.cds.set_term_structure(term_structure);
        self.reset_engine();
    }
}

impl RelativeDateDefaultProbabilityHelper for UpfrontCdsHelper {
    /// The base's dates, then the cash-settlement date they move
    /// (`initializeDates`, `cpp:190-193`).
    ///
    /// The override is what keeps the upfront date on the evaluation date it is
    /// measured from: the base rebuild alone would leave it at the date the
    /// helper was built on, and the contract would settle its upfront in the
    /// past without any of its other dates disagreeing.
    fn initialize_dates(&self) -> QlResult<()> {
        self.cds.initialize_dates()?;
        let upfront_date = self.cds.calendar.advance(
            self.cds.evaluation_date(),
            self.upfront_settlement_days as Integer,
            TimeUnit::Days,
            self.cds.payment_convention,
            false,
        );
        self.upfront_date.set(upfront_date);
        Ok(())
    }
}

#[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::event::Event;
    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 `cdsMaturity` arm of `initializeDates` (`cpp:85-88`): under the three
    /// post-Big-Bang rules the maturity is rolled off the *evaluation date*,
    /// where the other arm measures a tenor from the protection start, and the
    /// schedule runs from the previous IMM twentieth to it.
    ///
    /// Every date here is derived by hand from the rule - the twentieth of
    /// March, June, September or December at or before the trade date, plus the
    /// tenor, plus a quarter - rather than read back from [`cds_maturity`]. The
    /// helper calls that function itself, so an equality against it would hold
    /// for whatever maturity it returned. The round-trip bootstrap cannot stand
    /// in either: it rebuilds its contract on the same conventions, so a shared
    /// wrong schedule still reprices to the quote.
    #[test]
    fn the_cds_rules_roll_the_maturity_off_the_evaluation_date() {
        let settings = settings_at(today());
        let calendar = Target::new();
        let anchor = Date::new(20, Month::March, 2026);

        for (years, maturity) in [
            (2, Date::new(20, Month::June, 2028)),
            (3, Date::new(20, Month::June, 2029)),
            (5, Date::new(20, Month::June, 2031)),
            (7, Date::new(20, Month::June, 2033)),
        ] {
            let helper = SpreadCdsHelper::new(
                Handle::new(shared(SimpleQuote::new(0.01)) as Shared<dyn Quote>),
                Period::new(years, TimeUnit::Years),
                1,
                calendar.clone(),
                Frequency::Quarterly,
                BusinessDayConvention::Following,
                DateGeneration::CDS,
                Actual360::new(),
                0.4,
                discount(today()),
                Shared::clone(&settings),
            )
            .unwrap();

            let schedule = helper.cds.schedule();
            assert_eq!(schedule.date(0), anchor);
            assert_eq!(last_date(&schedule), maturity);
            assert_eq!(helper.earliest_date(), anchor);
            assert_eq!(
                helper.latest_date(),
                calendar.adjust(maturity, BusinessDayConvention::Following)
            );
            assert_eq!(helper.protection_start(), today() + 1);
        }
    }

    /// The date the CDS arm rolls *from* is the evaluation date (`cpp:87`), not
    /// the protection start the non-CDS arm measures from and the schedule
    /// starts on.
    ///
    /// The two are `settlement_days` apart, and on almost every date they roll
    /// back to the same twentieth - including the fixture above, where both
    /// land on 20 March 2026, so swapping one for the other there changes
    /// nothing. This evaluation date straddles a roll instead: 19 March rolls
    /// back to the previous December, while the protection start a day later is
    /// itself the March twentieth. The mis-wire that reads `protection_start`
    /// here therefore matures on 20 June 2031, a full quarter past the literal
    /// asserted below.
    #[test]
    fn the_cds_reference_date_is_the_evaluation_date_not_the_protection_start() {
        let evaluation_date = Date::new(19, Month::March, 2026);
        let calendar = Target::new();
        let helper = SpreadCdsHelper::new(
            Handle::new(shared(SimpleQuote::new(0.01)) as Shared<dyn Quote>),
            five_years(),
            1,
            calendar.clone(),
            Frequency::Quarterly,
            BusinessDayConvention::Following,
            DateGeneration::CDS,
            Actual360::new(),
            0.4,
            discount(evaluation_date),
            settings_at(evaluation_date),
        )
        .unwrap();

        let maturity = Date::new(20, Month::March, 2031);
        assert_eq!(helper.protection_start(), Date::new(20, Month::March, 2026));
        assert_eq!(last_date(&helper.cds.schedule()), maturity);
        assert_eq!(
            helper.latest_date(),
            calendar.adjust(maturity, BusinessDayConvention::Following)
        );
        assert_ne!(
            helper.latest_date(),
            Date::new(20, Month::June, 2031),
            "the maturity rolled off the protection start rather than the \
             evaluation date"
        );
    }

    /// `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.cds.swap().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.cds.swap();
        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));
    }

    /// The roll-off case `cdsMaturity` answers with a null date
    /// (`creditdefaultswap.cpp:494`): a `CDS2015` contract quoted at a zero
    /// tenor whose anchor is a June or December twentieth has already matured.
    ///
    /// C++ hands that null date to `MakeSchedule` and builds a schedule ending
    /// nowhere; the port refuses instead (D4), and this is the one input that
    /// reaches the refusal. The evaluation date is chosen to put the anchor on
    /// 20 June: `previous_twentieth` rolls any date from that day to the
    /// September twentieth back onto it.
    #[test]
    fn a_matured_zero_tenor_is_refused_rather_than_scheduled() {
        let settings = settings_at(Date::new(15, Month::July, 2026));
        let result = SpreadCdsHelper::new(
            Handle::new(shared(SimpleQuote::new(0.01)) as Shared<dyn Quote>),
            Period::new(0, TimeUnit::Months),
            1,
            Target::new(),
            Frequency::Quarterly,
            BusinessDayConvention::Following,
            DateGeneration::CDS2015,
            Actual360::new(),
            0.4,
            discount(today()),
            settings,
        );
        assert!(
            result
                .err()
                .is_some_and(|error| error.message().contains("has already matured"))
        );
    }

    /// The ISDA arm, ported as far as it goes: the pillar takes the extra day
    /// `initializeDates` adds under that model (`cpp:105-106`), and the engine
    /// it would price on is the deferral (`cpp:144-148`, #783).
    ///
    /// Both are inert on every other test here, which is the reason for this
    /// one: an omitted `++latestDate` and a silent fall back to the mid-point
    /// engine would each leave the whole suite green.
    #[test]
    fn the_isda_model_moves_the_pillar_and_defers_the_engine() {
        let settings = settings_at(today());
        let isda = helper(
            &settings,
            CdsHelperTerms {
                model: PricingModel::Isda,
                ..CdsHelperTerms::default()
            },
        );
        assert_eq!(
            isda.latest_date(),
            helper(&settings, CdsHelperTerms::default()).latest_date() + 1
        );

        isda.set_term_structure(&hazard_curve());
        assert!(
            isda.implied_quote()
                .err()
                .is_some_and(|error| error.message().contains("#783"))
        );
    }

    /// An upfront helper on a `lag`-day cash settlement, quoting a 1% upfront
    /// over a 5% running spread.
    fn upfront_helper(settings: &Shared<Settings<Date>>, lag: Natural) -> Shared<UpfrontCdsHelper> {
        UpfrontCdsHelper::with_terms(
            Handle::new(shared(SimpleQuote::new(0.01)) as Shared<dyn Quote>),
            0.05,
            five_years(),
            1,
            Target::new(),
            Frequency::Quarterly,
            BusinessDayConvention::Following,
            DateGeneration::CDS,
            Actual360::new(),
            0.4,
            discount(today()),
            lag,
            CdsHelperTerms::default(),
            Shared::clone(settings),
        )
        .unwrap()
    }

    fn hazard_curve() -> Shared<dyn DefaultProbabilityTermStructure> {
        shared(FlatHazardRate::with_rate(
            today(),
            0.02,
            Actual365Fixed::new(),
        ))
    }

    /// `upfrontDate` (`cpp:186-188`) and the contract it reaches (`cpp:199`):
    /// the upfront settles on the helper's own lag past the evaluation date.
    ///
    /// The lag here is five days rather than the C++ default of three, and that
    /// is the point: the contract deduces its own cash settlement three
    /// business days past the trade date (`creditdefaultswap.rs:502-509`), so a
    /// helper that never passed its `upfront_date` down would agree with one
    /// that did on every three-day fixture - including the bootstrap oracle.
    #[test]
    fn the_upfront_settles_on_the_helpers_own_lag() {
        let settings = settings_at(today());
        let helper = upfront_helper(&settings, 5);
        let calendar = Target::new();
        let expected = calendar.advance(
            today(),
            5,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );
        assert_ne!(
            expected,
            calendar.advance(
                today(),
                3,
                TimeUnit::Days,
                BusinessDayConvention::Following,
                false
            ),
            "the fixture's lag must differ from the contract's own default, or \
             this pins nothing"
        );
        assert_eq!(helper.upfront_date(), expected);

        helper.set_term_structure(&hazard_curve());
        let swap = helper.cds.swap();
        let swap = swap.as_ref().unwrap();
        assert_eq!(swap.upfront_payment().date(), expected);
        assert_eq!(swap.running_spread(), 0.05);
        assert_eq!(swap.trade_date(), today());
    }

    /// The `initializeDates` override (`cpp:190-193`): a moved evaluation date
    /// carries the upfront date with it, in the contract as well as the helper.
    ///
    /// Composition loses the C++ override for free - a rebuild routed at the
    /// shared base would leave the upfront settling on a date the contract has
    /// already passed, with every other date in agreement.
    #[test]
    fn an_evaluation_date_move_rebuilds_the_upfront_date() {
        let settings = settings_at(today());
        let helper = upfront_helper(&settings, 5);
        helper.set_term_structure(&hazard_curve());

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

        let expected = Target::new().advance(
            moved,
            5,
            TimeUnit::Days,
            BusinessDayConvention::Following,
            false,
        );
        assert_eq!(helper.upfront_date(), expected);
        assert_eq!(
            helper.cds.swap().as_ref().unwrap().upfront_payment().date(),
            expected
        );
    }

    /// `impliedQuote`'s `SavedSettings` (`cpp:220-221`) unwinds however the
    /// pricing ends. The bootstrap oracle only ever exercises the path that
    /// returns a quote; this is the other one, where a `?` between the write
    /// and its unwind would leave the caller's flag flipped.
    #[test]
    fn the_cash_flow_flag_is_restored_when_the_contract_cannot_price() {
        let settings = settings_at(today());
        settings.set_include_todays_cash_flows(Some(false));
        let helper = upfront_helper(&settings, 3);

        assert!(
            helper
                .implied_quote()
                .err()
                .is_some_and(|error| error.message().contains("bootstrapping curve is set"))
        );
        assert_eq!(settings.include_todays_cash_flows(), Some(false));
    }

    /// 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"))
        );
    }
}