libitofin 0.52.1

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
//! Discount-curve, yield and Z-spread bond analytics.
//!
//! Port of the `YieldTermStructure` and yield (IRR) subsets of
//! `ql/pricingengines/bond/bondfunctions.{hpp,cpp}`: the price, accrued, rate
//! and yield/duration/convexity/Z-spread wrappers that add a tradability guard and
//! delegate to the matching [`CashFlows`] overload (`bondfunctions.cpp:224-580`).
//! Each reads the bond's own cash flows and settings rather than a global
//! evaluation date (D5).
//!
//! Deviations, all by existing design decisions:
//! - `accruedAmount` is the port's [`Bond::accrued_amount`], which already
//!   carries the tradability guard and the `100 / notional` scaling
//!   (`bond.cpp` delegates the same call to `BondFunctions` in reverse); the
//!   wrapper here is the free-function surface over it.
//! - `atm_rate` preserves the own-NPV default. The additive
//!   [`BondFunctions::atm_rate_from_price`] accepts an explicit clean or dirty
//!   quote and scales it by the current settlement notional.

use crate::cashflows::{CashFlows, Duration};
use crate::errors::QlResult;
use crate::handle::Handle;
use crate::instruments::{Bond, BondPrice};
use crate::interestrate::{Compounding, InterestRate};
use crate::require;
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::time::date::Date;
use crate::time::daycounter::DayCounter;
use crate::time::frequency::Frequency;
use crate::types::{Rate, Real, Spread, Time};

/// Free-function bond analytics over a discount curve.
pub struct BondFunctions;

