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
//! Fixed-rate and zero-coupon callable/puttable bonds for lattice valuation.
//!
//! Port of the bond products and argument setup in
//! `ql/experimental/callablebonds/callablebond.{hpp,cpp}`. Prices are quoted per
//! 100 of face amount; clean exercise prices use indenture accrued interest,
//! independently of market ex-coupon conventions.

mod impliedvolatility;

mod oas;

mod sensitivities;

use std::any::Any;
use std::cell::Cell;

use crate::errors::QlResult;
use crate::event::event_has_occurred;
use crate::instrument::{Instrument, InstrumentBase};
use crate::instruments::{Bond, BondPrice, FixedRateBond, ZeroCouponBond};
use crate::pricingengine::{Arguments, Results};
use crate::pricingengines::bond::BlackCallableBondArguments;
use crate::settings::Settings;
use crate::shared::Shared;
use crate::time::businessdayconvention::BusinessDayConvention;
use crate::time::calendar::Calendar;
use crate::time::calendars::nullcalendar::NullCalendar;
use crate::time::date::Date;
use crate::time::daycounter::DayCounter;
use crate::time::frequency::Frequency;
use crate::time::period::Period;
use crate::time::schedule::Schedule;
use crate::types::{Natural, Rate, Real};
use crate::{fail, require};

/// The issuer's redemption right or the holder's sale right.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CallabilityType {
    /// The issuer may redeem the bond at the exercise price.
    Call,
    /// The holder may sell the bond back at the exercise price.
    Put,
}

/// A dated hard call or put, with a clean or dirty price per 100.
#[derive(Clone, Debug)]
pub struct Callability {
    price: BondPrice,
    call_type: CallabilityType,
    date: Date,
}

impl Callability {
    /// Constructs an exercise right.
    ///
    /// # Errors
    ///
    /// Rejects negative or nonfinite prices and null exercise dates.
    pub fn new(price: BondPrice, call_type: CallabilityType, date: Date) -> QlResult<Self> {
        require!(
            price.amount().is_finite() && price.amount() >= 0.0,
            "callability price must be finite and nonnegative"
        );
        require!(date != Date::null(), "null callability date");
        Ok(Self {
            price,
            call_type,
            date,
        })
    }

    /// The exercise price per 100, including its quote convention.
    pub fn price(&self) -> BondPrice {
        self.price
    }

    /// The direction of the exercise right.
    pub fn call_type(&self) -> CallabilityType {
        self.call_type
    }

    /// The exercise date.
    pub fn date(&self) -> Date {
        self.date
    }
}

/// Dated hard calls and puts, applied in the order supplied.
pub type CallabilitySchedule = Vec<Callability>;

/// Cash flows and exercise events required by a callable-bond engine.
#[derive(Default)]
pub struct CallableBondArguments {
    /// The date at which the bond is bought and quoted.
    pub settlement_date: Option<Date>,
    /// Coupon payment dates for flows owned at settlement.
    pub coupon_dates: Vec<Date>,
    /// Coupon amounts aligned with payment dates, in currency units.
    pub coupon_amounts: Vec<Real>,
    /// Constant face amount used to convert exercise quotes into currency units.
    pub face_amount: Real,
    /// The final redemption amount in currency units.
    pub redemption: Real,
    /// The final redemption date.
    pub redemption_date: Option<Date>,
    /// Dirty exercise prices per 100, aligned with dates and types.
    pub callability_prices: Vec<Real>,
    /// Exercise directions aligned with dates and prices.
    pub callability_types: Vec<CallabilityType>,
    /// Exercise dates still available after settlement.
    pub callability_dates: Vec<Date>,
}

