quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! Piecewise yield curve bootstrapping from market rate helpers.

use crate::termstructures::interpolated_discount_curve::{CurveError, InterpolatedDiscountCurve};
use crate::termstructures::yield_term_structure::YieldTermStructure;
use crate::time::calendar::{BusinessDayConvention, Calendar};
use crate::time::date::{Date, Period};
use crate::time::day_counter::DayCounter;
use crate::time::day_counters::actual_365_fixed::Actual365Fixed;
use std::sync::Arc;

/// Common trait for market rate helpers (deposits, FRAs, swaps) used to bootstrap yield curves.
pub trait RateHelper: Send + Sync {
    /// Return the maturity date of the underlying market instrument.
    fn maturity_date(&self) -> Date;

    /// Calculate the new discount factor at the pillar maturity given the curve established up to this point.
    fn solve_discount_factor(&self, ref_date: Date, curve: &InterpolatedDiscountCurve) -> f64;
}

/// Helper for money market deposit rates.
///
/// Implies simple compounding:
/// $$P(0, t) = \frac{1}{1 + R \cdot \tau}$$
#[derive(Clone)]
pub struct DepositRateHelper {
    rate: f64,
    maturity: Date,
    day_counter: Arc<dyn DayCounter>,
}

impl DepositRateHelper {
    /// Create a new deposit rate helper.
    pub fn new(rate: f64, maturity: Date, day_counter: Arc<dyn DayCounter>) -> Self {
        Self {
            rate,
            maturity,
            day_counter,
        }
    }
}

impl RateHelper for DepositRateHelper {
    #[inline]
    fn maturity_date(&self) -> Date {
        self.maturity
    }

    fn solve_discount_factor(&self, ref_date: Date, _curve: &InterpolatedDiscountCurve) -> f64 {
        let tau = self.day_counter.year_fraction(ref_date, self.maturity);
        1.0 / (1.0 + self.rate * tau)
    }
}

/// Helper for fixed-float par vanilla interest rate swaps.
///
/// Under a par swap, the present value of fixed coupon payments equals $1 - P(0, t_N)$:
/// $$S \sum_{j=1}^{N} \tau_j P(0, t_j) = 1 - P(0, t_N)$$
///
/// Solving for the pillar discount factor $P(0, t_N)$:
/// $$P(0, t_N) = \frac{1 - S \sum_{j=1}^{N-1} \tau_j P(0, t_j)}{1 + S \tau_N}$$
#[derive(Clone)]
pub struct SwapRateHelper {
    rate: f64,
    maturity: Date,
    fixed_dates: Vec<Date>,
    day_counter: Arc<dyn DayCounter>,
}

impl SwapRateHelper {
    /// Create a new swap rate helper from coupon payment dates.
    pub fn new(
        rate: f64,
        maturity: Date,
        fixed_dates: Vec<Date>,
        day_counter: Arc<dyn DayCounter>,
    ) -> Self {
        Self {
            rate,
            maturity,
            fixed_dates,
            day_counter,
        }
    }

    /// Convenience constructor creating fixed leg schedule from annual/semiannual frequency.
    pub fn from_tenor<C: Calendar>(
        rate: f64,
        ref_date: Date,
        tenor: Period,
        frequency_months: i64,
        calendar: &C,
        convention: BusinessDayConvention,
        day_counter: Arc<dyn DayCounter>,
    ) -> Self {
        let maturity = calendar
            .advance(ref_date, tenor, convention, false)
            .expect("Valid advance");

        let mut fixed_dates = Vec::new();
        let mut step = 1;
        loop {
            let next_date = calendar
                .advance(
                    ref_date,
                    Period::Months(frequency_months * step),
                    convention,
                    false,
                )
                .expect("Valid advance");

            if next_date >= maturity {
                fixed_dates.push(maturity);
                break;
            }
            fixed_dates.push(next_date);
            step += 1;
        }

        Self {
            rate,
            maturity,
            fixed_dates,
            day_counter,
        }
    }
}

impl RateHelper for SwapRateHelper {
    #[inline]
    fn maturity_date(&self) -> Date {
        self.maturity
    }