impl BondFunctions {
    /// Whether the bond can be traded at `settlement` (the settlement date when
    /// `None`): its notional has not yet been redeemed (`bondfunctions.cpp:39`).
    ///
    /// # Errors
    ///
    /// Propagates the settlement-date and notional lookups.
    pub fn is_tradable(bond: &Bond, settlement: Option<Date>) -> QlResult<bool> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        Ok(bond.notional(Some(settlement))? != 0.0)
    }

    /// The interest accrued at `settlement` (the settlement date when `None`),
    /// per 100 of notional (`bondfunctions.cpp:224`).
    ///
    /// # Errors
    ///
    /// Propagates the accrual lookup.
    pub fn accrued_amount(bond: &Bond, settlement: Option<Date>) -> QlResult<Real> {
        bond.accrued_amount(settlement)
    }

    /// The clean price per 100 of notional on `discount_curve`
    /// (`dirtyPrice - accruedAmount`, `bondfunctions.cpp:239`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn clean_price(
        bond: &Bond,
        discount_curve: &dyn YieldTermStructure,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let dirty = Self::dirty_price(bond, discount_curve, Some(settlement))?;
        let clean = dirty - bond.accrued_amount(Some(settlement))?;
        require!(clean.is_finite(), "clean price must be finite");
        Ok(clean)
    }

    /// The dirty price per 100 of notional on `discount_curve`
    /// (`CashFlows::npv * 100 / notional`, `bondfunctions.cpp:248`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn dirty_price(
        bond: &Bond,
        discount_curve: &dyn YieldTermStructure,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let notional = Self::require_tradable(bond, settlement)?;
        let npv = CashFlows::npv(
            bond.cashflows(),
            discount_curve,
            bond.settings(),
            Some(false),
            Some(settlement),
            None,
        )?;
        let dirty = (npv / notional) * 100.0;
        require!(dirty.is_finite(), "dirty price must be finite");
        Ok(dirty)
    }

    /// The basis-point value per 100 of notional on `discount_curve`
    /// (`CashFlows::bps * 100 / notional`, `bondfunctions.cpp:265`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn bps(
        bond: &Bond,
        discount_curve: &dyn YieldTermStructure,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let notional = Self::require_tradable(bond, settlement)?;
        let bps = CashFlows::bps(
            bond.cashflows(),
            discount_curve,
            bond.settings(),
            Some(false),
            Some(settlement),
            None,
        )?;
        Ok(bps * 100.0 / notional)
    }

    /// The at-the-money coupon rate that reprices the bond on `discount_curve`
    /// (`bondfunctions.cpp:280`, at the `price = {}` default).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date, and the leg must have
    /// some basis-point sensitivity.
    pub fn atm_rate(
        bond: &Bond,
        discount_curve: &dyn YieldTermStructure,
        settlement: Option<Date>,
    ) -> QlResult<Rate> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        Self::require_tradable(bond, settlement)?;
        CashFlows::atm_rate(
            bond.cashflows(),
            discount_curve,
            bond.settings(),
            Some(false),
            Some(settlement),
            Some(settlement),
            None,
        )
    }

    /// The coupon rate repricing an explicit clean or dirty quote per 100.
    ///
    /// Clean quotes include settlement accrued interest before scaling by the
    /// current notional. Settlement-date and ex-coupon flows are excluded, and
    /// the underlying ATM calculation still reads live coupon amounts.
    /// The existing [`Self::atm_rate`] keeps its own-NPV target unchanged.
    ///
    /// # Errors
    ///
    /// The bond must be tradable, the price and result finite, and the leg must
    /// have basis-point sensitivity unless the required coupon value is zero.
    pub fn atm_rate_from_price(
        bond: &Bond,
        discount_curve: &dyn YieldTermStructure,
        price: BondPrice,
        settlement: Option<Date>,
    ) -> QlResult<Rate> {
        require!(price.amount().is_finite(), "bond price must be finite");
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let notional = Self::require_tradable(bond, settlement)?;
        let dirty = price.amount()
            + if matches!(price, BondPrice::Clean(_)) {
                bond.accrued_amount(Some(settlement))?
            } else {
                0.0
            };
        let target = dirty / 100.0 * notional;
        require!(target.is_finite(), "target NPV must be finite");
        let rate = CashFlows::atm_rate(
            bond.cashflows(),
            discount_curve,
            bond.settings(),
            Some(false),
            Some(settlement),
            Some(settlement),
            Some(target),
        )?;
        require!(rate.is_finite(), "ATM rate must be finite");
        Ok(rate)
    }

    /// The yield (internal rate of return) that reprices the bond at `price`,
    /// solved off its own cash flows (`bondfunctions.hpp:167`).
    ///
    /// `settlement` defaults to the bond's settlement date, `accuracy` to
    /// `1e-10`, `max_evaluations` to `100` and `guess` to `0.05`. As C++, a
    /// clean price is grossed up by the accrued amount and the quote is scaled
    /// from per-100 to the bond's notional before the solve.
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date, and the solve must
    /// converge (as [`CashFlows::solve_yield`]).
    #[allow(clippy::too_many_arguments)]
    pub fn yield_rate(
        bond: &Bond,
        price: BondPrice,
        day_counter: DayCounter,
        compounding: Compounding,
        frequency: Frequency,
        settlement: Option<Date>,
        accuracy: Option<Real>,
        max_evaluations: Option<usize>,
        guess: Option<Rate>,
    ) -> QlResult<Rate> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let notional = Self::require_tradable(bond, settlement)?;
        let mut amount = price.amount();
        if matches!(price, BondPrice::Clean(_)) {
            amount += bond.accrued_amount(Some(settlement))?;
        }
        amount *= notional / 100.0;
        CashFlows::solve_yield(
            bond.cashflows(),
            amount,
            day_counter,
            compounding,
            frequency,
            bond.settings(),
            Some(false),
            Some(settlement),
            Some(settlement),
            accuracy,
            max_evaluations,
            guess,
        )
    }

    /// The bond's [`Duration`] under a flat `yield_rate` (`bondfunctions.cpp:389`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn duration(
        bond: &Bond,
        yield_rate: &InterestRate,
        duration_type: Duration,
        settlement: Option<Date>,
    ) -> QlResult<Time> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        Self::require_tradable(bond, settlement)?;
        CashFlows::duration(
            bond.cashflows(),
            yield_rate,
            duration_type,
            bond.settings(),
            Some(false),
            Some(settlement),
            None,
        )
    }

    /// The bond's convexity under a flat `yield_rate` (`bondfunctions.cpp:416`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn convexity(
        bond: &Bond,
        yield_rate: &InterestRate,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        Self::require_tradable(bond, settlement)?;
        CashFlows::convexity(
            bond.cashflows(),
            yield_rate,
            bond.settings(),
            Some(false),
            Some(settlement),
            None,
        )
    }

    /// The bond's basis-point value under a flat `yield_rate`, in the leg's own
    /// currency (unscaled, as C++, `bondfunctions.cpp:440`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn basis_point_value(
        bond: &Bond,
        yield_rate: &InterestRate,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        Self::require_tradable(bond, settlement)?;
        CashFlows::basis_point_value(
            bond.cashflows(),
            yield_rate,
            bond.settings(),
            Some(false),
            Some(settlement),
            None,
        )
    }

    /// The yield move a one-cent change in the bond's value implies, under a
    /// flat `yield_rate` (unscaled, as C++, `bondfunctions.cpp:464`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn yield_value_basis_point(
        bond: &Bond,
        yield_rate: &InterestRate,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        Self::require_tradable(bond, settlement)?;
        CashFlows::yield_value_basis_point(
            bond.cashflows(),
            yield_rate,
            bond.settings(),
            Some(false),
            Some(settlement),
            None,
        )
    }

    /// The basis-point value per 100 of notional under a flat `yield_rate`
    /// (`CashFlows::bps * 100 / notional`, `bondfunctions.cpp:348`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn bps_at_yield(
        bond: &Bond,
        yield_rate: &InterestRate,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let notional = Self::require_tradable(bond, settlement)?;
        let bps = CashFlows::bps_at_yield(
            bond.cashflows(),
            yield_rate,
            bond.settings(),
            Some(false),
            Some(settlement),
            None,
        )?;
        Ok(bps * 100.0 / notional)
    }

    /// The dirty price per 100 of notional under a flat `yield_rate`
    /// (`CashFlows::npv * 100 / notional`, `bondfunctions.cpp:310`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn dirty_price_at_yield(
        bond: &Bond,
        yield_rate: &InterestRate,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let notional = Self::require_tradable(bond, settlement)?;
        require!(yield_rate.rate().is_finite(), "yield rate must be finite");
        let npv = CashFlows::npv_at_yield(
            bond.cashflows(),
            yield_rate,
            bond.settings(),
            Some(false),
            Some(settlement),
            None,
        )?;
        require!(npv.is_finite(), "yield NPV must be finite");
        let dirty = (npv / notional) * 100.0;
        require!(dirty.is_finite(), "dirty price must be finite");
        Ok(dirty)
    }

    /// The clean price per 100 of notional under a flat `yield_rate`
    /// (`dirtyPrice - accruedAmount`, `bondfunctions.cpp:296`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date.
    pub fn clean_price_at_yield(
        bond: &Bond,
        yield_rate: &InterestRate,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let dirty = Self::dirty_price_at_yield(bond, yield_rate, Some(settlement))?;
        let clean = dirty - bond.accrued_amount(Some(settlement))?;
        require!(clean.is_finite(), "clean price must be finite");
        Ok(clean)
    }

    /// Dirty price from a bare yield and its conventions
    /// (`bondfunctions.cpp:320`).
    ///
    /// # Errors
    ///
    /// Propagates [`InterestRate::new`] and [`dirty_price_at_yield`](Self::dirty_price_at_yield).
    #[allow(clippy::too_many_arguments)]
    pub fn dirty_price_from_yield(
        bond: &Bond,
        yield_rate: Rate,
        day_counter: DayCounter,
        compounding: Compounding,
        frequency: Frequency,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let y = InterestRate::new(yield_rate, day_counter, compounding, frequency)?;
        Self::dirty_price_at_yield(bond, &y, settlement)
    }

    /// Clean price from a bare yield and its conventions
    /// (`bondfunctions.cpp:302`).
    ///
    /// # Errors
    ///
    /// Propagates [`InterestRate::new`] and [`clean_price_at_yield`](Self::clean_price_at_yield).
    #[allow(clippy::too_many_arguments)]
    pub fn clean_price_from_yield(
        bond: &Bond,
        yield_rate: Rate,
        day_counter: DayCounter,
        compounding: Compounding,
        frequency: Frequency,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let y = InterestRate::new(yield_rate, day_counter, compounding, frequency)?;
        Self::clean_price_at_yield(bond, &y, settlement)
    }

    /// The dirty price per 100 of notional on `discount_curve` shifted by a
    /// parallel zero-rate `z_spread` (`bondfunctions.cpp:507`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable, the spread and result finite, and the
    /// spreaded discount curve must accept the requested dates/conventions.
    pub fn dirty_price_at_z_spread(
        bond: &Bond,
        discount_curve: Handle<dyn YieldTermStructure>,
        z_spread: Spread,
        compounding: Compounding,
        frequency: Frequency,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let notional = Self::require_tradable(bond, settlement)?;
        require!(z_spread.is_finite(), "z-spread must be finite");
        let npv = CashFlows::npv_at_z_spread(
            bond.cashflows(),
            discount_curve,
            z_spread,
            compounding,
            frequency,
            bond.settings(),
            Some(false),
            Some(settlement),
            None,
        )?;
        let dirty = (npv / notional) * 100.0;
        require!(dirty.is_finite(), "dirty price must be finite");
        Ok(dirty)
    }

    /// The clean price per 100 of notional on `discount_curve` shifted by a
    /// parallel zero-rate `z_spread` (`bondfunctions.cpp:492`).
    ///
    /// # Errors
    ///
    /// The bond must be tradable, the spread and result finite, and the
    /// spreaded discount curve must accept the requested dates/conventions.
    pub fn clean_price_at_z_spread(
        bond: &Bond,
        discount_curve: Handle<dyn YieldTermStructure>,
        z_spread: Spread,
        compounding: Compounding,
        frequency: Frequency,
        settlement: Option<Date>,
    ) -> QlResult<Real> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let dirty = Self::dirty_price_at_z_spread(
            bond,
            discount_curve,
            z_spread,
            compounding,
            frequency,
            Some(settlement),
        )?;
        let clean = dirty - bond.accrued_amount(Some(settlement))?;
        require!(clean.is_finite(), "clean price must be finite");
        Ok(clean)
    }

    /// The zero-rate spread that reprices the bond at `price` on
    /// `discount_curve` (`bondfunctions.cpp:534`).
    ///
    /// `accuracy` defaults to `1e-10`, `max_evaluations` to `100` and `guess`
    /// to `0.0`.
    ///
    /// # Errors
    ///
    /// The bond must be tradable at the settlement date, and the solve must
    /// converge. Non-finite prices/guesses, non-positive or non-finite accuracy,
    /// zero evaluation limits, and non-finite scaled targets are rejected.
    #[allow(clippy::too_many_arguments)]
    pub fn z_spread(
        bond: &Bond,
        price: BondPrice,
        discount_curve: Handle<dyn YieldTermStructure>,
        compounding: Compounding,
        frequency: Frequency,
        settlement: Option<Date>,
        accuracy: Option<Real>,
        max_evaluations: Option<usize>,
        guess: Option<Rate>,
    ) -> QlResult<Spread> {
        let settlement = Self::settlement_or_eval(bond, settlement)?;
        let notional = Self::require_tradable(bond, settlement)?;
        require!(price.amount().is_finite(), "bond price must be finite");
        let accuracy = accuracy.unwrap_or(1.0e-10);
        require!(
            accuracy.is_finite() && accuracy > 0.0,
            "accuracy must be finite and positive"
        );
        let max_evaluations = max_evaluations.unwrap_or(100);
        require!(max_evaluations > 0, "maximum evaluations must be positive");
        let guess = guess.unwrap_or(0.0);
        require!(guess.is_finite(), "z-spread guess must be finite");
        let mut dirty = price.amount();
        if matches!(price, BondPrice::Clean(_)) {
            dirty += bond.accrued_amount(Some(settlement))?;
        }
        require!(dirty.is_finite(), "dirty price must be finite");
        let npv = (dirty / 100.0) * notional;
        require!(npv.is_finite(), "target NPV must be finite");
        CashFlows::z_spread(
            bond.cashflows(),
            npv,
            discount_curve,
            compounding,
            frequency,
            bond.settings(),
            Some(false),
            Some(settlement),
            Some(settlement),
            Some(accuracy),
            Some(max_evaluations),
            Some(guess),
        )
    }

    fn settlement_or_eval(bond: &Bond, settlement: Option<Date>) -> QlResult<Date> {
        match settlement {
            Some(date) => Ok(date),
            None => bond.settlement_date(None),
        }
    }

    fn require_tradable(bond: &Bond, settlement: Date) -> QlResult<Real> {
        let notional = bond.notional(Some(settlement))?;
        require!(notional.is_finite(), "bond notional must be finite");
        require!(
            notional != 0.0,
            "non tradable at {settlement} settlement date (maturity being {})",
            bond.maturity_date()?
        );
        Ok(notional)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cashflows::FixedRateLeg;
    use crate::instruments::Bond;
    use crate::interestrate::Compounding;
    use crate::settings::Settings;
    use crate::shared::{Shared, shared};
    use crate::termstructures::yields::FlatForward;
    use crate::time::businessdayconvention::BusinessDayConvention;
    use crate::time::calendar::Calendar;
    use crate::time::calendars::unitedstates::{self, UnitedStates};
    use crate::time::date::Month;
    use crate::time::dategenerationrule::DateGeneration;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::daycounters::actualactual::{ActualActual, Convention};
    use crate::time::frequency::Frequency;
    use crate::time::period::Period;
    use crate::time::schedule::Schedule;
    use crate::time::timeunit::TimeUnit;
    use crate::types::Rate;

    fn today() -> Date {
        Date::new(22, Month::November, 2004)
    }

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

    fn us_gov() -> Calendar {
        UnitedStates::new(unitedstates::Market::GovernmentBond)
    }

    /// `bonds.cpp::testCachedFixed`'s `flatRate(today, 0.03, Actual360())`,
    /// whose default compounding is continuous and annual.
    fn discount_curve() -> FlatForward {
        FlatForward::with_rate(
            today(),
            0.03,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )
    }

    /// The `FixedRateBond` of `bonds.cpp::testCachedFixed`: a semiannual
    /// schedule-driven `ActualActual(ISMA)` leg, 30 Nov 2004 to 30 Nov 2008,
    /// on the US government-bond calendar with a modified-following payment
    /// convention, then the par redemption `Bond::from_coupons` appends.
    fn bond_with_coupons(rates: Vec<Rate>) -> Bond {
        let unadjusted = BusinessDayConvention::Unadjusted;
        let schedule = Schedule::new(
            Date::new(30, Month::November, 2004),
            Date::new(30, Month::November, 2008),
            Period::new(6, TimeUnit::Months),
            us_gov(),
            unadjusted,
            unadjusted,
            DateGeneration::Backward,
            false,
            Date::null(),
            Date::null(),
        );
        let day_counter = ActualActual::with_schedule(Convention::ISMA, schedule.clone());
        let leg = FixedRateLeg::new(schedule)
            .with_notional(100.0)
            .with_coupon_rates(rates, day_counter, Compounding::Simple, Frequency::Annual)
            .unwrap()
            .with_payment_calendar(us_gov())
            .with_payment_adjustment(BusinessDayConvention::ModifiedFollowing)
            .build()
            .unwrap();
        Bond::from_coupons(
            1,
            us_gov(),
            Some(Date::new(30, Month::November, 2004)),
            leg,
            settings(),
        )
        .unwrap()
    }

    fn plain_bond() -> Bond {
        bond_with_coupons(vec![0.02875])
    }

    /// The plain bond's clean price reproduces the cached `bonds.cpp` value
    /// (`:867`, 99.298100 at 1e-6), oracling `CashFlows::npv` through the
    /// discount-curve `dirtyPrice`. Settlement is the 30 Nov 2004 dated date, so
    /// the accrued interest is zero and the clean and dirty prices agree.
    #[test]
    fn the_plain_bond_reproduces_its_cached_clean_price() {
        let bond = plain_bond();
        let curve = discount_curve();
        let clean = BondFunctions::clean_price(&bond, &curve, None).unwrap();
        let dirty = BondFunctions::dirty_price(&bond, &curve, None).unwrap();
        assert!((clean - 99.298100).abs() < 1e-6, "clean price {clean}");
        assert!((dirty - 99.298100).abs() < 1e-6, "dirty price {dirty}");
    }

    /// The varying-coupon bond's clean price reproduces the second cached
    /// `bonds.cpp` value (`:892`, 100.334149 at 1e-6), exercising the
    /// multiple-rate leg through the same discount-curve wrapper.
    #[test]
    fn the_varying_coupon_bond_reproduces_its_cached_clean_price() {
        let bond = bond_with_coupons(vec![0.02875, 0.03, 0.03125, 0.0325]);
        let curve = discount_curve();
        let clean = BondFunctions::clean_price(&bond, &curve, None).unwrap();
        assert!((clean - 100.334149).abs() < 1e-6, "clean price {clean}");
    }

    /// A single-rate bond's at-the-money rate is its coupon, and the
    /// default-price `atmRate` recovers it regardless of the discount curve:
    /// the target NPV is the leg's own, so the numerator and denominator
    /// discount factors cancel and the rate is `coupon-leg PV / bps = coupon`
    /// for any curve. This is a coupon-recovery invariant, not a curve oracle -
    /// the curve oracles are the two clean-price tests above.
    #[test]
    fn the_atm_rate_recovers_the_single_coupon_rate() {
        let bond = plain_bond();
        let curve = discount_curve();
        let atm = BondFunctions::atm_rate(&bond, &curve, None).unwrap();
        assert!((atm - 0.02875).abs() < 1e-10, "atm rate {atm}");
    }

    /// The basis-point value equals the dirty-price change for a one-basis-point
    /// coupon bump: the price is linear in the coupon rate on a fixed curve, so
    /// the finite difference is exact.
    #[test]
    fn the_bps_matches_a_one_basis_point_coupon_bump() {
        let curve = discount_curve();
        let base = plain_bond();
        let bumped = bond_with_coupons(vec![0.02875 + 1.0e-4]);
        let bps = BondFunctions::bps(&base, &curve, None).unwrap();
        let bump = BondFunctions::dirty_price(&bumped, &curve, None).unwrap()
            - BondFunctions::dirty_price(&base, &curve, None).unwrap();
        assert!((bps - bump).abs() < 1e-10, "bps {bps} vs bump {bump}");
    }

    /// Away from a coupon date the clean price nets off a positive accrued
    /// amount, and the three wrappers stay consistent.
    #[test]
    fn the_clean_price_nets_the_accrued_interest_off_the_dirty_price() {
        let bond = plain_bond();
        let curve = discount_curve();
        let mid = Date::new(15, Month::January, 2005);
        let dirty = BondFunctions::dirty_price(&bond, &curve, Some(mid)).unwrap();
        let clean = BondFunctions::clean_price(&bond, &curve, Some(mid)).unwrap();
        let accrued = BondFunctions::accrued_amount(&bond, Some(mid)).unwrap();
        assert!(accrued > 0.0, "accrued {accrued}");
        assert!((dirty - clean - accrued).abs() < 1e-12);
    }

    /// Once the notional has been redeemed the bond is no longer tradable: the
    /// price wrappers error and the accrued amount is zero.
    #[test]
    fn a_redeemed_bond_is_not_tradable() {
        let bond = plain_bond();
        let curve = discount_curve();
        let after = Date::new(1, Month::December, 2008);
        assert!(!BondFunctions::is_tradable(&bond, Some(after)).unwrap());
        let err = BondFunctions::dirty_price(&bond, &curve, Some(after)).unwrap_err();
        assert!(err.message().contains("non tradable"));
        assert_eq!(
            BondFunctions::accrued_amount(&bond, Some(after)).unwrap(),
            0.0
        );
    }
}

