quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! Sequence of cash flows (Leg).

use crate::cashflows::traits::CashFlow;
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;

/// A stream (leg) of cash flows.
///
/// Can represent either a bond's payment stream or one leg of a swap.
///
/// # Examples
/// ```
/// use std::sync::Arc;
/// use quantlib_rs::cashflows::leg::Leg;
/// use quantlib_rs::cashflows::simple::SimpleCashFlow;
/// use quantlib_rs::time::date::{Date, Month};
///
/// let mut leg = Leg::new();
/// let d1 = Date::from_ymd(2025, Month::January, 15).unwrap();
/// let d2 = Date::from_ymd(2025, Month::July, 15).unwrap();
///
/// leg.push(Arc::new(SimpleCashFlow::new(2.5, d1)));
/// leg.push(Arc::new(SimpleCashFlow::new(102.5, d2)));
///
/// assert_eq!(leg.len(), 2);
/// ```
#[derive(Clone, Default)]
pub struct Leg {
    cash_flows: Vec<Arc<dyn CashFlow>>,
}

impl Leg {
    /// Create an empty leg.
    pub fn new() -> Self {
        Self {
            cash_flows: Vec::new(),
        }
    }

    /// Construct a leg from a vector of cash flows.
    pub fn from_cash_flows(cash_flows: Vec<Arc<dyn CashFlow>>) -> Self {
        Self { cash_flows }
    }

    /// Append a cash flow to the leg.
    pub fn push(&mut self, cash_flow: Arc<dyn CashFlow>) {
        self.cash_flows.push(cash_flow);
    }

    /// Return the number of cash flows in this leg.
    pub fn len(&self) -> usize {
        self.cash_flows.len()
    }

    /// Returns true if the leg has no cash flows.
    pub fn is_empty(&self) -> bool {
        self.cash_flows.is_empty()
    }

    /// Return a slice of the cash flows.
    pub fn cash_flows(&self) -> &[Arc<dyn CashFlow>] {
        &self.cash_flows
    }

    /// Calculate the Net Present Value (NPV) of cash flows occurring strictly after `settlement_date`.
    ///
    /// Cash flows are discounted to `settlement_date` using the provided discount curve:
    /// $$\text{NPV} = \sum_{d_i > d_{\text{settle}}} \frac{\text{Amount}_i \cdot P(0, d_i)}{P(0, d_{\text{settle}})}$$
    pub fn npv(&self, discount_curve: &dyn YieldTermStructure, settlement_date: Date) -> f64 {
        let dc = Actual365Fixed;
        let ref_date = discount_curve.reference_date();
        let t_settle = dc.year_fraction(ref_date, settlement_date);
        let df_settle = discount_curve.discount(t_settle);

        if df_settle <= 0.0 {
            return 0.0;
        }

        let mut total_npv = 0.0;
        for cf in &self.cash_flows {
            if cf.date() > settlement_date {
                let t_cf = dc.year_fraction(ref_date, cf.date());
                let df_cf = discount_curve.discount(t_cf);
                total_npv += cf.amount() * (df_cf / df_settle);
            }
        }
        total_npv
    }
}