quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! Discounting engine for vanilla interest rate swaps.

use crate::instruments::swaps::vanilla_swap::{SwapType, VanillaSwap};
use crate::termstructures::yield_term_structure::YieldTermStructure;
use crate::time::date::Date;
use crate::time::day_counter::DayCounter;
use crate::time::day_counters::actual_365_fixed::Actual365Fixed;
use std::sync::Arc;

/// Discounting pricing engine for vanilla interest rate swaps.
///
/// Supports both classic single-curve pricing and modern dual-curve discounting
/// (e.g. OIS discounting curve + forward Libor/EURIBOR projection curve).
///
/// # Examples
/// ```
/// use std::sync::Arc;
/// use quantlib_rs::engines::swap_engine::DiscountingSwapEngine;
/// use quantlib_rs::instruments::swaps::vanilla_swap::{VanillaSwap, SwapType};
/// use quantlib_rs::termstructures::yield_term_structure::FlatForward;
/// 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};
/// use quantlib_rs::time::schedule::{DateGenerationRule, Schedule};
///
/// let cal = WeekendsOnly;
/// let today = Date::from_ymd(2024, Month::January, 15).unwrap();
/// let maturity = Date::from_ymd(2029, Month::January, 15).unwrap();
///
/// let fixed_schedule = Schedule::new(
///     today,
///     maturity,
///     Period::Months(6),
///     &cal,
///     BusinessDayConvention::Following,
///     BusinessDayConvention::Following,
///     DateGenerationRule::Backward,
///     false,
/// ).unwrap();
///
/// let float_schedule = Schedule::new(
///     today,
///     maturity,
///     Period::Months(3),
///     &cal,
///     BusinessDayConvention::Following,
///     BusinessDayConvention::Following,
///     DateGenerationRule::Backward,
///     false,
/// ).unwrap();
///
/// let fixed_dc = Arc::new(Thirty360::new(Thirty360Convention::BondBasis));
/// let float_dc = Arc::new(Actual360);
///
/// let curve = Arc::new(FlatForward::new(0.05, today));
/// let engine = DiscountingSwapEngine::new(curve.clone());
///
/// let swap = VanillaSwap::new(
///     SwapType::Payer,
///     10_000_000.0,
///     fixed_schedule,
///     0.05,
///     fixed_dc,
///     float_schedule,
///     float_dc,
///     0.0,
/// );
///
/// let fair_rate = engine.fair_rate(&swap, today);
/// assert!((fair_rate - 0.05).abs() < 0.005);
/// ```
#[derive(Clone)]
pub struct DiscountingSwapEngine {
    discount_curve: Arc<dyn YieldTermStructure>,
    projection_curve: Arc<dyn YieldTermStructure>,
}

impl DiscountingSwapEngine {
    /// Create a single-curve swap engine where discounting and floating projection share the same curve.
    pub fn new(curve: Arc<dyn YieldTermStructure>) -> Self {
        Self {
            discount_curve: curve.clone(),
            projection_curve: curve,
        }
    }

    /// Create a dual-curve swap engine with separate discount and forward projection curves.
    pub fn with_dual_curves(
        discount_curve: Arc<dyn YieldTermStructure>,
        projection_curve: Arc<dyn YieldTermStructure>,
    ) -> Self {
        Self {
            discount_curve,
            projection_curve,
        }
    }

    /// Return the discounting yield curve.
    pub fn discount_curve(&self) -> &dyn YieldTermStructure {
        self.discount_curve.as_ref()
    }

    /// Return the floating forward projection yield curve.
    pub fn projection_curve(&self) -> &dyn YieldTermStructure {
        self.projection_curve.as_ref()
    }