/// The yield-side wrappers reproduced at the bond-instrument level, oracling the
/// leg analytics of #251 through `BondFunctions`.
///
/// The cases chosen to oracle the wrappers at the bond level: the gilt and
/// Australian ex-coupon bonds (`bonds.cpp::testExCouponGilt` :1155,
/// `testExCouponAustralianBond` :1283), `testBasisPointValue` (:1759) and
/// `testThirty360BondWithSettlementOn31st` (:1715). In C++ only the last two
/// call the `BondFunctions` wrappers directly; the ex-coupon tests call
/// `CashFlows::` on the bare leg (`:1265`, `:1393`). The Rust cases route every
/// number through the bond wrappers regardless, which is the bond-level oracle
/// this ticket wants. Each builds the `FixedRateBond` cash flows, feeds the
/// tabulated price to [`BondFunctions::yield_rate`] (or [`Bond::yield_rate`]),
/// and checks the analytics that come back; the redemption is the one
/// `Bond::from_coupons` appends, so the leg matches #251's exactly.
#[cfg(test)]
mod yield_tests {
    use super::*;
    use crate::cashflows::FixedRateLeg;
    use crate::instruments::BondPrice;
    use crate::interestrate::{Compounding, InterestRate};
    use crate::settings::Settings;
    use crate::shared::{Shared, shared};
    use crate::time::businessdayconvention::BusinessDayConvention;
    use crate::time::calendar::Calendar;
    use crate::time::calendars::australia::{self, Australia};
    use crate::time::calendars::nullcalendar::NullCalendar;
    use crate::time::calendars::unitedkingdom::{self, UnitedKingdom};
    use crate::time::calendars::unitedstates::{self, UnitedStates};
    use crate::time::date::Month;
    use crate::time::dategenerationrule::DateGeneration;
    use crate::time::daycounters::actualactual::{ActualActual, Convention};
    use crate::time::daycounters::thirty360::{Convention as Thirty360Convention, Thirty360};
    use crate::time::frequency::Frequency;
    use crate::time::period::Period;
    use crate::time::schedule::Schedule;
    use crate::time::timeunit::TimeUnit;

