quantsupport 0.1.0

Rust library for fixed-income, derivative pricing and risk analytics.
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
use crate::{
    ad::adreal::{ADReal, Const, FloatExt, IsReal},
    core::{elements::curveelement::ADCurveElement, pillars::Pillars},
    math::interpolation::interpolator::{Interpolate, Interpolator},
    rates::{
        compounding::Compounding, interestrate::InterestRate,
        yieldtermstructure::interestratestermstructure::InterestRatesTermStructure,
    },
    time::{date::Date, daycounter::DayCounter, enums::Frequency},
    utils::errors::{QSError, Result},
};

/// A discount factors term structure.
///
/// ## Example
/// ```rust
/// use quantsupport::prelude::*;
///
/// let dates = vec![
///     Date::new(2020, 1, 1),
///     Date::new(2020, 4, 1),
///     Date::new(2020, 7, 1),
///     Date::new(2020, 10, 1),
///     Date::new(2021, 1, 1),
/// ];
///
/// let discount_factors = vec![1.0, 0.99, 0.98, 0.97, 0.96];
/// let day_counter = DayCounter::Actual360;
///
/// let discount_term_structure = DiscountTermStructure::<f64>::new(
///    dates.clone(),
///    discount_factors.clone(),
///    day_counter,
///    Interpolator::Linear,
///    true).unwrap();
///
/// assert_eq!(
///     discount_term_structure.dates().clone(),
///     dates
/// );
/// assert_eq!(
///     discount_term_structure.discount_factors().clone(),
///     discount_factors
/// );
///  ```

#[derive(Clone)]
pub struct DiscountTermStructure<T>
where
    T: IsReal,
{
    reference_date: Date,
    dates: Vec<Date>,
    year_fractions: Vec<f64>,
    discount_factors: Vec<T>,
    interpolator: Interpolator,
    day_counter: DayCounter,
    enable_extrapolation: bool,
    pillar_labels: Option<Vec<String>>,
    pillar_values: Option<Vec<T>>,
}

impl<T> DiscountTermStructure<T>
where
    T: IsReal,
{
    /// Returns a reference to the vector of dates.
    #[must_use]
    pub const fn dates(&self) -> &Vec<Date> {
        &self.dates
    }

    /// Returns a reference to the vector of discount factors.
    #[must_use]
    pub const fn discount_factors(&self) -> &Vec<T> {
        &self.discount_factors
    }

    /// Returns the day counter convention used.
    #[must_use]
    pub const fn day_counter(&self) -> DayCounter {
        self.day_counter
    }

    /// Returns whether extrapolation is enabled.
    #[must_use]
    pub const fn enable_extrapolation(&self) -> bool {
        self.enable_extrapolation
    }

    /// Returns the interpolator used.
    #[must_use]
    pub const fn interpolator(&self) -> Interpolator {
        self.interpolator
    }

    /// Returns the reference date of the term structure.
    ///
    /// ## Errors
    /// Returns an error if the reference date is not set.
    pub fn with_pillar_labels(mut self, pillar_labels: Vec<String>) -> Result<Self> {
        let expected_len = self
            .pillar_values
            .as_ref()
            .map_or(self.discount_factors.len(), Vec::len);
        if pillar_labels.len() != expected_len {
            return Err(QSError::InvalidValueErr(
                "Pillar labels need to have the same size as the exposed pillar values".into(),
            ));
        }
        self.pillar_labels = Some(pillar_labels);
        Ok(self)
    }

    /// Overrides the values exposed through the [`Pillars`] interface.
    ///
    /// # Errors
    /// Returns an error if the provided values do not match the number of curve nodes.
    pub fn with_pillar_values(mut self, pillar_values: Vec<T>) -> Result<Self> {
        if let Some(pillar_labels) = &self.pillar_labels {
            if pillar_values.len() != pillar_labels.len() {
                return Err(QSError::InvalidValueErr(
                    "Pillar values need to have the same size as pillar labels".into(),
                ));
            }
        }
        if pillar_values.is_empty() {
            return Err(QSError::InvalidValueErr(
                "Pillar values cannot be empty".into(),
            ));
        }
        self.pillar_values = Some(pillar_values);
        Ok(self)
    }
}

