quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Proleptic Gregorian calendar date implementation with $O(1)$ serial day arithmetic.

use std::fmt;
use std::ops::{Add, Sub};
use thiserror::Error;

/// Error type for invalid date construction and manipulations.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum DateError {
    /// Provided year is outside the valid range [-9999, 9999].
    #[error("Year {0} is out of valid range [-9999, 9999]")]
    InvalidYear(i32),
    /// Provided month is invalid (must be 1..=12).
    #[error("Month {0} is invalid (must be 1..=12)")]
    InvalidMonth(u8),
    /// Provided day is invalid for the given year and month.
    #[error("Day {day} is invalid for month {month} in year {year}")]
    InvalidDay {
        /// The invalid day provided
        day: u8,
        /// The month
        month: u8,
        /// The year
        year: i32,
    },
    /// An arithmetic overflow occurred in date calculations.
    #[error("Date calculation resulted in overflow")]
    Overflow,
}

/// Representation of a calendar month.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Month {
    /// January (31 days)
    January = 1,
    /// February (28 or 29 days)
    February = 2,
    /// March (31 days)
    March = 3,
    /// April (30 days)
    April = 4,
    /// May (31 days)
    May = 5,
    /// June (30 days)
    June = 6,
    /// July (31 days)
    July = 7,
    /// August (31 days)
    August = 8,
    /// September (30 days)
    September = 9,
    /// October (31 days)
    October = 10,
    /// November (30 days)
    November = 11,
    /// December (31 days)
    December = 12,
}

impl Month {
    /// Construct a [`Month`] from a 1-based integer (1 = January, 12 = December).
    ///
    /// # Examples
    /// ```
    /// use quantlib_rs::time::date::Month;
    /// assert_eq!(Month::from_number(1), Ok(Month::January));
    /// assert_eq!(Month::from_number(12), Ok(Month::December));
    /// assert!(Month::from_number(13).is_err());
    /// ```
    pub fn from_number(n: u8) -> Result<Self, DateError> {
        match n {
            1 => Ok(Self::January),
            2 => Ok(Self::February),
            3 => Ok(Self::March),
            4 => Ok(Self::April),
            5 => Ok(Self::May),
            6 => Ok(Self::June),
            7 => Ok(Self::July),
            8 => Ok(Self::August),
            9 => Ok(Self::September),
            10 => Ok(Self::October),
            11 => Ok(Self::November),
            12 => Ok(Self::December),
            _ => Err(DateError::InvalidMonth(n)),
        }
    }

    /// Return the 1-based integer representation of the month (1 = Jan, 12 = Dec).
    #[inline]
    pub fn as_number(self) -> u8 {
        self as u8
    }
}

/// Day of the week in ISO 8601 (Monday = 1, Sunday = 7).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Weekday {
    /// Monday (ISO 1)
    Monday = 1,
    /// Tuesday (ISO 2)
    Tuesday = 2,
    /// Wednesday (ISO 3)
    Wednesday = 3,
    /// Thursday (ISO 4)
    Thursday = 4,
    /// Friday (ISO 5)
    Friday = 5,
    /// Saturday (ISO 6)
    Saturday = 6,
    /// Sunday (ISO 7)
    Sunday = 7,
}

impl Weekday {
    /// Return true if the day is a weekend day (Saturday or Sunday).
    #[inline]
    pub fn is_weekend(self) -> bool {
        matches!(self, Self::Saturday | Self::Sunday)
    }
}

/// Time period for financial date advancement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Period {
    /// Number of days
    Days(i64),
    /// Number of weeks
    Weeks(i64),
    /// Number of months
    Months(i64),
    /// Number of years
    Years(i64),
}

/// Proleptic Gregorian calendar date stored as a serial day count since `1970-01-01` (epoch day 0).
///
/// This representation makes date comparison, day arithmetic, and day count calculations $O(1)$
/// and allocation-free.
///
/// # Examples
/// ```
/// use quantlib_rs::time::date::{Date, Month, Weekday};
///
/// let date = Date::from_ymd(2026, Month::September, 3).unwrap();
/// assert_eq!(date.year(), 2026);
/// assert_eq!(date.month(), Month::September);
/// assert_eq!(date.day(), 3);
/// assert_eq!(date.weekday(), Weekday::Thursday);
///
/// let next_day = date + 1;
/// assert_eq!(next_day.day(), 4);
/// assert_eq!(next_day - date, 1);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Date {
    serial: i64,
}

impl Date {
    /// Creates a Date from Year, Month, and Day.
    ///
    /// # Errors
    /// Returns [`DateError`] if year is outside [-9999, 9999] or day is out of range
    /// for the given month and year.
    ///
    /// # Examples
    /// ```
    /// use quantlib_rs::time::date::{Date, Month};
    /// let d = Date::from_ymd(2024, Month::February, 29).unwrap();
    /// assert_eq!(d.day(), 29);
    /// assert!(Date::from_ymd(2023, Month::February, 29).is_err());
    /// ```
    pub fn from_ymd(year: i32, month: Month, day: u8) -> Result<Self, DateError> {
        if !(-9999..=9999).contains(&year) {
            return Err(DateError::InvalidYear(year));
        }
        let m = month.as_number();
        let max_days = days_in_month(year, month);
        if day < 1 || day > max_days {
            return Err(DateError::InvalidDay {
                day,
                month: m,
                year,
            });
        }
        let serial = days_from_civil(year, m, day);
        Ok(Self { serial })
    }