    const FACE_AMOUNT: Real = 1_000_000.0;

    /// One row of a `bonds.cpp` expectation table: the settlement date, the
    /// dirty price (`testPrice + accrued`, per 100 of notional) and the
    /// Bloomberg yield, duration and convexity it drives.
    struct Case {
        settlement: Date,
        dirty_price: Real,
        irr: Rate,
        duration: Real,
        convexity: Real,
    }

    fn us_gov() -> Calendar {
        UnitedStates::new(unitedstates::Market::GovernmentBond)
    }

    /// The `FixedRateBond` of the ex-coupon cases: a semiannual `ActualActual
    /// (ISMA)` leg on a 100 notional with an ex-coupon period, wrapped in a
    /// `Bond` whose appended par redemption completes the leg.
    fn ex_coupon_bond(
        start: Date,
        first_coupon: Date,
        maturity: Date,
        coupon: Rate,
        ex_coupon_period: Period,
        payment_calendar: Calendar,
        ex_coupon_calendar: Calendar,
    ) -> (Bond, DayCounter) {
        let unadjusted = BusinessDayConvention::Unadjusted;
        let schedule = Schedule::new(
            start,
            maturity,
            Period::new(6, TimeUnit::Months),
            NullCalendar::new(),
            unadjusted,
            unadjusted,
            DateGeneration::Forward,
            true,
            first_coupon,
            Date::null(),
        );
        let day_counter = ActualActual::with_schedule(Convention::ISMA, schedule.clone());
        let leg = FixedRateLeg::new(schedule)
            .with_notional(100.0)
            .with_coupon_rate(
                coupon,
                day_counter.clone(),
                Compounding::Simple,
                Frequency::Annual,
            )
            .unwrap()
            .with_payment_calendar(payment_calendar.clone())
            .with_payment_adjustment(unadjusted)
            .with_ex_coupon_period(ex_coupon_period, ex_coupon_calendar, unadjusted, false)
            .build()
            .unwrap();
        let bond =
            Bond::from_coupons(1, payment_calendar, None, leg, shared(Settings::new())).unwrap();
        (bond, day_counter)
    }