impl Arguments for CallableBondArguments {
    fn validate(&self) -> QlResult<()> {
        let Some(settlement) = self.settlement_date else {
            fail!("null settlement date");
        };
        let Some(redemption_date) = self.redemption_date else {
            fail!("null redemption date");
        };
        require!(
            settlement != Date::null() && redemption_date != Date::null(),
            "null bond date"
        );
        require!(settlement <= redemption_date, "settlement after redemption");
        require!(
            self.face_amount.is_finite() && self.face_amount > 0.0,
            "face amount must be finite and positive"
        );
        require!(
            self.redemption.is_finite() && self.redemption >= 0.0,
            "redemption must be finite and nonnegative"
        );
        require!(
            self.coupon_dates.len() == self.coupon_amounts.len(),
            "coupon dates/amounts length mismatch"
        );
        require!(
            self.callability_dates.len() == self.callability_prices.len()
                && self.callability_dates.len() == self.callability_types.len(),
            "callability dates/prices/types length mismatch"
        );
        require!(
            self.coupon_dates.windows(2).all(|pair| pair[0] <= pair[1]),
            "coupon dates must be ordered"
        );
        for (date, amount) in self.coupon_dates.iter().zip(&self.coupon_amounts) {
            require!(
                *date != Date::null() && *date > settlement && *date <= redemption_date,
                "coupon outside settlement/redemption interval"
            );
            require!(amount.is_finite(), "nonfinite coupon amount");
        }
        for (date, price) in self.callability_dates.iter().zip(&self.callability_prices) {
            require!(
                *date != Date::null() && *date > settlement && *date <= redemption_date,
                "callability outside settlement/redemption interval"
            );
            require!(
                price.is_finite() && *price >= 0.0,
                "invalid callability price"
            );
        }
        Ok(())
    }
}

fn checked_callable_settlement_date(bond: &Bond, settings: &Settings<Date>) -> QlResult<Date> {
    let mut date = settings
        .evaluation_date()
        .ok_or_else(|| crate::errors::QlError::new("evaluation date is unset", file!(), line!()))?;
    require!(date != Date::null(), "null evaluation date");
    let calendar = bond.calendar();
    let mut remaining = bond.settlement_days();
    while remaining > 0 || calendar.is_holiday(date) {
        require!(
            date < Date::max_date(),
            "settlement exceeds supported date range"
        );
        date += 1;
        if calendar.is_business_day(date) {
            remaining = remaining.saturating_sub(1);
        }
    }
    Ok(bond.issue_date().map_or(date, |issue| date.max(issue)))
}

/// A fixed-rate bond with dated hard issuer calls or holder puts.
///
/// This composes the existing fixed-rate bond and shares its instrument base,
/// expiry handling, cash-flow observers and settlement-result storage.
pub struct CallableFixedRateBond {
    bond: FixedRateBond,
    put_call_schedule: CallabilitySchedule,
    face_amount: Real,
    settings: Shared<Settings<Date>>,
}

impl CallableFixedRateBond {
    /// Constructs a callable fixed-rate bond without an ex-coupon period.
    ///
    /// # Errors
    ///
    /// Rejects invalid amounts, nonfinite coupons, exercise after maturity,
    /// and the existing fixed-rate bond's construction errors.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        settlement_days: Natural,
        face_amount: Real,
        schedule: Schedule,
        coupons: Vec<Rate>,
        accrual_day_counter: DayCounter,
        payment_convention: BusinessDayConvention,
        redemption: Real,
        issue_date: Option<Date>,
        put_call_schedule: CallabilitySchedule,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Self> {
        Self::with_ex_coupon(
            settlement_days,
            face_amount,
            schedule,
            coupons,
            accrual_day_counter,
            payment_convention,
            redemption,
            issue_date,
            put_call_schedule,
            None,
            NullCalendar::new(),
            BusinessDayConvention::Unadjusted,
            false,
            settings,
        )
    }