    /// Construct a Date from serial days since 1970-01-01.
    #[inline]
    pub const fn from_serial(serial: i64) -> Self {
        Self { serial }
    }

    /// Returns the serial days since 1970-01-01.
    #[inline]
    pub const fn serial(&self) -> i64 {
        self.serial
    }

    /// Returns the year component.
    #[inline]
    pub fn year(&self) -> i32 {
        let (y, _, _) = civil_from_days(self.serial);
        y
    }

    /// Returns the [`Month`] component.
    #[inline]
    pub fn month(&self) -> Month {
        let (_, m, _) = civil_from_days(self.serial);
        Month::from_number(m).expect("civil_from_days returns valid month")
    }

    /// Returns the day of the month (1..=31).
    #[inline]
    pub fn day(&self) -> u8 {
        let (_, _, d) = civil_from_days(self.serial);
        d
    }

    /// Returns year, month, and day components as a tuple.
    #[inline]
    pub fn ymd(&self) -> (i32, Month, u8) {
        let (y, m, d) = civil_from_days(self.serial);
        (
            y,
            Month::from_number(m).expect("valid month from civil_from_days"),
            d,
        )
    }

    /// Returns the day of the week.
    #[inline]
    pub fn weekday(&self) -> Weekday {
        let wd = ((self.serial + 3).rem_euclid(7)) + 1;
        match wd {
            1 => Weekday::Monday,
            2 => Weekday::Tuesday,
            3 => Weekday::Wednesday,
            4 => Weekday::Thursday,
            5 => Weekday::Friday,
            6 => Weekday::Saturday,
            7 => Weekday::Sunday,
            _ => unreachable!(),
        }
    }

    /// Returns true if the year of this date is a leap year.
    #[inline]
    pub fn is_leap_year(&self) -> bool {
        is_leap_year(self.year())
    }

    /// Returns true if this date is the last calendar day of its month.
    ///
    /// # Examples
    /// ```
    /// use quantlib_rs::time::date::{Date, Month};
    /// let leap_feb = Date::from_ymd(2024, Month::February, 29).unwrap();
    /// assert!(leap_feb.is_end_of_month());
    /// let mid_month = Date::from_ymd(2024, Month::February, 15).unwrap();
    /// assert!(!mid_month.is_end_of_month());
    /// ```
    #[inline]
    pub fn is_end_of_month(&self) -> bool {
        let (y, m, d) = self.ymd();
        d == days_in_month(y, m)
    }

    /// Returns the day of the year (1..=366).
    pub fn day_of_year(&self) -> u16 {
        let (y, _, _) = self.ymd();
        let jan1 = days_from_civil(y, 1, 1);
        (self.serial - jan1 + 1) as u16
    }

    /// Return the last day of the month for the given year and month.
    pub fn end_of_month(year: i32, month: Month) -> Result<Self, DateError> {
        let max_day = days_in_month(year, month);
        Self::from_ymd(year, month, max_day)
    }

    /// Advance this date by a [`Period`], adjusting for end-of-month if requested.
    ///
    /// When adding months or years, if the destination month has fewer days than
    /// the source day (e.g. Jan 31 + 1 month), it is clamped to the end of the destination
    /// month (e.g. Feb 28/29). If `preserve_end_of_month` is true and the starting date
    /// was the end of the month, the result is rolled to the end of the target month.
    ///
    /// # Examples
    /// ```
    /// use quantlib_rs::time::date::{Date, Month, Period};
    /// let d = Date::from_ymd(2024, Month::January, 31).unwrap();
    /// let next = d.advance(Period::Months(1), false).unwrap();
    /// assert_eq!(next, Date::from_ymd(2024, Month::February, 29).unwrap());
    /// ```
    pub fn advance(&self, period: Period, preserve_end_of_month: bool) -> Result<Self, DateError> {
        match period {
            Period::Days(n) => self
                .serial
                .checked_add(n)
                .map(Self::from_serial)
                .ok_or(DateError::Overflow),
            Period::Weeks(w) => {
                let days = w.checked_mul(7).ok_or(DateError::Overflow)?;
                self.advance(Period::Days(days), preserve_end_of_month)
            }
            Period::Months(m) => {
                let (y, current_month, d) = self.ymd();
                let is_eom = preserve_end_of_month && self.is_end_of_month();

                let total_months = (y as i64) * 12 + (current_month.as_number() as i64 - 1) + m;
                let target_year = (total_months.div_euclid(12)) as i32;
                let target_month_num = (total_months.rem_euclid(12) + 1) as u8;
                let target_month = Month::from_number(target_month_num)?;

                let target_max_days = days_in_month(target_year, target_month);
                let target_day = if is_eom {
                    target_max_days
                } else {
                    d.min(target_max_days)
                };

                Self::from_ymd(target_year, target_month, target_day)
            }
            Period::Years(y) => {
                let months = y.checked_mul(12).ok_or(DateError::Overflow)?;
                self.advance(Period::Months(months), preserve_end_of_month)
            }
        }
    }
}