impl DiscountTermStructure<f64> {
    /// Creates a new `DiscountTermStructure` with the given dates, discount factors, day counter, interpolator, and extrapolation setting.
    ///
    /// ## Arguments
    ///
    /// * `dates` - Vector of dates for the discount factors
    /// * `discount_factors` - Vector of discount factors corresponding to the dates
    /// * `day_counter` - Day counter convention to use for year fraction calculations
    /// * `interpolator` - Interpolation method to use
    /// * `enable_extrapolation` - Whether to allow extrapolation beyond the given dates
    ///
    /// ## Errors
    ///
    /// Returns an error if dates and discount factors have different lengths or if the first discount factor is not 1.0.
    pub fn new(
        dates: Vec<Date>,
        discount_factors: Vec<f64>,
        day_counter: DayCounter,
        interpolator: Interpolator,
        enable_extrapolation: bool,
    ) -> Result<Self> {
        // check if year_fractions and discount_factors have the same size
        if dates.len() != discount_factors.len() {
            return Err(QSError::InvalidValueErr(
                "Dates and discount_factors need to have the same size".to_string(),
            ));
        }

        // order dates y discount_factors
        let mut zipped = dates.into_iter().zip(discount_factors).collect::<Vec<_>>();
        zipped.sort_by_key(|a| a.0);
        let (dates, discount_factors): (Vec<Date>, Vec<f64>) = zipped.into_iter().unzip();

        // discount_factors[0] needs to be 1.0
        if (discount_factors[0] - 1.0).abs() > 1e-12 {
            return Err(QSError::InvalidValueErr(
                "First discount factor needs to be 1.0".to_string(),
            ));
        }
        let reference_date = dates[0];
        let year_fractions: Vec<f64> = dates
            .iter()
            .map(|x| day_counter.year_fraction(reference_date, *x))
            .collect();

        Ok(Self {
            reference_date,
            dates,
            year_fractions,
            discount_factors,
            interpolator,
            day_counter,
            enable_extrapolation,
            pillar_labels: None,
            pillar_values: None,
        })
    }
}

impl DiscountTermStructure<ADReal> {
    /// Creates a new `DiscountTermStructure` with the given dates, discount factors, day counter, interpolator, and extrapolation setting.
    ///
    /// # Arguments
    ///
    /// * `dates` - Vector of dates for the discount factors
    /// * `discount_factors` - Vector of discount factors corresponding to the dates
    /// * `day_counter` - Day counter convention to use for year fraction calculations
    /// * `interpolator` - Interpolation method to use
    /// * `enable_extrapolation` - Whether to allow extrapolation beyond the given dates
    ///
    /// # Errors
    ///
    /// Returns an error if dates and discount factors have different lengths or if the first discount factor is not 1.0.
    pub fn new(
        dates: Vec<Date>,
        discount_factors: Vec<ADReal>,
        day_counter: DayCounter,
        interpolator: Interpolator,
        enable_extrapolation: bool,
    ) -> Result<Self> {
        // check if year_fractions and discount_factors have the same size
        if dates.len() != discount_factors.len() {
            return Err(QSError::InvalidValueErr(
                "Dates and discount_factors need to have the same size".to_string(),
            ));
        }

        // order dates y discount_factors
        let mut zipped = dates.into_iter().zip(discount_factors).collect::<Vec<_>>();
        zipped.sort_by_key(|a| a.0);
        let (dates, discount_factors): (Vec<Date>, Vec<ADReal>) = zipped.into_iter().unzip();

        // discount_factors[0] needs to be 1.0
        if (discount_factors[0] - Const::one()).abs() > 1e-12 {
            return Err(QSError::InvalidValueErr(
                "First discount factor needs to be 1.0".to_string(),
            ));
        }
        let reference_date = dates[0];
        let year_fractions: Vec<f64> = dates
            .iter()
            .map(|x| day_counter.year_fraction(reference_date, *x))
            .collect();

        Ok(Self {
            reference_date,
            dates,
            year_fractions,
            discount_factors,
            interpolator,
            day_counter,
            enable_extrapolation,
            pillar_labels: None,
            pillar_values: None,
        })
    }
}