    /// The `yield -> duration -> convexity` round trip each table row drives
    /// through `BondFunctions`, at the row's C++ tolerances.
    fn check(bond: &Bond, day_counter: &DayCounter, case: &Case, tolerance: (Real, Real, Real)) {
        let (comp, freq) = (Compounding::Compounded, Frequency::Semiannual);
        let settlement = Some(case.settlement);

        let irr = BondFunctions::yield_rate(
            bond,
            BondPrice::Dirty(case.dirty_price),
            day_counter.clone(),
            comp,
            freq,
            settlement,
            None,
            None,
            None,
        )
        .unwrap();
        assert!((irr - case.irr).abs() < tolerance.0, "yield {irr}");

        let rate = InterestRate::new(irr, day_counter.clone(), comp, freq).unwrap();
        let duration =
            BondFunctions::duration(bond, &rate, Duration::Modified, settlement).unwrap();
        assert!(
            (duration - case.duration).abs() < tolerance.0,
            "duration {duration}"
        );

        let convexity = BondFunctions::convexity(bond, &rate, settlement).unwrap();
        assert!(
            (convexity - case.convexity).abs() < tolerance.1,
            "convexity {convexity}"
        );
    }

    /// `bonds.cpp::testExCouponGilt` (:1155), verified against Bloomberg.
    #[test]
    fn the_uk_gilt_reproduces_its_yield_duration_and_convexity_through_the_bond() {
        let calendar = UnitedKingdom::new(unitedkingdom::Market::Settlement);
        let (bond, day_counter) = ex_coupon_bond(
            Date::new(29, Month::February, 1996),
            Date::new(7, Month::June, 1996),
            Date::new(7, Month::June, 2021),
            0.08,
            Period::new(6, TimeUnit::Days),
            calendar.clone(),
            calendar,
        );
        let cases = [
            Case {
                settlement: Date::new(29, Month::May, 2013),
                dirty_price: 106.8021978,
                irr: 0.0749518,
                duration: 5.6760445,
                convexity: 42.1531486,
            },
            Case {
                settlement: Date::new(30, Month::May, 2013),
                dirty_price: 102.8241758,
                irr: 0.0749618,
                duration: 5.8928163,
                convexity: 43.7562186,
            },
            Case {
                settlement: Date::new(31, Month::May, 2013),
                dirty_price: 102.8461538,
                irr: 0.0749599,
                duration: 5.8901860,
                convexity: 43.7239438,
            },
        ];
        for case in &cases {
            check(&bond, &day_counter, case, (1e-6, 1e-6, 1e-6));
        }
    }