/// Howard Hinnant's algorithm: days from civil (proleptic Gregorian) to days since 1970-01-01.
/// Public domain algorithm widely used in C++20 chrono and standard libraries.
#[inline]
fn days_from_civil(year: i32, month: u8, day: u8) -> i64 {
    let y = year - i32::from(month <= 2);
    let era = (if y >= 0 { y } else { y - 399 }) / 400;
    let yoe = (y - era * 400) as u32;
    let m = month as u32;
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as u32 - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era as i64 * 146_097 + doe as i64 - 719_468
}

/// Howard Hinnant's algorithm: civil year, month, day from days since 1970-01-01.
#[inline]
fn civil_from_days(z: i64) -> (i32, u8, u8) {
    let z = z + 719_468;
    let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
    let doe = (z - era * 146_097) as u32;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe as i32 + era as i32 * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = (doy - (153 * mp + 2) / 5 + 1) as u8;
    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u8;
    let y = y + i32::from(m <= 2);
    (y, m, d)
}

/// Returns true if the Gregorian year is a leap year.
#[inline]
pub const fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

/// Returns the number of days in a given month of a given year.
#[inline]
pub fn days_in_month(year: i32, month: Month) -> u8 {
    match month {
        Month::January
        | Month::March
        | Month::May
        | Month::July
        | Month::August
        | Month::October
        | Month::December => 31,
        Month::April | Month::June | Month::September | Month::November => 30,
        Month::February => {
            if is_leap_year(year) {
                29
            } else {
                28
            }
        }
    }
}

impl Add<i64> for Date {
    type Output = Self;

    #[inline]
    fn add(self, days: i64) -> Self::Output {
        Self::from_serial(self.serial + days)
    }
}

impl Sub<i64> for Date {
    type Output = Self;

    #[inline]
    fn sub(self, days: i64) -> Self::Output {
        Self::from_serial(self.serial - days)
    }
}

impl Sub<Date> for Date {
    type Output = i64;

    #[inline]
    fn sub(self, rhs: Date) -> Self::Output {
        self.serial - rhs.serial
    }
}

impl fmt::Display for Date {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (y, m, d) = self.ymd();
        write!(f, "{:04}-{:02}-{:02}", y, m.as_number(), d)
    }
}

impl fmt::Debug for Date {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Date({})", self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_date_civil_roundtrip() {
        // Roundtrip test spanning multiple centuries and leap years
        for year in [1900, 1901, 1999, 2000, 2004, 2024, 2026, 2100] {
            for month_idx in 1..=12 {
                let month = Month::from_number(month_idx).unwrap();
                let max_d = days_in_month(year, month);
                for day in [1, 15, max_d] {
                    let d = Date::from_ymd(year, month, day).unwrap();
                    assert_eq!(d.year(), year);
                    assert_eq!(d.month(), month);
                    assert_eq!(d.day(), day);
                }
            }
        }
    }

    #[test]
    fn test_leap_years() {
        assert!(!is_leap_year(1900)); // Divisible by 100, not 400
        assert!(is_leap_year(2000)); // Divisible by 400
        assert!(is_leap_year(2024)); // Divisible by 4
        assert!(!is_leap_year(2023));
        assert!(!is_leap_year(2100));
    }

    #[test]
    fn test_weekday() {
        // 1970-01-01 was Thursday
        let epoch = Date::from_ymd(1970, Month::January, 1).unwrap();
        assert_eq!(epoch.weekday(), Weekday::Thursday);

        // 2026-09-03 is Thursday
        let d = Date::from_ymd(2026, Month::September, 3).unwrap();
        assert_eq!(d.weekday(), Weekday::Thursday);

        // 2024-02-29 was Thursday
        let leap_d = Date::from_ymd(2024, Month::February, 29).unwrap();
        assert_eq!(leap_d.weekday(), Weekday::Thursday);
    }

    #[test]
    fn test_advance_months_end_of_month() {
        let jan31 = Date::from_ymd(2024, Month::January, 31).unwrap();
        let feb29 = jan31.advance(Period::Months(1), false).unwrap();
        assert_eq!(feb29, Date::from_ymd(2024, Month::February, 29).unwrap());

        // In a non-leap year
        let jan31_2023 = Date::from_ymd(2023, Month::January, 31).unwrap();
        let feb28_2023 = jan31_2023.advance(Period::Months(1), false).unwrap();
        assert_eq!(
            feb28_2023,
            Date::from_ymd(2023, Month::February, 28).unwrap()
        );
    }

    #[test]
    fn test_day_difference() {
        let d1 = Date::from_ymd(2026, Month::January, 1).unwrap();
        let d2 = Date::from_ymd(2026, Month::January, 11).unwrap();
        assert_eq!(d2 - d1, 10);
        assert_eq!(d1 - d2, -10);
    }
}