impl Pillars<ADReal> for DiscountTermStructure<ADReal> {
    fn pillars(&self) -> Option<Vec<(String, &ADReal)>> {
        self.pillar_labels.as_ref().map(|labels| {
            let values = self
                .pillar_values
                .as_ref()
                .unwrap_or(&self.discount_factors);
            labels.iter().cloned().zip(values.iter()).collect()
        })
    }

    fn pillar_labels(&self) -> Option<Vec<String>> {
        self.pillar_labels.clone()
    }

    fn put_pillars_on_tape(&mut self) {
        if let Some(pillar_values) = self.pillar_values.as_mut() {
            pillar_values.iter_mut().for_each(ADReal::put_on_tape);
        } else {
            self.discount_factors
                .iter_mut()
                .for_each(ADReal::put_on_tape);
        }
    }
}

impl InterestRatesTermStructure<f64> for DiscountTermStructure<f64> {
    fn reference_date(&self) -> Date {
        self.reference_date
    }

    fn discount_factor(&self, date: Date) -> Result<f64> {
        if date < self.reference_date() {
            return Err(QSError::InvalidValueErr(
                "Date needs to be greater than reference date".to_string(),
            ));
        }
        if date == self.reference_date() {
            return Ok(1.0);
        }

        let year_fraction = self
            .day_counter()
            .year_fraction(self.reference_date(), date);

        let discount_factor = self.interpolator.interpolate(
            year_fraction,
            &self.year_fractions,
            &self.discount_factors,
            self.enable_extrapolation,
        )?;
        Ok(discount_factor)
    }

    fn forward_rate(
        &self,
        start_date: Date,
        end_date: Date,
        comp: Compounding,
        freq: Frequency,
    ) -> Result<f64> {
        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::<f64>::implied_rate(comp_factor, self.day_counter(), comp, freq, t)?
                .rate(),
        )
    }
}

impl InterestRatesTermStructure<ADReal> for DiscountTermStructure<ADReal> {
    fn reference_date(&self) -> Date {
        self.reference_date
    }
    fn discount_factor(&self, date: Date) -> Result<ADReal> {
        if date < self.reference_date() {
            return Err(QSError::InvalidValueErr(
                "Date needs to be greater than reference date".to_string(),
            ));
        }
        if date == self.reference_date() {
            return Ok(ADReal::one());
        }

        let year_fraction = ADReal::new(
            self.day_counter()
                .year_fraction(self.reference_date(), date),
        );

        let tmp_yfs = self
            .year_fractions
            .iter()
            .copied()
            .map(ADReal::new)
            .collect::<Vec<ADReal>>();

        let discount_factor = self.interpolator.interpolate(
            year_fraction,
            &tmp_yfs,
            &self.discount_factors,
            self.enable_extrapolation,
        )?;
        Ok(discount_factor)
    }

    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())
    }
}