    /// Constructs a callable bond with market ex-coupon conventions.
    ///
    /// Clean exercise quotes still include indenture accrued from the previous
    /// coupon, rather than the market's negative ex-coupon accrued interest.
    ///
    /// # Errors
    ///
    /// Propagates the same construction errors as [`new`](Self::new).
    #[allow(clippy::too_many_arguments)]
    pub fn with_ex_coupon(
        settlement_days: Natural,
        face_amount: Real,
        schedule: Schedule,
        coupons: Vec<Rate>,
        accrual_day_counter: DayCounter,
        payment_convention: BusinessDayConvention,
        redemption: Real,
        issue_date: Option<Date>,
        put_call_schedule: CallabilitySchedule,
        ex_coupon_period: Option<Period>,
        ex_coupon_calendar: Calendar,
        ex_coupon_convention: BusinessDayConvention,
        ex_coupon_end_of_month: bool,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Self> {
        require!(
            schedule.len() >= 2,
            "callable bond schedule requires at least two dates"
        );
        require!(
            schedule.dates().iter().all(|date| *date != Date::null())
                && schedule.dates().windows(2).all(|pair| pair[0] < pair[1]),
            "callable bond schedule dates must be nonnull and strictly increasing"
        );
        require!(
            face_amount.is_finite() && face_amount > 0.0,
            "face amount must be finite and positive"
        );
        require!(
            redemption.is_finite() && redemption >= 0.0,
            "redemption must be finite and nonnegative"
        );
        require!(
            coupons.iter().all(|rate| rate.is_finite()),
            "nonfinite coupon rate"
        );
        require!(
            put_call_schedule
                .iter()
                .all(|call| call.date() <= schedule.end_date()),
            "bond cannot mature before the last call/put date"
        );
        let bond = FixedRateBond::new(
            settlement_days,
            face_amount,
            schedule,
            coupons,
            accrual_day_counter,
            payment_convention,
            redemption,
            issue_date,
            None,
            ex_coupon_period,
            ex_coupon_calendar,
            ex_coupon_convention,
            ex_coupon_end_of_month,
            None,
            Shared::clone(&settings),
        )?;
        Ok(Self {
            bond,
            put_call_schedule,
            face_amount,
            settings,
        })
    }

    fn checked_settlement_date(&self) -> QlResult<Date> {
        checked_callable_settlement_date(self.bond(), &self.settings)
    }

    /// The immutable exercise schedule.
    pub fn callability(&self) -> &CallabilitySchedule {
        &self.put_call_schedule
    }

    /// The existing bond base for schedule, notional, settlement and accrual queries.
    pub fn bond(&self) -> &Bond {
        self.bond.bond()
    }

    /// The engine's value at settlement, in currency units.
    ///
    /// # Errors
    ///
    /// Propagates pricing failures or a missing settlement value.
    pub fn settlement_value(&mut self) -> QlResult<Real> {
        self.calculate()?;
        self.bond.bond_mut().settlement_value()
    }

    /// The settlement price per 100 including accrued interest.
    ///
    /// # Errors
    ///
    /// Propagates pricing, settlement and notional errors.
    pub fn dirty_price(&mut self) -> QlResult<Real> {
        self.calculate()?;
        let notional = self
            .bond()
            .notional(Some(self.checked_settlement_date()?))?;
        if notional == 0.0 {
            return Ok(0.0);
        }
        let price = (self.settlement_value()? / notional) * 100.0;
        require!(price.is_finite(), "callable dirty price overflow");
        Ok(price)
    }

    /// The settlement price per 100 excluding accrued interest.
    ///
    /// # Errors
    ///
    /// Propagates pricing, settlement, notional and accrual errors.
    pub fn clean_price(&mut self) -> QlResult<Real> {
        let price = self.dirty_price()?
            - self
                .bond()
                .accrued_amount(Some(self.checked_settlement_date()?))?;
        require!(price.is_finite(), "callable clean price overflow");
        Ok(price)
    }
}

impl Instrument for CallableFixedRateBond {
    fn base(&self) -> &InstrumentBase {
        self.bond.bond().base()
    }
    fn base_mut(&mut self) -> &mut InstrumentBase {
        self.bond.bond_mut().base_mut()
    }
    fn is_expired(&self) -> QlResult<bool> {
        self.bond.bond().is_expired()
    }
    fn setup_expired(&mut self) {
        self.bond.bond_mut().setup_expired();
    }
    fn fetch_results(&mut self, results: &dyn Results) -> QlResult<()> {
        self.bond.bond_mut().fetch_results(results)
    }