    /// Calculate the Net Present Value (NPV) of the fixed leg on valuation date `as_of`.
    pub fn fixed_leg_npv(&self, swap: &VanillaSwap, as_of: Date) -> f64 {
        let dc_curve = Actual365Fixed;
        let ref_date = self.discount_curve.reference_date();
        let t_as_of = dc_curve.year_fraction(ref_date, as_of);
        let df_as_of = self.discount_curve.discount(t_as_of);

        if df_as_of <= 0.0 {
            return 0.0;
        }

        let dates = swap.fixed_schedule().dates();
        let mut npv = 0.0;

        for i in 1..dates.len() {
            let start = dates[i - 1];
            let end = dates[i];
            if end > as_of {
                let tau = swap.fixed_day_counter().year_fraction(start, end);
                let coupon = swap.nominal() * swap.fixed_rate() * tau;
                let t_end = dc_curve.year_fraction(ref_date, end);
                let df = self.discount_curve.discount(t_end);
                npv += coupon * (df / df_as_of);
            }
        }

        npv
    }

    /// Calculate the fixed leg annuity (sum of discounted year fractions per unit notional).
    pub fn fixed_leg_annuity(&self, swap: &VanillaSwap, as_of: Date) -> f64 {
        let dc_curve = Actual365Fixed;
        let ref_date = self.discount_curve.reference_date();
        let t_as_of = dc_curve.year_fraction(ref_date, as_of);
        let df_as_of = self.discount_curve.discount(t_as_of);

        if df_as_of <= 0.0 {
            return 0.0;
        }

        let dates = swap.fixed_schedule().dates();
        let mut annuity = 0.0;

        for i in 1..dates.len() {
            let start = dates[i - 1];
            let end = dates[i];
            if end > as_of {
                let tau = swap.fixed_day_counter().year_fraction(start, end);
                let t_end = dc_curve.year_fraction(ref_date, end);
                let df = self.discount_curve.discount(t_end);
                annuity += tau * (df / df_as_of);
            }
        }

        annuity
    }

    /// Calculate the Net Present Value (NPV) of the floating leg on valuation date `as_of`.
    pub fn floating_leg_npv(&self, swap: &VanillaSwap, as_of: Date) -> f64 {
        let dc_curve = Actual365Fixed;
        let ref_date = self.discount_curve.reference_date();
        let t_as_of = dc_curve.year_fraction(ref_date, as_of);
        let df_as_of = self.discount_curve.discount(t_as_of);

        if df_as_of <= 0.0 {
            return 0.0;
        }

        let dates = swap.floating_schedule().dates();
        let mut npv = 0.0;

        for i in 1..dates.len() {
            let start = dates[i - 1];
            let end = dates[i];
            if end > as_of {
                let tau = swap.floating_day_counter().year_fraction(start, end);
                if tau <= 0.0 {
                    continue;
                }

                // Project forward rate from projection curve
                let t_start = dc_curve.year_fraction(ref_date, start);
                let t_end = dc_curve.year_fraction(ref_date, end);

                let p_start = self.projection_curve.discount(t_start);
                let p_end = self.projection_curve.discount(t_end);

                let forward_rate = if p_end > 0.0 {
                    (p_start / p_end - 1.0) / tau
                } else {
                    0.0
                };

                let coupon_amount = swap.nominal() * (forward_rate + swap.spread()) * tau;
                let df_discount = self.discount_curve.discount(t_end);

                npv += coupon_amount * (df_discount / df_as_of);
            }
        }

        npv
    }

    /// Calculate the total Net Present Value (NPV) of the swap.
    pub fn calculate_npv(&self, swap: &VanillaSwap, as_of: Date) -> f64 {
        let fixed_npv = self.fixed_leg_npv(swap, as_of);
        let float_npv = self.floating_leg_npv(swap, as_of);

        match swap.swap_type() {
            SwapType::Payer => float_npv - fixed_npv,
            SwapType::Receiver => fixed_npv - float_npv,
        }
    }

    /// Calculate the fair par swap rate that renders the swap NPV exactly zero.
    pub fn fair_rate(&self, swap: &VanillaSwap, as_of: Date) -> f64 {
        let float_npv = self.floating_leg_npv(swap, as_of);
        let annuity = self.fixed_leg_annuity(swap, as_of);

        if annuity <= 1e-12 {
            0.0
        } else {
            float_npv / (swap.nominal() * annuity)
        }
    }
}