    /// `bonds.cpp::testExCouponAustralianBond` (:1283), Bloomberg-verified.
    #[test]
    fn the_australian_bond_reproduces_its_yield_duration_and_convexity_through_the_bond() {
        let (bond, day_counter) = ex_coupon_bond(
            Date::new(15, Month::February, 2004),
            Date::new(15, Month::August, 2004),
            Date::new(15, Month::February, 2017),
            0.06,
            Period::new(7, TimeUnit::Days),
            Australia::new(australia::Market::Settlement),
            NullCalendar::new(),
        );
        let cases = [
            Case {
                settlement: Date::new(7, Month::August, 2014),
                dirty_price: 105.867,
                irr: 0.04723,
                duration: 2.26276,
                convexity: 6.54870,
            },
            Case {
                settlement: Date::new(8, Month::August, 2014),
                dirty_price: 102.884,
                irr: 0.047235,
                duration: 2.32536,
                convexity: 6.72531,
            },
            Case {
                settlement: Date::new(11, Month::August, 2014),
                dirty_price: 102.934,
                irr: 0.047190,
                duration: 2.31732,
                convexity: 6.68407,
            },
        ];
        for case in &cases {
            check(&bond, &day_counter, case, (1e-5, 1e-4, 1e-3));
        }
    }

