quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! Coupon and payment schedule generation for bonds, swaps, and loans.

use crate::time::calendar::{BusinessDayConvention, Calendar};
use crate::time::date::{Date, DateError, Period};

/// Date generation rules for coupon schedules.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum DateGenerationRule {
    /// Advance backward from the termination date (standard for fixed income).
    #[default]
    Backward,
    /// Advance forward from the effective date.
    Forward,
    /// Only the effective and termination dates (zero coupon).
    Zero,
}

/// Coupon payment schedule containing a sequence of dates.
///
/// # Examples
/// ```
/// use quantlib_rs::time::date::{Date, Month, Period};
/// use quantlib_rs::time::calendar::BusinessDayConvention;
/// use quantlib_rs::time::calendars::weekends_only::WeekendsOnly;
/// use quantlib_rs::time::schedule::{Schedule, DateGenerationRule};
///
/// let cal = WeekendsOnly;
/// let start = Date::from_ymd(2024, Month::January, 15).unwrap();
/// let end = Date::from_ymd(2025, Month::January, 15).unwrap();
///
/// let schedule = Schedule::new(
///     start,
///     end,
///     Period::Months(6),
///     &cal,
///     BusinessDayConvention::Following,
///     BusinessDayConvention::Following,
///     DateGenerationRule::Forward,
///     false,
/// ).unwrap();
///
/// assert_eq!(schedule.dates().len(), 3); // Jan 15 2024, Jul 15 2024, Jan 15 2025
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Schedule {
    dates: Vec<Date>,
    tenor: Period,
    convention: BusinessDayConvention,
    rule: DateGenerationRule,
}

impl Schedule {
    /// Generate a new coupon schedule.
    #[allow(clippy::too_many_arguments)]
    pub fn new<C: Calendar>(
        effective_date: Date,
        termination_date: Date,
        tenor: Period,
        calendar: &C,
        convention: BusinessDayConvention,
        termination_date_convention: BusinessDayConvention,
        rule: DateGenerationRule,
        end_of_month: bool,
    ) -> Result<Self, DateError> {
        if effective_date >= termination_date {
            return Err(DateError::InvalidDay {
                day: effective_date.day(),
                month: effective_date.month().as_number(),
                year: effective_date.year(),
            });
        }

        let mut dates = Vec::new();

        match rule {
            DateGenerationRule::Zero => {
                dates.push(calendar.adjust(effective_date, convention));
                dates.push(calendar.adjust(termination_date, termination_date_convention));
            }
            DateGenerationRule::Forward => {
                let current = effective_date;
                dates.push(calendar.adjust(current, convention));

                let mut step = 1;
                loop {
                    let next_raw = match tenor {
                        Period::Days(d) => {
                            effective_date.advance(Period::Days(d * step), end_of_month)?
                        }
                        Period::Weeks(w) => {
                            effective_date.advance(Period::Weeks(w * step), end_of_month)?
                        }
                        Period::Months(m) => {
                            effective_date.advance(Period::Months(m * step), end_of_month)?
                        }
                        Period::Years(y) => {
                            effective_date.advance(Period::Years(y * step), end_of_month)?
                        }
                    };

                    if next_raw >= termination_date {
                        break;
                    }
                    dates.push(calendar.adjust(next_raw, convention));
                    step += 1;
                }
                dates.push(calendar.adjust(termination_date, termination_date_convention));
            }
            DateGenerationRule::Backward => {
                let mut unadjusted = Vec::new();
                unadjusted.push(termination_date);

                let mut step = 1;
                loop {
                    let prev_raw = match tenor {
                        Period::Days(d) => {
                            termination_date.advance(Period::Days(-d * step), end_of_month)?
                        }
                        Period::Weeks(w) => {
                            termination_date.advance(Period::Weeks(-w * step), end_of_month)?
                        }
                        Period::Months(m) => {
                            termination_date.advance(Period::Months(-m * step), end_of_month)?
                        }
                        Period::Years(y) => {
                            termination_date.advance(Period::Years(-y * step), end_of_month)?
                        }
                    };

                    if prev_raw <= effective_date {
                        break;
                    }
                    unadjusted.push(prev_raw);
                    step += 1;
                }
                unadjusted.push(effective_date);
                unadjusted.reverse();

                for (idx, &d) in unadjusted.iter().enumerate() {
                    let conv = if idx == unadjusted.len() - 1 {
                        termination_date_convention
                    } else {
                        convention
                    };
                    dates.push(calendar.adjust(d, conv));
                }
            }
        }

        Ok(Self {
            dates,
            tenor,
            convention,
            rule,
        })
    }

    /// Return a slice of the generated dates.
    pub fn dates(&self) -> &[Date] {
        &self.dates
    }

    /// Return the number of dates in the schedule.
    pub fn len(&self) -> usize {
        self.dates.len()
    }

    /// Returns true if the schedule has no dates.
    pub fn is_empty(&self) -> bool {
        self.dates.is_empty()
    }

    /// Return the tenor of the schedule.
    pub fn tenor(&self) -> Period {
        self.tenor
    }

    /// Return the business day convention.
    pub fn convention(&self) -> BusinessDayConvention {
        self.convention
    }

    /// Return the date generation rule.
    pub fn rule(&self) -> DateGenerationRule {
        self.rule
    }

    /// Return the date at the given index.
    pub fn date(&self, index: usize) -> Option<Date> {
        self.dates.get(index).copied()
    }
}