quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! Thirty/360 day counters (Bond Basis / US and European 30E/360).

use crate::time::date::Date;
use crate::time::day_counter::DayCounter;

/// Thirty/360 conventions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Thirty360Convention {
    /// US Bond Basis (ISMA 30/360): $d_1=31 \to 30$; if $d_2=31$ and $d_1 \ge 30$, $d_2 \to 30$.
    #[default]
    BondBasis,
    /// European (30E/360 / ISDA 2000): $d_1=31 \to 30$; $d_2=31 \to 30$.
    European,
}

/// Thirty/360 day counter.
///
/// Under 30/360, each full month is assumed to have 30 days and each year 360 days:
/// $$\text{Day Count} = 360(y_2 - y_1) + 30(m_2 - m_1) + (d_2 - d_1)$$
/// $$\text{Year Fraction} = \frac{\text{Day Count}}{360}$$
///
/// # Examples
/// ```
/// use quantlib_rs::time::date::{Date, Month};
/// use quantlib_rs::time::day_counter::DayCounter;
/// use quantlib_rs::time::day_counters::thirty_360::{Thirty360, Thirty360Convention};
///
/// let dc = Thirty360::new(Thirty360Convention::BondBasis);
/// let d1 = Date::from_ymd(2024, Month::February, 15).unwrap();
/// let d2 = Date::from_ymd(2024, Month::August, 15).unwrap();
///
/// assert_eq!(dc.day_count(d1, d2), 180);
/// assert!((dc.year_fraction(d1, d2) - 0.5).abs() < 1e-12);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Thirty360 {
    convention: Thirty360Convention,
}

impl Thirty360 {
    /// Create a new Thirty/360 day counter with the specified convention.
    pub const fn new(convention: Thirty360Convention) -> Self {
        Self { convention }
    }
}

impl DayCounter for Thirty360 {
    fn name(&self) -> &'static str {
        match self.convention {
            Thirty360Convention::BondBasis => "30/360 (Bond Basis)",
            Thirty360Convention::European => "30E/360 (Eurobond Basis)",
        }
    }

    fn day_count(&self, start: Date, end: Date) -> i64 {
        let (y1, m1, mut d1) = start.ymd();
        let (y2, m2, mut d2) = end.ymd();

        match self.convention {
            Thirty360Convention::BondBasis => {
                if d1 == 31 {
                    d1 = 30;
                }
                if d2 == 31 && d1 >= 30 {
                    d2 = 30;
                }
            }
            Thirty360Convention::European => {
                if d1 == 31 {
                    d1 = 30;
                }
                if d2 == 31 {
                    d2 = 30;
                }
            }
        }

        360 * (y2 as i64 - y1 as i64)
            + 30 * (m2.as_number() as i64 - m1.as_number() as i64)
            + (d2 as i64 - d1 as i64)
    }

    #[inline]
    fn year_fraction(&self, start: Date, end: Date) -> f64 {
        self.day_count(start, end) as f64 / 360.0
    }
}