    fn solve_discount_factor(&self, ref_date: Date, curve: &InterpolatedDiscountCurve) -> f64 {
        let n = self.fixed_dates.len();
        if n == 0 {
            return 1.0;
        }

        let dc_curve = Actual365Fixed;
        let mut prev_date = ref_date;
        let mut accrued_sum_prev = 0.0;

        for &d in &self.fixed_dates[..n - 1] {
            let tau = self.day_counter.year_fraction(prev_date, d);
            let t_curve = dc_curve.year_fraction(ref_date, d);
            let df = curve.discount(t_curve);
            accrued_sum_prev += tau * df;
            prev_date = d;
        }

        let tau_last = self.day_counter.year_fraction(prev_date, self.maturity);
        let numerator = 1.0 - self.rate * accrued_sum_prev;
        let denominator = 1.0 + self.rate * tau_last;

        (numerator / denominator).max(1e-6)
    }
}

/// Bootstrapper building an [`InterpolatedDiscountCurve`] from market rate helpers.
///
/// # Examples
/// ```
/// use std::sync::Arc;
/// use quantlib_rs::termstructures::bootstrapped_curve::{DepositRateHelper, SwapRateHelper, PiecewiseYieldCurve};
/// use quantlib_rs::termstructures::yield_term_structure::YieldTermStructure;
/// use quantlib_rs::time::calendar::BusinessDayConvention;
/// use quantlib_rs::time::calendars::weekends_only::WeekendsOnly;
/// use quantlib_rs::time::date::{Date, Month, Period};
/// use quantlib_rs::time::day_counters::actual_360::Actual360;
/// use quantlib_rs::time::day_counters::thirty_360::{Thirty360, Thirty360Convention};
///
/// let today = Date::from_ymd(2024, Month::January, 15).unwrap();
/// let cal = WeekendsOnly;
/// let dc_dep = Arc::new(Actual360);
/// let dc_swap = Arc::new(Thirty360::new(Thirty360Convention::BondBasis));
///
/// // 6M deposit at 5.0%
/// let dep_mat = Date::from_ymd(2024, Month::July, 15).unwrap();
/// let dep_helper = Box::new(DepositRateHelper::new(0.05, dep_mat, dc_dep));
///
/// // 2Y swap at 5.2%
/// let swap_helper = Box::new(SwapRateHelper::from_tenor(
///     0.052,
///     today,
///     Period::Years(2),
///     6,
///     &cal,
///     BusinessDayConvention::Following,
///     dc_swap,
/// ));
///
/// let helpers: Vec<Box<dyn quantlib_rs::termstructures::bootstrapped_curve::RateHelper>> = vec![dep_helper, swap_helper];
/// let curve = PiecewiseYieldCurve::bootstrap(today, helpers).unwrap();
///
/// assert_eq!(curve.discount(0.0), 1.0);
/// assert!(curve.discount(1.0) < 1.0 && curve.discount(1.0) > 0.8);
/// ```
pub struct PiecewiseYieldCurve;

impl PiecewiseYieldCurve {
    /// Bootstrap an [`InterpolatedDiscountCurve`] from a set of rate helpers.
    pub fn bootstrap(
        ref_date: Date,
        mut helpers: Vec<Box<dyn RateHelper>>,
    ) -> Result<InterpolatedDiscountCurve, CurveError> {
        if helpers.is_empty() {
            return Err(CurveError::NonMonotonicTimes);
        }

        // Sort helpers by maturity date
        helpers.sort_by_key(|h| h.maturity_date());

        let dc_curve = Actual365Fixed;
        let mut times = vec![0.0];
        let mut discounts = vec![1.0];

        for helper in helpers {
            let mat = helper.maturity_date();
            let t = dc_curve.year_fraction(ref_date, mat);

            if t <= *times.last().unwrap() {
                continue; // Skip duplicate or non-increasing maturities
            }

            // Current temporary curve with already-bootstrapped pillars
            let df = if times.len() >= 2 {
                let temp_curve =
                    InterpolatedDiscountCurve::new(times.clone(), discounts.clone(), ref_date)?;
                helper.solve_discount_factor(ref_date, &temp_curve)
            } else {
                // Temporary dummy curve for the first pillar
                let dummy_times = vec![0.0, t];
                let dummy_discounts = vec![1.0, 1.0];
                let temp_curve =
                    InterpolatedDiscountCurve::new(dummy_times, dummy_discounts, ref_date)?;
                helper.solve_discount_factor(ref_date, &temp_curve)
            };

            times.push(t);
            discounts.push(df);
        }

        InterpolatedDiscountCurve::new(times, discounts, ref_date)
    }
}