RustQuant_data/curves.rs
1// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2// RustQuant: A Rust library for quantitative finance tools.
3// Copyright (C) 2023 https://github.com/avhz
4// Dual licensed under Apache 2.0 and MIT.
5// See:
6// - LICENSE-APACHE.md
7// - LICENSE-MIT.md
8// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
9
10//! Curves module.
11//!
12//! This module contains the following curve structures:
13//! - [Curve](crate::data::curves::curve::Curve)
14//! - [DiscountCurve](crate::data::curves::discount_curve::DiscountCurve)
15//! - [SpotCurve](crate::data::curves::spot_curve::SpotCurve)
16//! - [ForwardCurve](crate::data::curves::forward_curve::ForwardCurve)
17//!
18//! Curves are constructed from a set of dates and rates, and can be used to
19//! interpolate rates for dates that are not in the curve.
20//! Currently, the curves are fit to a Nelson-Siegel-Svensson model via
21//! particle swarm optimization (thanks to the [argmin](https://docs.rs/argmin/latest/argmin/index.html) crate),
22//! and a log-cosh loss function, however these may change in the future.
23//!
24//! The curves are fit to the models *"lazily"* in the sense that no
25//! fitting takes place until the user requests a rate for a date that is not
26//! present in the curve. At that point, the curve is fit to the model and the
27//! rate is interpolated.
28
29use argmin::{
30 core::{CostFunction, Executor, State},
31 solver::particleswarm::ParticleSwarm,
32};
33use derive_builder::Builder;
34use plotly::{color::NamedColor, common::Marker, common::Mode, Plot, Scatter};
35use std::{collections::BTreeMap, hash::Hash, iter::zip};
36use time::Date;
37use RustQuant_math::{
38 interpolation::{ExponentialInterpolator, Interpolator, LinearInterpolator},
39 InterpolationIndex,
40};
41use RustQuant_stochastics::{CurveModel, NelsonSiegelSvensson};
42use RustQuant_time::{Calendar, DateRollingConvention, DayCountConvention};
43
44// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
45// BASE CURVE DATA STRUCTURE
46// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
47
48/// Curve index trait.
49pub trait CurveIndex: Ord + Hash + InterpolationIndex + Clone + Copy {}
50impl<T> CurveIndex for T where T: Ord + Hash + InterpolationIndex + Clone + Copy {}
51
52/// Curve data structure.
53#[derive(Clone, Debug, PartialEq, Default)]
54pub struct Curve<C>
55where
56 C: CurveIndex,
57{
58 /// The nodes of the curve.
59 pub nodes: BTreeMap<C, f64>,
60}
61
62macro_rules! impl_curve {
63 ($index:ty) => {
64 impl Curve<$index> {
65 /// Create a new curve.
66 pub fn new() -> Self {
67 Self {
68 nodes: BTreeMap::new(),
69 }
70 }
71
72 /// Get the first key in the curve.
73 pub fn first_key(&self) -> Option<&$index> {
74 self.nodes.keys().next()
75 }
76
77 /// Get the last key in the curve.
78 pub fn last_key(&self) -> Option<&$index> {
79 self.nodes.keys().next_back()
80 }
81
82 /// Get the keys of the curve.
83 pub fn keys(&self) -> Vec<$index> {
84 self.nodes.keys().cloned().collect()
85 }
86
87 /// Get the values of the curve.
88 pub fn values(&self) -> Vec<f64> {
89 self.nodes.values().cloned().collect()
90 }
91
92 /// Get the length of the curve.
93 pub fn len(&self) -> usize {
94 self.nodes.len()
95 }
96
97 /// Check if the curve is empty.
98 pub fn is_empty(&self) -> bool {
99 self.nodes.is_empty()
100 }
101
102 /// Get the first value in the curve.
103 pub fn first_value(&self) -> Option<&f64> {
104 self.nodes.values().next()
105 }
106
107 /// Get the last value in the curve.
108 pub fn last_value(&self) -> Option<&f64> {
109 self.nodes.values().next_back()
110 }
111
112 /// Add a node to the curve.
113 pub fn insert(&mut self, index: $index, value: f64) {
114 self.nodes.insert(index, value);
115 }
116
117 /// Get a value for a specific index.
118 pub fn get(&self, index: $index) -> Option<&f64> {
119 self.nodes.get(&index)
120 }
121
122 /// Get a mutable reference to a value for a specific index.
123 pub fn get_mut(&mut self, index: $index) -> Option<&mut f64> {
124 self.nodes.get_mut(&index)
125 }
126
127 /// Create a Curve from a vector of indices and values.
128 pub fn new_from_slice(indices: &[$index], values: &[f64]) -> Self {
129 let mut curve = Self::new();
130
131 for (index, value) in indices.iter().zip(values.iter()) {
132 curve.insert(*index, *value);
133 }
134
135 curve
136 }
137
138 /// Create a Curve from a function.
139 pub fn new_from_function<F>(f: F, indices: &[$index]) -> Self
140 where
141 F: Fn($index) -> f64,
142 {
143 let mut curve = Self::new();
144
145 for index in indices {
146 curve.insert(*index, f(*index));
147 }
148
149 curve
150 }
151
152 /// Create a Curve from a constant value.
153 pub fn new_from_constant(value: f64, indices: &[$index]) -> Self {
154 let mut curve = Self::new();
155
156 for index in indices {
157 curve.insert(*index, value);
158 }
159
160 curve
161 }
162
163 /// Get the bracketing indices for a specific index.
164 pub fn get_brackets(&self, index: $index) -> ($index, $index) {
165 let first = self.first_key().unwrap();
166 let last = self.last_key().unwrap();
167
168 if index <= *first {
169 return (*first, *first);
170 }
171
172 if index >= *last {
173 return (*last, *last);
174 }
175
176 let left = self.nodes.range(..index).next_back().unwrap().0;
177 let right = self.nodes.range(index..).next().unwrap().0;
178
179 return (*left, *right);
180 }
181
182 /// Shift the curve by a constant value.
183 pub fn shift(&mut self, shift: f64) {
184 for value in self.nodes.values_mut() {
185 *value += shift;
186 }
187 }
188
189 /// Interpolate the curve at a specific index.
190 ///
191 /// Note: This method modifies the curve by adding the interpolated value.
192 pub fn interpolate(&mut self, index: $index) -> f64 {
193 if self.nodes.contains_key(&index) {
194 return *self.nodes.get(&index).unwrap();
195 }
196
197 let xs: Vec<$index> = self.nodes.keys().cloned().collect();
198 let ys: Vec<f64> = self.nodes.values().cloned().collect();
199
200 let interpolator = LinearInterpolator::new(xs, ys).unwrap();
201
202 self.insert(index, interpolator.interpolate(index).unwrap());
203
204 *self.nodes.get(&index).unwrap()
205 }
206
207 /// Interpolate the curve at multiple indices.
208 ///
209 /// Note: This method modifies the curve by adding the interpolated values.
210 pub fn interpolate_many(&mut self, indices: &[$index]) {
211 let xs: Vec<$index> = self.nodes.keys().cloned().collect();
212 let ys: Vec<f64> = self.nodes.values().cloned().collect();
213
214 // let interpolator = LinearInterpolator::new(xs, ys).unwrap();
215 let interpolator = ExponentialInterpolator::new(xs, ys).unwrap();
216
217 for index in indices {
218 if !self.nodes.contains_key(index) {
219 self.insert(*index, interpolator.interpolate(*index).unwrap());
220 }
221 }
222 }
223
224 /// Plot the curve.
225 pub fn plot(&self) {
226 let mut plot = Plot::new();
227
228 let xs = self
229 .nodes
230 .keys()
231 .map(|x| x.to_string())
232 .collect::<Vec<String>>();
233
234 let ys = self.nodes.values().cloned().collect::<Vec<f64>>();
235
236 let trace = Scatter::new(xs, ys).mode(Mode::LinesMarkers);
237
238 plot.add_trace(trace);
239 plot.show();
240 // plot
241 }
242
243 /// Static method to plot multiple curves.
244 pub fn plot_many(curves: &[Self]) {
245 let mut plot = Plot::new();
246
247 for curve in curves {
248 let xs = curve
249 .nodes
250 .keys()
251 .map(|x| x.to_string())
252 .collect::<Vec<String>>();
253
254 let ys = curve.nodes.values().cloned().collect::<Vec<f64>>();
255
256 let trace = Scatter::new(xs, ys);
257
258 plot.add_trace(trace);
259 }
260
261 plot.show();
262 }
263 }
264 };
265}
266
267// Implement the Curve for temporal types.
268impl_curve!(time::Date);
269impl_curve!(time::Time);
270impl_curve!(time::OffsetDateTime);
271impl_curve!(time::PrimitiveDateTime);
272
273// Implement the Curve for unsigned integer types.
274// impl_curve!(u64);
275// impl_curve!(u32);
276// impl_curve!(u16);
277// impl_curve!(u8);
278// impl_curve!(usize);
279
280// Implement the Curve for signed integer types.
281// impl_curve!(i64);
282// impl_curve!(i32);
283// impl_curve!(i16);
284// impl_curve!(i8);
285// impl_curve!(isize);
286
287// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
288// CURVE RELATED CONSTANTS
289// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
290
291const CURVE_OPTIM_MAX_ITER: u64 = 69;
292const CURVE_OPTIM_SWARM_SIZE: usize = 1000;
293
294// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
295// MACRO TO IMPLEMENT SPECIFIC CURVES
296// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
297
298/// Generic trait for curves.
299pub trait Curves<C> {
300 /// Create a new curve from a set of `Date`s and rates (`f64`s).
301 fn new(dates: &[Date], rates: &[f64]) -> Self;
302
303 /// Get the initial date of the curve.
304 fn initial_date(&self) -> Date;
305
306 /// Get the terminal date of the curve.
307 fn terminal_date(&self) -> Date;
308
309 /// Get the rate for a specific date.
310 fn get_rate(&mut self, date: Date) -> f64;
311
312 /// Get multiple rates for a set of dates.
313 fn get_rates(&mut self, dates: &[Date]) -> Vec<f64>;
314
315 /// Insert a new rate into the curve.
316 fn insert_rate(&mut self, date: Date, rate: f64);
317
318 /// Fit the curve to a Nelson-Siegel-Svensson model.
319 fn fit(&mut self) -> Result<(), argmin::core::Error>;
320
321 /// Plot the curve.
322 fn plot(&self);
323}
324
325macro_rules! impl_specific_curve_cost_function {
326 ($curve:ident, $curve_function:ident) => {
327 impl<C> CostFunction for &$curve<Date, C>
328 where
329 C: Calendar,
330 {
331 type Param = Vec<f64>;
332 type Output = f64;
333
334 fn cost(&self, p: &Self::Param) -> Result<Self::Output, argmin::core::Error> {
335 let nss = RustQuant_stochastics::NelsonSiegelSvensson::new(
336 p[0], p[1], p[2], p[3], p[4], p[5],
337 );
338
339 let n = self.curve.len() as f64;
340 let x = self.curve.keys();
341 let y = self.curve.values();
342
343 let y_model = x
344 .iter()
345 .map(|date| nss.$curve_function(*date))
346 .collect::<Vec<f64>>();
347
348 let data = zip(y.iter(), y_model.iter());
349
350 // let mae = data.map(|(o, p)| (o - p).abs()).sum::<f64>() / n;
351 // let mse = data.map(|(o, p)| (o - p).powi(2)).sum::<f64>() / n;
352 let log_cosh_loss = data.map(|(o, p)| (p - o).cosh().ln()).sum::<f64>() / n;
353
354 Ok(log_cosh_loss)
355 }
356 }
357 };
358}
359
360macro_rules! impl_specific_curve {
361 ($curve:ident, $curve_function:ident) => {
362 impl<C> Curves<C> for $curve<Date, C>
363 where
364 C: Calendar + Clone,
365 {
366 #[doc = concat!("Fit the ", stringify!($curve))]
367 fn fit(&mut self) -> Result<(), argmin::core::Error> {
368 let zero = f64::EPSILON;
369
370 let bounds = [
371 (zero, 0.3), // Beta_0
372 (-0.3, 0.3), // Beta_1
373 (-1.0, 1.0), // Beta_2
374 (-1.0, 1.0), // Beta_3
375 (zero, 5.0), // Tau_1
376 (zero, 5.0), // Tau_2
377 ].to_vec().into_iter().map(|(a, b)| (a, b)).collect();
378
379 let model = self.clone();
380
381 let solver = ParticleSwarm::new(bounds, CURVE_OPTIM_SWARM_SIZE);//-0.3593 -0.7238 2.0289
382 // .with_inertia_factor(0.1)? // Inertia factor (w)
383 // .with_cognitive_factor(2.)? // Cognitive (personal) factor
384 // .with_social_factor(2.)?; // Social (global) factor
385
386 // let solver = SimulatedAnnealing::new(100_f64);
387 let executor =
388 Executor::new(&model, solver).configure(|state| state.max_iters(CURVE_OPTIM_MAX_ITER));
389
390 let result = executor.run()?;
391 let params = result.state().get_best_param().unwrap().position.to_vec();
392
393 self.nss = NelsonSiegelSvensson::new(
394 params[0], params[1], params[2], params[3], params[4], params[5],
395 );
396
397 self.fitted = true;
398 println!("TIME: {:?}", result.state().get_time());
399
400 Ok(())
401 }
402
403 #[doc = concat!("Creates a new ", stringify!($curve), " curve from a set of `Date`s and rates.")]
404 fn new(dates: &[Date], rates: &[f64]) -> Self {
405 assert!(dates.len() == rates.len());
406
407 Self {
408 curve: Curve::<Date>::new_from_slice(&dates, &rates),
409
410 calendar: None,
411 day_count_convention: None,
412 date_rolling_convention: None,
413 nss: NelsonSiegelSvensson::default(),
414 fitted: false,
415 fitted_curve: None,
416 }
417 }
418
419 #[doc = concat!("Get the initial date of the ", stringify!($curve))]
420 fn initial_date(&self) -> Date {
421 *self.curve.first_key().unwrap()
422 }
423
424 #[doc = concat!("Get the terminal date of the ", stringify!($curve))]
425 fn terminal_date(&self) -> Date {
426 *self.curve.last_key().unwrap()
427 }
428
429 #[doc = concat!("Insert a new rate into the ", stringify!($curve))]
430 fn insert_rate(&mut self, date: Date, rate: f64) {
431 self.curve.insert(date, rate);
432 }
433
434 /// Get the rate for a specific date.
435 ///
436 /// Note: If the date is not in the curve, the rate is interpolated,
437 /// and the interpolated rate is also stored in the curve.
438 /// This is why a mutable reference to the curve is required.
439 ///
440 /// Note: Interpolation is performed by fitting the curve
441 /// to a Nelson-Siegel-Svensson model (if not already fitted),
442 /// and then interpolating the rate for the given date.
443 fn get_rate(&mut self, date: Date) -> f64 {
444 match self.curve.get(date) {
445 Some(rate) => *rate,
446 None => {
447 if !self.fitted {
448 self.fit().unwrap();
449 self.fitted_curve = Some(Curve::<Date>::new());
450 }
451
452 let rate = self.nss.$curve_function(date);
453 self.insert_rate(date, rate);
454 self.fitted_curve.as_mut().unwrap().insert(date, rate);
455
456 rate
457 }
458 }
459 }
460
461 /// Get multiple rates for a set of dates.
462 ///
463 /// Note: If a date is not in the curve, the rate is interpolated,
464 /// and the interpolated rate is also stored in the curve.
465 /// This is why a mutable reference to the curve is required.
466 ///
467 /// Note: Interpolation is performed by fitting the curve
468 /// to a Nelson-Siegel-Svensson model (if not already fitted),
469 /// and then interpolating the rate for the given date.
470 fn get_rates(&mut self, dates: &[Date]) -> Vec<f64> {
471 dates.iter().map(|date| self.get_rate(*date)).collect()
472 }
473
474 #[doc = concat!("Plot the ", stringify!($curve))]
475 fn plot(&self) {
476 let mut plot = Plot::new();
477
478 let xs = self
479 .curve
480 .nodes
481 .keys()
482 .map(|x| x.to_string())
483 .collect::<Vec<String>>();
484
485 let ys = self.curve.nodes.values().cloned().collect::<Vec<f64>>();
486
487 let trace = Scatter::new(xs, ys).mode(Mode::Markers).name(
488 concat!(stringify!($curve)),
489 );
490
491 plot.add_trace(trace);
492
493 if self.fitted {
494 let xs = self
495 .fitted_curve
496 .as_ref()
497 .unwrap()
498 .nodes
499 .keys()
500 .map(|x| x.to_string())
501 .collect::<Vec<String>>();
502
503 let ys = self
504 .fitted_curve
505 .as_ref()
506 .unwrap()
507 .nodes
508 .values()
509 .cloned()
510 .collect::<Vec<f64>>();
511
512 let trace = Scatter::new(xs, ys)
513 .mode(Mode::LinesMarkers)
514 .marker(Marker::new().color(NamedColor::Red))
515 .name("Fitted curve");
516
517 plot.add_trace(trace);
518 }
519
520 plot.show();
521 }
522 }
523 };
524}
525
526// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
527// DISCOUNT CURVE
528// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
529
530/// Discount curve data structure.
531#[derive(Builder, Clone, Debug)]
532pub struct DiscountCurve<I, C>
533where
534 I: CurveIndex,
535 C: Calendar,
536{
537 /// Map of dates and rates.
538 pub curve: Curve<I>,
539
540 /// Calendar.
541 pub calendar: Option<C>,
542
543 /// Day count convention.
544 pub day_count_convention: Option<DayCountConvention>,
545
546 /// Date rolling convention.
547 pub date_rolling_convention: Option<DateRollingConvention>,
548
549 /// Nelson-Siegel-Svensson parameters.
550 /// Backend for fitting the curve to interpolate missing rates.
551 #[builder(default)]
552 pub nss: NelsonSiegelSvensson,
553
554 /// Whether the curve has been fitted.
555 #[builder(default = "false")]
556 pub fitted: bool,
557
558 /// Fitted curve.
559 #[builder(default)]
560 pub fitted_curve: Option<Curve<I>>,
561}
562
563impl_specific_curve_cost_function!(DiscountCurve, discount_factor);
564impl_specific_curve!(DiscountCurve, discount_factor);
565
566// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
567// SPOT CURVE
568// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
569
570/// Spot curve data structure.
571#[derive(Builder, Clone, Debug)]
572pub struct SpotCurve<I, C>
573where
574 I: CurveIndex,
575 C: Calendar,
576{
577 /// Map of dates and rates.
578 pub curve: Curve<I>,
579
580 /// Calendar.
581 pub calendar: Option<C>,
582
583 /// Day count convention.
584 pub day_count_convention: Option<DayCountConvention>,
585
586 /// Date rolling convention.
587 pub date_rolling_convention: Option<DateRollingConvention>,
588
589 /// Nelson-Siegel-Svensson parameters.
590 /// Backend for fitting the curve to interpolate missing rates.
591 #[builder(default)]
592 pub nss: NelsonSiegelSvensson,
593
594 /// Whether the curve has been fitted.
595 #[builder(default = "false")]
596 pub fitted: bool,
597
598 /// Fitted curve.
599 #[builder(default)]
600 pub fitted_curve: Option<Curve<I>>,
601}
602
603impl_specific_curve_cost_function!(SpotCurve, spot_rate);
604impl_specific_curve!(SpotCurve, spot_rate);
605
606// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
607// FORWARD CURVE
608// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
609
610/// Forward curve data structure.
611#[derive(Builder, Clone, Debug)]
612pub struct ForwardCurve<I, C>
613where
614 I: CurveIndex,
615 C: Calendar,
616{
617 /// Map of dates and rates.
618 pub curve: Curve<I>,
619
620 /// Calendar.
621 pub calendar: Option<C>,
622
623 /// Day count convention.
624 pub day_count_convention: Option<DayCountConvention>,
625
626 /// Date rolling convention.
627 pub date_rolling_convention: Option<DateRollingConvention>,
628
629 /// Nelson-Siegel-Svensson parameters.
630 /// Backend for fitting the curve to interpolate missing rates.
631 #[builder(default)]
632 pub nss: NelsonSiegelSvensson,
633
634 /// Whether the curve has been fitted.
635 #[builder(default = "false")]
636 pub fitted: bool,
637
638 /// Fitted curve.
639 #[builder(default)]
640 pub fitted_curve: Option<Curve<I>>,
641}
642
643impl_specific_curve_cost_function!(ForwardCurve, forward_rate);
644impl_specific_curve!(ForwardCurve, forward_rate);
645
646// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
647// FLAT CURVE
648// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
649
650/// Flat curve data structure.
651#[derive(Builder, Clone, Debug)]
652pub struct FlatCurve<C>
653where
654 C: Calendar,
655{
656 /// Rate of the curve.
657 pub rate: f64,
658
659 /// Calendar.
660 pub calendar: Option<C>,
661
662 /// Day count convention.
663 pub day_count_convention: Option<DayCountConvention>,
664
665 /// Date rolling convention.
666 pub date_rolling_convention: Option<DateRollingConvention>,
667}
668
669impl<C> FlatCurve<C>
670where
671 C: Calendar,
672{
673 /// Create a new flat curve.
674 pub fn new_flat_curve(rate: f64) -> Self {
675 Self {
676 rate,
677 calendar: None,
678 day_count_convention: None,
679 date_rolling_convention: None,
680 }
681 }
682
683 /// Get the rate of the curve.
684 pub fn get_rate(&self) -> f64 {
685 self.rate
686 }
687
688 /// Get rate for a specific date.
689 pub fn get_rate_for_date(&self, _date: Date) -> f64 {
690 self.rate
691 }
692
693 /// Get rates for multiple dates.
694 pub fn get_rates_for_dates(&self, dates: &[Date]) -> Vec<f64> {
695 vec![self.rate; dates.len()]
696 }
697}
698
699// impl<C> Curves<C> for FlatCurve<C>
700// where
701// C: Calendar,
702// {
703// /// NOT TO BE USED. Prefer the `new_flat_curve()` method.
704// fn new(dates: &[Date], rates: &[f64]) -> Self {
705// unimplemented!("FlatCurve does not support this method. Use `new_flat_curve()` instead.")
706// }
707
708// fn initial_date(&self) -> Date {
709// Date::MIN
710// }
711
712// fn terminal_date(&self) -> Date {
713// Date::MAX
714// }
715
716// fn get_rate(&mut self, date: Date) -> f64 {
717// self.rate
718// }
719
720// fn get_rates(&mut self, dates: &[Date]) -> Vec<f64> {
721// vec![self.rate; dates.len()]
722// }
723
724// fn insert_rate(&mut self, date: Date, rate: f64) {
725// todo!()
726// }
727
728// fn fit(&mut self) -> Result<(), argmin::core::Error> {
729// unimplemented!()
730// }
731
732// fn plot(&self) {
733// unimplemented!()
734// }
735// }
736
737// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
738// Base Curve Trait
739// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
740
741// /// Base trait for all curves to implement.
742// pub trait Curve {
743// /// Initial date of the curve.
744// fn initial_date(&self) -> Date;
745
746// /// Final date of the curve.
747// fn terminal_date(&self) -> Date;
748
749// /// Updates the rate for the given date.
750// fn update_rate(&mut self, date: Date, rate: f64);
751
752// /// Create a new curve from a set of dates and rates.
753// fn from_dates_and_rates(dates: &[Date], rates: &[f64]) -> Self;
754
755// /// Create a new curve from an initial date, a set of rates, and a set of
756// /// durations.
757// /// The dates are calculated as the initial date plus the duration, thus
758// /// there must be:
759// /// - One initial date
760// /// - n rates
761// /// - n-1 durations
762// fn from_initial_date_rates_and_durations(
763// initial_date: Date,
764// rates: &[f64],
765// durations: &[Duration],
766// ) -> Self;
767
768// /// Function to find the interval of dates that contains the given date.
769// /// The interval is defined by the two dates that are closest to the given
770// /// date, just before and just after.
771// fn find_date_interval(&self, date: Date) -> (Date, Date);
772
773// /// Returns the rate for the given date, using linear interpolation for
774// /// dates between the curve's initial and terminal dates.
775// /// If the date is outside the curve's range, we panic.
776// ///
777// /// We use the following formula for the interpolation:
778// ///
779// /// $$
780// /// y = \frac{y_0 (x_1 - x) + y_1 (x - x_0)}{x_1 - x_0}
781// /// $$
782// ///
783// /// Note: there must be at least two points in the curve, otherwise
784// /// we consider the curve to be a flat rate, and return the same rate
785// /// for all dates.
786// fn rate(&self, date: Date) -> f64;
787
788// /// Returns the discount factor for the given date.
789// /// This is a convenience function that calls [`rate`](Curve::rate) to get the rate for
790// /// the given date, and then calculates the discount factor using the
791// /// formula:
792// /// $$
793// /// p(t) = e^{- r \cdot t}
794// /// $$
795// fn discount_factor(&self, date: Date) -> f64 {
796// let t = DayCountConvention::default().day_count_factor(self.initial_date(), date);
797
798// f64::exp(-self.rate(date) * t)
799// }
800
801// /// Returns multiple discount factors for the given dates.
802// /// This is a convenience function that calls [`discount_factor`](Curve::discount_factor) for each
803// /// date.
804// fn discount_factors(&self, dates: &[Date]) -> Vec<f64> {
805// dates
806// .iter()
807// .map(|date| self.discount_factor(*date))
808// .collect::<Vec<f64>>()
809// }
810// }
811
812// #[allow(clippy::module_name_repetitions)]
813// /// Yield curve struct.
814// pub struct YieldCurve {
815// /// Map of dates and rates.
816// /// The dates are the keys and the rates are the values.
817// /// The reason for using a [BTreeMap] is that it is sorted by date,
818// /// which makes sense for a term structure.
819// pub rates: BTreeMap<Date, f64>,
820// // /// A model for the curve.
821// // pub model: Option<M>,
822// }
823
824// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
825// Unit tests
826// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
827
828#[cfg(test)]
829mod tests_curves {
830 // use super::*;
831 // use crate::time::today;
832 // use time::Duration;
833 // use time::OffsetDateTime;
834
835 // #[test]
836 // fn test_discount_curve_creation() {
837 // let dates = [today() + Duration::days(30), today() + Duration::days(60)];
838 // let rates = [0.025, 0.03];
839
840 // let discount_curve = DiscountCurve::new(&dates, &rates);
841
842 // assert_eq!(discount_curve.rates, rates);
843 // }
844
845 // #[test]
846 // fn test_discount_curve_initial_date() {
847 // let dates = [
848 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30),
849 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60),
850 // ];
851
852 // let rates = [0.025, 0.03];
853
854 // let discount_curve = DiscountCurve::new(&dates, &rates);
855 // let initial_date = discount_curve.initial_date();
856
857 // assert_eq!(
858 // initial_date,
859 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30)
860 // );
861 // }
862
863 // #[test]
864 // fn test_discount_curve_final_date() {
865 // let dates = [
866 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30),
867 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60),
868 // ];
869
870 // let rates = [0.025, 0.03];
871
872 // let discount_curve = DiscountCurve::new(&dates, &rates);
873 // let final_date = discount_curve.terminal_date();
874
875 // assert_eq!(
876 // final_date,
877 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60)
878 // );
879 // }
880
881 // #[test]
882 // fn test_find_date_interval() {
883 // let dates = [
884 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30),
885 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60),
886 // ];
887
888 // let rates = [0.025, 0.03];
889
890 // let discount_curve = DiscountCurve::new(&dates, &rates);
891
892 // let date1 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30);
893 // let date2 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(45);
894 // let date3 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60);
895
896 // let interval1 = discount_curve.find_date_interval(date1);
897 // let interval2 = discount_curve.find_date_interval(date2);
898 // let interval3 = discount_curve.find_date_interval(date3);
899
900 // assert_eq!(interval1, (date1, date1));
901 // assert_eq!(interval2, (date1, date3));
902 // assert_eq!(interval3, (date3, date3));
903 // }
904
905 // #[allow(clippy::similar_names)]
906 // #[test]
907 // fn test_discount_curve_discount_factor() {
908 // // Initial date of the curve.
909 // let t0 = OffsetDateTime::UNIX_EPOCH.date();
910
911 // // Create a discount curve with 8 points.
912 // let rate_vec = vec![0.025, 0.03, 0.035, 0.04, 0.045, 0.05, 0.055, 0.06];
913 // let date_vec = vec![
914 // t0 + Duration::days(30),
915 // t0 + Duration::days(60),
916 // t0 + Duration::days(90),
917 // t0 + Duration::days(120),
918 // t0 + Duration::days(150),
919 // t0 + Duration::days(180),
920 // t0 + Duration::days(210),
921 // t0 + Duration::days(360),
922 // ];
923
924 // let discount_curve = DiscountCurve::from_dates_and_rates(&date_vec, &rate_vec);
925
926 // println!("Curve: {:?}", discount_curve.rates);
927
928 // // Test the discount factor for a dates inside the curve's range.
929 // let date1 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(45);
930 // let date2 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(80);
931 // let date3 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(250);
932
933 // let df1 = discount_curve.discount_factor(date1);
934 // let df2 = discount_curve.discount_factor(date2);
935 // let df3 = discount_curve.discount_factor(date3);
936
937 // println!("df1: {:?}", df1);
938 // println!("df2: {:?}", df2);
939 // println!("df3: {:?}", df3);
940
941 // assert!(df1 > 0.0 && df1 < 1.0 && df2 > 0.0 && df2 < 1.0 && df3 > 0.0 && df3 < 1.0);
942
943 // assert!(df1 > df2 && df2 > df3);
944 // }
945
946 // #[test]
947 // fn test_discount_curve_creation() {
948 // let dates = [today() + Duration::days(30), today() + Duration::days(60)];
949 // let rates = [0.025, 0.03];
950
951 // let discount_curve = ForwardCurve::new(&dates, &rates);
952
953 // assert_eq!(discount_curve.rates, rates);
954 // }
955
956 // #[test]
957 // fn test_discount_curve_initial_date() {
958 // let dates = [
959 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30),
960 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60),
961 // ];
962
963 // let rates = [0.025, 0.03];
964
965 // let discount_curve = ForwardCurve::new(&dates, &rates);
966 // let initial_date = discount_curve.initial_date();
967
968 // assert_eq!(
969 // initial_date,
970 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30)
971 // );
972 // }
973
974 // #[test]
975 // fn test_discount_curve_final_date() {
976 // let dates = [
977 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30),
978 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60),
979 // ];
980
981 // let rates = [0.025, 0.03];
982
983 // let discount_curve = ForwardCurve::new(&dates, &rates);
984 // let final_date = discount_curve.terminal_date();
985
986 // assert_eq!(
987 // final_date,
988 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60)
989 // );
990 // }
991
992 // #[test]
993 // fn test_find_date_interval() {
994 // let dates = [
995 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30),
996 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60),
997 // ];
998
999 // let rates = [0.025, 0.03];
1000
1001 // let discount_curve = ForwardCurve::new(&dates, &rates);
1002
1003 // let date1 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30);
1004 // let date2 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(45);
1005 // let date3 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60);
1006
1007 // let interval1 = discount_curve.find_date_interval(date1);
1008 // let interval2 = discount_curve.find_date_interval(date2);
1009 // let interval3 = discount_curve.find_date_interval(date3);
1010
1011 // assert_eq!(interval1, (date1, date1));
1012 // assert_eq!(interval2, (date1, date3));
1013 // assert_eq!(interval3, (date3, date3));
1014 // }
1015
1016 // #[allow(clippy::similar_names)]
1017 // #[test]
1018 // fn test_discount_curve_discount_factor() {
1019 // // Initial date of the curve.
1020 // let t0 = OffsetDateTime::UNIX_EPOCH.date();
1021
1022 // // Create a discount curve with 8 points.
1023 // let rate_vec = vec![0.025, 0.03, 0.035, 0.04, 0.045, 0.05, 0.055, 0.06];
1024 // let date_vec = vec![
1025 // t0 + Duration::days(30),
1026 // t0 + Duration::days(60),
1027 // t0 + Duration::days(90),
1028 // t0 + Duration::days(120),
1029 // t0 + Duration::days(150),
1030 // t0 + Duration::days(180),
1031 // t0 + Duration::days(210),
1032 // t0 + Duration::days(360),
1033 // ];
1034
1035 // let discount_curve = ForwardCurve::from_dates_and_rates(&date_vec, &rate_vec);
1036
1037 // println!("Curve: {:?}", discount_curve.rates);
1038
1039 // // Test the discount factor for a dates inside the curve's range.
1040 // let date1 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(45);
1041 // let date2 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(80);
1042 // let date3 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(250);
1043
1044 // let df1 = discount_curve.discount_factor(date1);
1045 // let df2 = discount_curve.discount_factor(date2);
1046 // let df3 = discount_curve.discount_factor(date3);
1047
1048 // println!("df1: {:?}", df1);
1049 // println!("df2: {:?}", df2);
1050 // println!("df3: {:?}", df3);
1051
1052 // assert!(df1 > 0.0 && df1 < 1.0 && df2 > 0.0 && df2 < 1.0 && df3 > 0.0 && df3 < 1.0);
1053
1054 // assert!(df1 > df2 && df2 > df3);
1055 // }
1056
1057 // #[test]
1058 // fn test_discount_curve_creation() {
1059 // let dates = [today() + Duration::days(30), today() + Duration::days(60)];
1060 // let rates = [0.025, 0.03];
1061
1062 // let discount_curve = SpotCurve::new(&dates, &rates);
1063
1064 // assert_eq!(discount_curve.rates, rates);
1065 // }
1066
1067 // #[test]
1068 // fn test_discount_curve_initial_date() {
1069 // let dates = [
1070 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30),
1071 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60),
1072 // ];
1073
1074 // let rates = [0.025, 0.03];
1075
1076 // let discount_curve = SpotCurve::new(&dates, &rates);
1077 // let initial_date = discount_curve.initial_date();
1078
1079 // assert_eq!(
1080 // initial_date,
1081 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30)
1082 // );
1083 // }
1084
1085 // #[test]
1086 // fn test_discount_curve_final_date() {
1087 // let dates = [
1088 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30),
1089 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60),
1090 // ];
1091
1092 // let rates = [0.025, 0.03];
1093
1094 // let discount_curve = SpotCurve::new(&dates, &rates);
1095 // let final_date = discount_curve.terminal_date();
1096
1097 // assert_eq!(
1098 // final_date,
1099 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60)
1100 // );
1101 // }
1102
1103 // #[test]
1104 // fn test_find_date_interval() {
1105 // let dates = [
1106 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30),
1107 // OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60),
1108 // ];
1109
1110 // let rates = [0.025, 0.03];
1111
1112 // let discount_curve = SpotCurve::new(&dates, &rates);
1113
1114 // let date1 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(30);
1115 // let date2 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(45);
1116 // let date3 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(60);
1117
1118 // let interval1 = discount_curve.find_date_interval(date1);
1119 // let interval2 = discount_curve.find_date_interval(date2);
1120 // let interval3 = discount_curve.find_date_interval(date3);
1121
1122 // assert_eq!(interval1, (date1, date1));
1123 // assert_eq!(interval2, (date1, date3));
1124 // assert_eq!(interval3, (date3, date3));
1125 // }
1126
1127 // #[allow(clippy::similar_names)]
1128 // #[test]
1129 // fn test_discount_curve_discount_factor() {
1130 // // Initial date of the curve.
1131 // let t0 = OffsetDateTime::UNIX_EPOCH.date();
1132
1133 // // Create a discount curve with 8 points.
1134 // let rate_vec = vec![0.025, 0.03, 0.035, 0.04, 0.045, 0.05, 0.055, 0.06];
1135 // let date_vec = vec![
1136 // t0 + Duration::days(30),
1137 // t0 + Duration::days(60),
1138 // t0 + Duration::days(90),
1139 // t0 + Duration::days(120),
1140 // t0 + Duration::days(150),
1141 // t0 + Duration::days(180),
1142 // t0 + Duration::days(210),
1143 // t0 + Duration::days(360),
1144 // ];
1145
1146 // let discount_curve = SpotCurve::new(&date_vec, &rate_vec);
1147
1148 // println!("Curve: {:?}", discount_curve.rates);
1149
1150 // // Test the discount factor for a dates inside the curve's range.
1151 // let date1 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(45);
1152 // let date2 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(80);
1153 // let date3 = OffsetDateTime::UNIX_EPOCH.date() + Duration::days(250);
1154
1155 // let df1 = discount_curve.discount_factor(date1);
1156 // let df2 = discount_curve.discount_factor(date2);
1157 // let df3 = discount_curve.discount_factor(date3);
1158
1159 // println!("df1: {:?}", df1);
1160 // println!("df2: {:?}", df2);
1161 // println!("df3: {:?}", df3);
1162
1163 // assert!(df1 > 0.0 && df1 < 1.0 && df2 > 0.0 && df2 < 1.0 && df3 > 0.0 && df3 < 1.0);
1164
1165 // assert!(df1 > df2 && df2 > df3);
1166 // }
1167}