    fn setup_arguments(&self, arguments: &mut dyn Arguments) -> QlResult<()> {
        if let Some(args) = (arguments as &mut dyn Any).downcast_mut::<BlackCallableBondArguments>()
        {
            self.setup_arguments(&mut args.bond)?;
            args.cashflows = self.bond().cashflows().clone();
            args.payment_day_counter = Some(self.bond.day_counter().clone());
            args.frequency = self.bond.frequency();
            args.callability_count = self.put_call_schedule.len();
            return Ok(());
        }
        let Some(args) = (arguments as &mut dyn Any).downcast_mut::<CallableBondArguments>() else {
            fail!("wrong argument type");
        };
        let settlement = self.checked_settlement_date()?;
        let redemption =
            self.bond().redemptions().first().ok_or_else(|| {
                crate::errors::QlError::new("missing redemption", file!(), line!())
            })?;
        *args = CallableBondArguments {
            settlement_date: Some(settlement),
            face_amount: self.face_amount,
            redemption: redemption.amount()?,
            redemption_date: Some(redemption.date()),
            ..CallableBondArguments::default()
        };
        for flow in self.bond().cashflows() {
            if flow.as_coupon().is_some()
                && !flow.has_occurred(&self.settings, Some(settlement), Some(false))?
                && !flow.trading_ex_coupon(&self.settings, Some(settlement))?
            {
                args.coupon_dates.push(flow.date());
                args.coupon_amounts.push(flow.amount()?);
            }
        }
        for callability in &self.put_call_schedule {
            let call_date = callability.date();
            if event_has_occurred(call_date, &self.settings, Some(settlement), Some(false))? {
                continue;
            }
            let mut price = callability.price().amount();
            if let BondPrice::Clean(_) = callability.price() {
                for flow in self.bond().cashflows() {
                    if !event_has_occurred(
                        flow.date(),
                        &self.settings,
                        Some(call_date),
                        Some(false),
                    )? {
                        if let Some(coupon) = flow.as_coupon() {
                            let mut accrued = coupon.accrued_amount(call_date)?;
                            if coupon.trades_ex_coupon_on(call_date) {
                                accrued += flow.amount()?;
                            }
                            let notional = self.bond().notional(Some(call_date))?;
                            require!(
                                notional.is_finite() && notional > 0.0,
                                "invalid notional at call date"
                            );
                            price += accrued / notional * 100.0;
                        }
                        break;
                    }
                }
            }
            args.callability_dates.push(call_date);
            args.callability_types.push(callability.call_type());
            args.callability_prices.push(price);
        }
        Ok(())
    }
}

/// A zero-coupon bond with dated hard issuer calls or holder puts.
///
/// Uses the underlying bond's instrument base, observers and settlement results.
/// Clean and dirty exercise quotes coincide because no interest accrues.
pub struct CallableZeroCouponBond {
    bond: Bond,
    put_call_schedule: CallabilitySchedule,
    face_amount: Real,
    day_counter: DayCounter,
    settings: Shared<Settings<Date>>,
    settings_flags: Cell<(bool, Option<bool>)>,
}

impl CallableZeroCouponBond {
    /// Constructs a single-redemption callable bond.
    ///
    /// `redemption` and exercise prices are per 100 of face. Contractual maturity
    /// is unadjusted; the redemption payment follows `payment_convention`.
    /// Exercise rights retain the supplied order, including coincident events.
    ///
    /// # Errors
    /// Rejects nonpositive/nonfinite face, negative/nonfinite redemption,
    /// invalid issue dates and exercise after maturity or adjusted redemption.
    /// Propagates zero-coupon construction errors, including scaled overflow.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        settlement_days: Natural,
        face_amount: Real,
        calendar: Calendar,
        maturity_date: Date,
        day_counter: DayCounter,
        payment_convention: BusinessDayConvention,
        redemption: Real,
        issue_date: Option<Date>,
        put_call_schedule: CallabilitySchedule,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Self> {
        require!(
            face_amount.is_finite() && face_amount > 0.0,
            "face amount must be finite and positive"
        );
        require!(
            redemption.is_finite() && redemption >= 0.0,
            "redemption must be finite and nonnegative"
        );
        require!(maturity_date != Date::null(), "null maturity date");
        require!(
            settlement_days <= (Date::max_date() - Date::min_date()) as Natural,
            "settlement lag exceeds supported date range"
        );
        let payment_date = Self::adjusted_date(&calendar, maturity_date, payment_convention)?;
        if let Some(issue) = issue_date {
            require!(
                issue != Date::null() && issue <= maturity_date && issue <= payment_date,
                "invalid issue date"
            );
        }
        require!(
            put_call_schedule
                .iter()
                .all(|call| call.date() <= maturity_date && call.date() <= payment_date),
            "bond cannot redeem before the last call/put date"
        );
        let bond = ZeroCouponBond::new(
            settlement_days,
            calendar,
            face_amount,
            maturity_date,
            payment_convention,
            redemption,
            issue_date,
            Shared::clone(&settings),
        )?
        .into_bond();
        Ok(Self {
            bond,
            put_call_schedule,
            face_amount,
            day_counter,
            settings_flags: Cell::new(Self::flags(&settings)),
            settings,
        })
    }

