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
use serde::{Deserialize, Serialize};
use crate::{
ad::adreal::{ADReal, IsReal},
core::request::LegsProvider,
currencies::currency::Currency,
indices::marketindex::MarketIndex,
instruments::cashflows::{cashflowtype::CashflowType, leg::Leg},
math::interpolation::interpolator::{Interpolate as _, Interpolator},
quotes::quote::{BuiltInstrument, Level, Quote},
rates::{
bootstrapping::resolvedcurvespec::{ResolvedCurveSpec, ResolvedInstrument},
compounding::Compounding,
interestrate::InterestRate,
},
time::{date::Date, daycounter::DayCounter, enums::Frequency},
utils::errors::{QSError, Result},
};
/// Selects market quotes by identifier.
pub trait QuoteSelector {
/// Returns the quote with the given identifier.
fn select(&self, identifier: &str) -> Option<Quote>;
/// Returns the reference (valuation) date used for building instruments.
fn reference_date(&self) -> Date;
}
/// User-defined bootstrap specification for a curve, carrying the quote
/// identifiers that should be used to calibrate it.
#[derive(Debug, Serialize, Deserialize)]
pub struct CurveSpec {
market_index: MarketIndex,
#[serde(default = "default_currency")]
currency: Currency,
#[serde(default = "default_day_counter")]
day_counter: DayCounter,
#[serde(default = "default_interpolator")]
interpolator: Interpolator,
#[serde(default = "default_enable_extrapolation")]
enable_extrapolation: bool,
/// Quote identifiers that define the pillars of this curve.
#[serde(default)]
quotes: Vec<String>,
}
const fn default_currency() -> Currency {
Currency::USD
}
const fn default_day_counter() -> DayCounter {
DayCounter::Actual360
}
const fn default_interpolator() -> Interpolator {
Interpolator::LogLinear
}
const fn default_enable_extrapolation() -> bool {
true
}
impl CurveSpec {
/// Creates a curve specification.
#[must_use]
pub const fn new(
market_index: MarketIndex,
currency: Currency,
day_counter: DayCounter,
interpolator: Interpolator,
enable_extrapolation: bool,
quotes: Vec<String>,
) -> Self {
Self {
market_index,
currency,
day_counter,
interpolator,
enable_extrapolation,
quotes,
}
}
/// Returns the market index for this spec.
#[must_use]
pub const fn market_index(&self) -> &MarketIndex {
&self.market_index
}
/// Returns the currency of this spec.
#[must_use]
pub const fn currency(&self) -> Currency {
self.currency
}
/// Resolves configured quote identifiers into concrete calibration
/// instruments.
///
/// # Errors
/// Returns an error if a quote is not found, quote levels are missing,
/// or a pillar date cannot be inferred.
pub fn resolve(
&self,
selector: &impl QuoteSelector,
level: Level,
) -> Result<ResolvedCurveSpec> {
let mut instruments = Vec::new();
for id in &self.quotes {
let Some(quote) = selector.select(id) else {
continue;
};
let fallback_value = ADReal::new(quote.levels().value(level)?);
let built = quote.build_instrument(selector.reference_date(), level)?;
let pillar_date = Self::resolve_pillar_dates(&built)?;
// When the tape is recording, the instrument build creates
// ADReal leaf nodes for its internal rates. We extract that
// same ADReal so `pillar_values` shares the identical tape
// node used in the bootstrap residual computation, giving
// end-to-end AD connectivity from quote → solver → DF.
let quote_value = Self::extract_primary_rate(&built).unwrap_or(fallback_value);
instruments.push(ResolvedInstrument::new(
quote,
level,
built,
quote_value,
pillar_date,
));
}
instruments.sort_by_key(super::resolvedcurvespec::ResolvedInstrument::pillar_date);
Ok(ResolvedCurveSpec::new(
self.market_index.clone(),
self.currency,
self.day_counter,
self.interpolator,
self.enable_extrapolation,
selector.reference_date(),
instruments,
))
}
/// Extracts the primary AD-enabled rate from a built instrument.
///
/// For instruments whose quote enters the residual through the
/// coupon-level `InterestRate` (deposits, swaps), this returns the
/// `ADReal` stored in the first [`FixedRateCoupon`]. Because
/// [`ADReal`] is `Copy` with a shared tape-node pointer, this is the
/// *same* tape leaf used by every coupon of the instrument.
///
/// For instruments where the quote is used directly in the residual
/// function (FX forwards, rate futures), the fallback `quote_value`
/// created in [`collect_quotes`] is used instead.
fn extract_primary_rate(built: &BuiltInstrument) -> Option<ADReal> {
match built {
BuiltInstrument::FixedRateDeposit(dep) => dep.leg().cashflows().iter().find_map(|cf| {
if let CashflowType::FixedRateCoupon(c) = cf {
Some(c.rate().rate())
} else {
None
}
}),
BuiltInstrument::Swap(swap) => {
for leg in swap.legs() {
for cf in leg.cashflows() {
if let CashflowType::FixedRateCoupon(c) = cf {
return Some(c.rate().rate());
}
}
}
None
}
BuiltInstrument::BasisSwap(bs) => {
// For basis swaps the quote is typically a spread on
// one of the floating legs.
for leg in bs.legs() {
for cf in leg.cashflows() {
if let CashflowType::FloatingRateCoupon(c) = cf {
let s = c.spread();
if s.value().abs() > 1e-18 {
return Some(s);
}
}
}
}
None
}
// Rate futures and FX forwards: the quote value is passed
// directly to the residual function, so we rely on the
// fallback created in collect_quotes.
_ => None,
}
}
/// Resolves the pillar date for a given built instrument.
fn resolve_pillar_dates(built: &BuiltInstrument) -> Result<Date> {
match built {
BuiltInstrument::FixedRateDeposit(x) => Ok(x.leg().last_payment_date()),
BuiltInstrument::Swap(x) => x
.legs()
.iter()
.map(Leg::last_payment_date)
.max()
.ok_or_else(|| QSError::InvalidValueErr("Swap has no legs".into())),
BuiltInstrument::BasisSwap(x) => x
.legs()
.iter()
.map(Leg::last_payment_date)
.max()
.ok_or_else(|| QSError::InvalidValueErr("BasisSwap has no legs".into())),
BuiltInstrument::CrossCurrencySwap(x) => x
.legs()
.iter()
.map(Leg::last_payment_date)
.max()
.ok_or_else(|| {
QSError::InvalidValueErr("CrossCurrencySwap has no legs".into())
}),
BuiltInstrument::RateFutures(x) => Ok(x.end_date()),
BuiltInstrument::FxForward(x) => Ok(x.delivery_date()),
_ => Err(QSError::InvalidValueErr("Instrument not supported".into())),
}
}
}
/// Curve state carrying current obtained values during bootstrapping.
#[derive(Clone)]
pub struct BootstrappedCurve {
reference_date: Date,
times: Vec<f64>,
discount_factors: Vec<ADReal>,
day_counter: DayCounter,
interpolator: Interpolator,
}
impl BootstrappedCurve {
/// Creates a curve with flat discount factors = 1.0 at every pillar.
#[must_use]
pub fn new(
reference_date: Date,
times: Vec<f64>,
day_counter: DayCounter,
interpolator: Interpolator,
) -> Self {
let discount_factors = vec![ADReal::one(); times.len()];
Self {
reference_date,
times,
discount_factors,
day_counter,
interpolator,
}
}
/// Creates a curve with explicit discount factors.
///
/// `times` and `discount_factors` must have the same length.
#[must_use]
pub const fn new_with_dfs(
reference_date: Date,
times: Vec<f64>,
discount_factors: Vec<ADReal>,
day_counter: DayCounter,
interpolator: Interpolator,
) -> Self {
Self {
reference_date,
times,
discount_factors,
day_counter,
interpolator,
}
}
/// Returns the reference date.
#[must_use]
pub const fn reference_date(&self) -> Date {
self.reference_date
}
/// Returns the day counter.
#[must_use]
pub const fn day_counter(&self) -> DayCounter {
self.day_counter
}
/// Returns the interpolator.
#[must_use]
pub const fn interpolator(&self) -> Interpolator {
self.interpolator
}
/// Returns the pillar times.
#[must_use]
pub fn times(&self) -> &[f64] {
&self.times
}
/// Returns the discount factors.
#[must_use]
pub fn discount_factors(&self) -> &[ADReal] {
&self.discount_factors
}
/// Replaces all discount factors.
pub fn set_discount_factors(&mut self, discount_factors: &[ADReal]) {
self.discount_factors.clear();
self.discount_factors.extend_from_slice(discount_factors);
}
/// Computes the discount factor at `date` by interpolating the curve.
///
/// # Errors
/// Returns an error if interpolation fails.
pub fn discount_factor(&self, date: Date) -> Result<ADReal> {
let year_fraction = ADReal::new(self.day_counter.year_fraction(self.reference_date, date));
let tmp_yfs = self
.times
.iter()
.copied()
.map(ADReal::new)
.collect::<Vec<ADReal>>();
let discount_factor =
self.interpolator
.interpolate(year_fraction, &tmp_yfs, &self.discount_factors, true)?;
Ok(discount_factor)
}
/// Computes the simply-compounded forward rate between two dates.
///
/// # Errors
/// Returns an error if the underlying discount-factor interpolation fails.
pub fn forward_rate(
&self,
start_date: Date,
end_date: Date,
comp: Compounding,
freq: Frequency,
) -> Result<ADReal> {
let discount_factor_to_star = self.discount_factor(start_date)?;
let discount_factor_to_end = self.discount_factor(end_date)?;
let comp_factor = discount_factor_to_star / discount_factor_to_end;
let t = self.day_counter.year_fraction(start_date, end_date);
Ok(InterestRate::<ADReal>::implied_rate(
comp_factor.into(),
self.day_counter,
comp,
freq,
t,
)?
.rate())
}
}