impl ADCurveElement for DiscountTermStructure<ADReal> {}

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

    #[test]
    fn test_year_fractions() {
        let dates = vec![
            Date::new(2020, 1, 1),
            Date::new(2020, 4, 1),
            Date::new(2020, 7, 1),
            Date::new(2020, 10, 1),
            Date::new(2021, 1, 1),
        ];
        let discount_factors = vec![1.0, 0.99, 0.98, 0.97, 0.96];
        let day_counter = DayCounter::Actual360;

        let discount_term_structure = DiscountTermStructure::<f64>::new(
            dates,
            discount_factors,
            day_counter,
            Interpolator::Linear,
            true,
        )
        .unwrap_or_else(|e| {
            panic!("DiscountTermStructure::new should succeed in test_year_fractions: {e}")
        });

        assert_eq!(
            discount_term_structure.dates(),
            &vec![
                Date::new(2020, 1, 1),
                Date::new(2020, 4, 1),
                Date::new(2020, 7, 1),
                Date::new(2020, 10, 1),
                Date::new(2021, 1, 1)
            ]
        );
    }

    #[test]
    fn test_discount_dactors() {
        let dates = vec![
            Date::new(2020, 1, 1),
            Date::new(2020, 4, 1),
            Date::new(2020, 7, 1),
            Date::new(2020, 10, 1),
            Date::new(2021, 1, 1),
        ];
        let discount_factors = vec![1.0, 0.99, 0.98, 0.97, 0.96];
        let day_counter = DayCounter::Actual360;

        let discount_term_structure = DiscountTermStructure::<f64>::new(
            dates,
            discount_factors,
            day_counter,
            Interpolator::Linear,
            true,
        )
        .unwrap_or_else(|e| {
            panic!("DiscountTermStructure::new should succeed in test_discount_dactors: {e}")
        });

        assert_eq!(
            discount_term_structure.discount_factors(),
            &vec![1.0, 0.99, 0.98, 0.97, 0.96]
        );
    }

    #[test]
    fn test_reference_date() {
        let dates = vec![
            Date::new(2020, 1, 1),
            Date::new(2020, 4, 1),
            Date::new(2020, 7, 1),
            Date::new(2020, 10, 1),
            Date::new(2021, 1, 1),
        ];
        let discount_factors = vec![1.0, 0.99, 0.98, 0.97, 0.96];
        let day_counter = DayCounter::Actual360;

        let discount_term_structure = DiscountTermStructure::<f64>::new(
            dates,
            discount_factors,
            day_counter,
            Interpolator::Linear,
            true,
        )
        .unwrap_or_else(|e| {
            panic!("DiscountTermStructure::new should succeed in test_reference_date: {e}")
        });

        assert_eq!(
            discount_term_structure.reference_date(),
            Date::new(2020, 1, 1)
        );
    }

    #[test]
    fn test_interpolation() {
        let dates = vec![
            Date::new(2020, 1, 1),
            Date::new(2020, 4, 1),
            Date::new(2020, 7, 1),
            Date::new(2020, 10, 1),
            Date::new(2021, 1, 1),
        ];
        let discount_factors = vec![1.0, 0.99, 0.98, 0.97, 0.96];
        let day_counter = DayCounter::Actual360;

        let discount_term_structure = DiscountTermStructure::<f64>::new(
            dates,
            discount_factors,
            day_counter,
            Interpolator::Linear,
            true,
        )
        .unwrap_or_else(|e| {
            panic!("DiscountTermStructure::new should succeed in test_interpolation: {e}")
        });

        let df = discount_term_structure
            .discount_factor(Date::new(2020, 6, 1))
            .unwrap_or_else(|e| panic!("discount_factor failed in test_interpolation: {e}"));
        assert!((df - 0.9832967032967033).abs() < 1e-8);
    }

    #[test]

    fn test_forward_rate() {
        let dates = vec![
            Date::new(2020, 1, 1),
            Date::new(2020, 4, 1),
            Date::new(2020, 7, 1),
            Date::new(2020, 10, 1),
            Date::new(2021, 1, 1),
        ];
        let discount_factors = vec![1.0, 0.99, 0.98, 0.97, 0.96];
        let day_counter = DayCounter::Actual360;

        let discount_term_structure = DiscountTermStructure::<f64>::new(
            dates,
            discount_factors,
            day_counter,
            Interpolator::Linear,
            true,
        )
        .unwrap_or_else(|e| {
            panic!("DiscountTermStructure::new should succeed in test_forward_rate: {e}")
        });

        let comp = Compounding::Simple;
        let freq = Frequency::Annual;

        let fwd = discount_term_structure
            .forward_rate(Date::new(2020, 1, 1), Date::new(2020, 12, 31), comp, freq)
            .unwrap_or_else(|e| panic!("forward_rate failed in test_forward_rate: {e}"));
        assert!((fwd - 0.04097957689796514).abs() < 1e-8);
        println!("forward_rate: {fwd}");
    }

    #[test]
    fn order_dates() {
        let dates = vec![
            Date::new(2020, 1, 1),
            Date::new(2020, 4, 1),
            Date::new(2020, 7, 1),
            Date::new(2020, 10, 1),
            Date::new(2021, 1, 1),
        ];
        let discount_factors = vec![0.99, 0.98, 0.97, 0.96, 1.0];
        let day_counter = DayCounter::Actual360;

        let discount_term_structure = DiscountTermStructure::<f64>::new(
            dates,
            discount_factors,
            day_counter,
            Interpolator::Linear,
            true,
        );

        assert!(discount_term_structure.is_err());
    }
}