    fn adjusted_date(
        calendar: &Calendar,
        date: Date,
        convention: BusinessDayConvention,
    ) -> QlResult<Date> {
        use BusinessDayConvention::*;
        let roll = |mut candidate: Date, step| -> QlResult<Date> {
            while calendar.is_holiday(candidate) {
                require!(
                    if step > 0 {
                        candidate < Date::max_date()
                    } else {
                        candidate > Date::min_date()
                    },
                    "payment adjustment exceeds supported date range"
                );
                candidate += step;
            }
            Ok(candidate)
        };
        match convention {
            Unadjusted => Ok(date),
            Following => roll(date, 1),
            Preceding => roll(date, -1),
            ModifiedFollowing | HalfMonthModifiedFollowing => {
                let next = roll(date, 1)?;
                if next.month() != date.month()
                    || (convention == HalfMonthModifiedFollowing
                        && date.day_of_month() <= 15
                        && next.day_of_month() > 15)
                {
                    roll(date, -1)
                } else {
                    Ok(next)
                }
            }
            ModifiedPreceding => {
                let previous = roll(date, -1)?;
                if previous.month() != date.month() {
                    roll(date, 1)
                } else {
                    Ok(previous)
                }
            }
            Nearest => {
                let (mut next, mut previous) = (date, date);
                while calendar.is_holiday(next) && calendar.is_holiday(previous) {
                    require!(
                        next < Date::max_date() && previous > Date::min_date(),
                        "payment adjustment exceeds supported date range"
                    );
                    next += 1;
                    previous -= 1;
                }
                Ok(if calendar.is_holiday(next) {
                    previous
                } else {
                    next
                })
            }
        }
    }

    fn checked_settlement_date(&self) -> QlResult<Date> {
        checked_callable_settlement_date(&self.bond, &self.settings)
    }

    fn flags(settings: &Settings<Date>) -> (bool, Option<bool>) {
        (
            settings.include_reference_date_events(),
            settings.include_todays_cash_flows(),
        )
    }