    fn treasury_today() -> Date {
        Date::new(29, Month::January, 2024)
    }

    /// The `FixedRateBond` cash flows of `testBasisPointValue`: a semiannual
    /// `Thirty360(USA)` leg on the million-face notional at `coupon`, with the
    /// par redemption `Bond::from_coupons` appends.
    fn treasury_bond(coupon: Rate, settings: Shared<Settings<Date>>) -> (Bond, DayCounter) {
        let unadjusted = BusinessDayConvention::Unadjusted;
        let day_counter = Thirty360::with_convention(Thirty360Convention::USA);
        let schedule = Schedule::new(
            Date::new(15, Month::November, 2023),
            Date::new(15, Month::August, 2033),
            Period::new(6, TimeUnit::Months),
            us_gov(),
            unadjusted,
            unadjusted,
            DateGeneration::Forward,
            false,
            Date::null(),
            Date::null(),
        );
        let leg = FixedRateLeg::new(schedule)
            .with_notional(FACE_AMOUNT)
            .with_coupon_rate(
                coupon,
                day_counter.clone(),
                Compounding::Simple,
                Frequency::Annual,
            )
            .unwrap()
            .with_payment_calendar(us_gov())
            .with_payment_adjustment(unadjusted)
            .build()
            .unwrap();
        let bond = Bond::from_coupons(1, us_gov(), None, leg, settings).unwrap();
        (bond, day_counter)
    }

    /// `bonds.cpp::testBasisPointValue` (:1759): the clean price yields
    /// 0.041301, and the basis-point value and yield value reproduce the table
    /// at `:1798-1806` at both settlement dates. The yield is solved once and
    /// reused, as C++ does, since `d(bpv)/dy` here is of order 1e4.
    #[test]
    fn the_treasury_bond_reproduces_its_basis_point_value_through_the_bond() {
        let settings = shared(Settings::new());
        settings.set_evaluation_date(treasury_today());
        let (bond, day_counter) = treasury_bond(0.045, settings);
        let (comp, freq) = (Compounding::Compounded, Frequency::Semiannual);
        let settlement = Date::new(30, Month::January, 2024);

        let irr = BondFunctions::yield_rate(
            &bond,
            BondPrice::Clean(102.890625),
            day_counter.clone(),
            comp,
            freq,
            Some(settlement),
            None,
            None,
            None,
        )
        .unwrap();
        assert!((irr - 0.041301).abs() < 1e-6, "yield {irr}");

        let rate = InterestRate::new(irr, day_counter, comp, freq).unwrap();
        let cases = [
            (settlement, -795.098043, -0.0012571287),
            (
                Date::new(12, Month::February, 2024),
                -792.789400,
                -0.0012607913,
            ),
        ];
        for (settlement, expected_bpv, expected_yvbp) in cases {
            let settlement = Some(settlement);
            let bpv = BondFunctions::basis_point_value(&bond, &rate, settlement).unwrap();
            assert!((bpv - expected_bpv).abs() < 1e-6, "bpv {bpv}");

            let yvbp = BondFunctions::yield_value_basis_point(&bond, &rate, settlement).unwrap()
                * FACE_AMOUNT;
            assert!((yvbp - expected_yvbp).abs() < 1e-9, "yvbp {yvbp}");
        }
    }

    /// [`Bond::yield_rate`] resolves the default settlement date off the
    /// evaluation date and reproduces the treasury yield, closing the instrument
    /// round trip.
    #[test]
    fn the_bond_yield_method_reproduces_the_treasury_yield() {
        let settings = shared(Settings::new());
        settings.set_evaluation_date(treasury_today());
        let (bond, day_counter) = treasury_bond(0.045, settings);
        let irr = bond
            .yield_rate(
                BondPrice::Clean(102.890625),
                day_counter,
                Compounding::Compounded,
                Frequency::Semiannual,
                None,
                None,
                None,
                None,
            )
            .unwrap();
        assert!((irr - 0.041301).abs() < 1e-6, "yield {irr}");
    }