    /// The immutable exercise schedule.
    pub fn callability(&self) -> &CallabilitySchedule {
        &self.put_call_schedule
    }

    /// The underlying bond for cash-flow, settlement and notional queries.
    pub fn bond(&self) -> &Bond {
        &self.bond
    }

    /// The payment day counter supplied at construction.
    pub fn day_counter(&self) -> &DayCounter {
        &self.day_counter
    }

    /// The engine's value at settlement, in currency units.
    ///
    /// # Errors
    /// Propagates pricing failures or missing settlement results.
    pub fn settlement_value(&mut self) -> QlResult<Real> {
        self.calculate()?;
        self.bond.settlement_value()
    }

    /// The settlement price per 100 of face, including accrued interest.
    ///
    /// # Errors
    /// Propagates pricing, notional and settlement errors or quote overflow.
    pub fn dirty_price(&mut self) -> QlResult<Real> {
        self.calculate()?;
        if self.is_expired()? {
            return Ok(0.0);
        }
        let notional = self.bond.notional(Some(self.checked_settlement_date()?))?;
        if notional == 0.0 {
            return Ok(0.0);
        }
        let price = (self.settlement_value()? / notional) * 100.0;
        require!(price.is_finite(), "callable dirty price overflow");
        Ok(price)
    }

    /// The settlement price per 100, equal to the dirty price for this bond.
    ///
    /// # Errors
    /// Propagates the same errors as [`dirty_price`](Self::dirty_price).
    pub fn clean_price(&mut self) -> QlResult<Real> {
        self.dirty_price()
    }
}

impl Instrument for CallableZeroCouponBond {
    fn base(&self) -> &InstrumentBase {
        let flags = Self::flags(&self.settings);
        if self.settings_flags.replace(flags) != flags {
            self.bond.base().invalidate_silently();
        }
        self.bond.base()
    }
    fn base_mut(&mut self) -> &mut InstrumentBase {
        self.bond.base_mut()
    }
    fn is_expired(&self) -> QlResult<bool> {
        require!(
            self.settings
                .evaluation_date()
                .is_some_and(|date| date != Date::null()),
            "evaluation date must be set and nonnull"
        );
        self.bond.is_expired()
    }
    fn setup_expired(&mut self) {
        self.bond.setup_expired();
    }
    fn fetch_results(&mut self, results: &dyn Results) -> QlResult<()> {
        self.bond.fetch_results(results)
    }
    fn setup_arguments(&self, arguments: &mut dyn Arguments) -> QlResult<()> {
        if let Some(args) = (arguments as &mut dyn Any).downcast_mut::<BlackCallableBondArguments>()
        {
            self.setup_arguments(&mut args.bond)?;
            args.cashflows = self.bond().cashflows().clone();
            args.payment_day_counter = Some(self.day_counter.clone());
            args.frequency = Frequency::Once;
            args.callability_count = self.put_call_schedule.len();
            return Ok(());
        }
        let Some(args) = (arguments as &mut dyn Any).downcast_mut::<CallableBondArguments>() else {
            fail!("wrong argument type");
        };
        let settlement = self.checked_settlement_date()?;
        let redemption =
            self.bond.redemptions().first().ok_or_else(|| {
                crate::errors::QlError::new("missing redemption", file!(), line!())
            })?;
        *args = CallableBondArguments {
            settlement_date: Some(settlement),
            face_amount: self.face_amount,
            redemption: redemption.amount()?,
            redemption_date: Some(redemption.date()),
            ..CallableBondArguments::default()
        };
        for callability in &self.put_call_schedule {
            if event_has_occurred(
                callability.date(),
                &self.settings,
                Some(settlement),
                Some(false),
            )? {
                continue;
            }
            args.callability_dates.push(callability.date());
            args.callability_types.push(callability.call_type());
            args.callability_prices.push(callability.price().amount());
        }
        Ok(())
    }
}