    /// The basis-point value per 100 of notional is the change in the leg's
    /// present value for a one-basis-point bump in the coupon at the same flat
    /// yield: an independent finite difference of the analytic `bps_at_yield`.
    #[test]
    fn the_bps_at_yield_matches_a_one_basis_point_coupon_bump() {
        let settings = shared(Settings::new());
        settings.set_evaluation_date(treasury_today());
        let settlement = Some(Date::new(30, Month::January, 2024));
        let rate = InterestRate::new(
            0.041301,
            Thirty360::with_convention(Thirty360Convention::USA),
            Compounding::Compounded,
            Frequency::Semiannual,
        )
        .unwrap();

        let (base, _) = treasury_bond(0.045, settings.clone());
        let (bumped, _) = treasury_bond(0.045 + 1.0e-4, settings.clone());
        let base_npv = CashFlows::npv_at_yield(
            base.cashflows(),
            &rate,
            settings.as_ref(),
            Some(false),
            settlement,
            None,
        )
        .unwrap();
        let bumped_npv = CashFlows::npv_at_yield(
            bumped.cashflows(),
            &rate,
            settings.as_ref(),
            Some(false),
            settlement,
            None,
        )
        .unwrap();

        let bps = BondFunctions::bps_at_yield(&base, &rate, settlement).unwrap();
        let bump = (bumped_npv - base_npv) * 100.0 / FACE_AMOUNT;
        assert!((bps - bump).abs() < 1e-6, "bps {bps} vs bump {bump}");
    }

    /// A redeemed bond is not tradable, so the yield wrappers guard, while
    /// [`Bond::yield_rate`] short-circuits to a zero yield.
    #[test]
    fn a_redeemed_bond_has_no_yield_analytics() {
        let settings = shared(Settings::new());
        settings.set_evaluation_date(treasury_today());
        let (bond, day_counter) = treasury_bond(0.045, settings);
        let after = Date::new(16, Month::August, 2033);
        let rate = InterestRate::new(
            0.041301,
            day_counter.clone(),
            Compounding::Compounded,
            Frequency::Semiannual,
        )
        .unwrap();

        let err =
            BondFunctions::duration(&bond, &rate, Duration::Modified, Some(after)).unwrap_err();
        assert!(err.message().contains("non tradable"));
        let zero = bond
            .yield_rate(
                BondPrice::Clean(100.0),
                day_counter,
                Compounding::Compounded,
                Frequency::Semiannual,
                Some(after),
                None,
                None,
                None,
            )
            .unwrap();
        assert_eq!(zero, 0.0);
    }

    /// `bonds.cpp::testThirty360BondWithSettlementOn31st` (:1715): a real bond
    /// (CUSIP 3130A0X70, Bloomberg data) whose settlement falls on the 31st,
    /// driving yield, Macaulay duration, convexity and accrued straight through
    /// the `BondFunctions` wrappers at the C++ tolerances.
    #[test]
    fn the_thirty360_bond_reproduces_its_yield_macaulay_duration_and_convexity() {
        let settings = shared(Settings::new());
        settings.set_evaluation_date(Date::new(28, Month::July, 2017));
        let unadjusted = BusinessDayConvention::Unadjusted;
        let day_counter = Thirty360::with_convention(Thirty360Convention::USA);
        let schedule = Schedule::new(
            Date::new(13, Month::February, 2014),
            Date::new(13, Month::August, 2018),
            Period::new(6, TimeUnit::Months),
            us_gov(),
            unadjusted,
            unadjusted,
            DateGeneration::Forward,
            false,
            Date::null(),
            Date::null(),
        );
        let leg = FixedRateLeg::new(schedule)
            .with_notional(100.0)
            .with_coupon_rate(
                0.015,
                day_counter.clone(),
                Compounding::Simple,
                Frequency::Annual,
            )
            .unwrap()
            .with_payment_calendar(us_gov())
            .with_payment_adjustment(unadjusted)
            .build()
            .unwrap();
        let bond = Bond::from_coupons(1, us_gov(), None, leg, settings).unwrap();

        let (comp, freq) = (Compounding::Compounded, Frequency::Semiannual);
        let settlement = Some(Date::new(31, Month::July, 2017));

        let irr = BondFunctions::yield_rate(
            &bond,
            BondPrice::Clean(100.0),
            day_counter.clone(),
            comp,
            freq,
            settlement,
            None,
            None,
            None,
        )
        .unwrap();
        assert!((irr - 0.015).abs() < 1e-4, "yield {irr}");

        let rate = InterestRate::new(irr, day_counter, comp, freq).unwrap();
        let duration =
            BondFunctions::duration(&bond, &rate, Duration::Macaulay, settlement).unwrap();
        assert!((duration - 1.022).abs() < 1e-3, "duration {duration}");

        let convexity = BondFunctions::convexity(&bond, &rate, settlement).unwrap() / 100.0;
        assert!((convexity - 0.015).abs() < 1e-3, "convexity {convexity}");

        let accrued = BondFunctions::accrued_amount(&bond, settlement).unwrap();
        assert!((accrued - 0.7).abs() < 1e-6, "accrued {accrued}");
    }
}

#[cfg(test)]
#[path = "bond_price_atm_tests.rs"]
mod price_atm_tests;

#[cfg(test)]
#[path = "bond_yield_convention_tests.rs"]
mod yield_convention_tests;