RustQuant_time/
day_counting.rs

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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// RustQuant: A Rust library for quantitative finance tools.
// Copyright (C) 2022-2024 https://github.com/avhz
// Dual licensed under Apache 2.0 and MIT.
// See:
//      - LICENSE-APACHE.md
//      - LICENSE-MIT.md
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// IMPORTS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

use super::{contains_leap_year, days_between, is_last_day_of_february, leap_year_count};
use crate::Calendar;
use std::fmt;
use time::{util::is_leap_year, Date, Duration, Month};

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/// Day count conventions.
///
/// From Wikipedia (<https://en.wikipedia.org/wiki/Day_count_convention>):
/// """
/// In finance, a day count convention determines how interest accrues
/// over time for a variety of investments, including bonds, notes,
/// loans, mortgages, medium-term notes, swaps, and forward rate agreements (FRAs).
/// This determines the number of days between two coupon payments,
/// thus calculating the amount transferred on payment dates and also the
/// accrued interest for dates between payments. The day count is also
/// used to quantify periods of time when discounting a cash-flow to its
/// present value. When a security such as a bond is sold between interest
/// payment dates, the seller is eligible to some fraction of the coupon amount.
/// """
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug)]
pub enum DayCountConvention {
    /// The '1/1' day count, which always returns a day count of 1.
    One_One,

    /// The 'Act/360' day count, which divides the actual number of days by 360.
    Actual_360,

    /// The 'Act/364' day count, which divides the actual number of days by 364.
    Actual_364,

    /// The 'Act/364' day count, which divides the actual number of days by 366.
    Actual_366,

    /// The 'Act/365.25' day count, which divides the actual number of days by 365.25.
    Actual_365_25,

    /// The 'Act/365 Actual' day count, which divides the actual number of days
    /// by 366 if a leap day is contained, or by 365 if not.
    Actual_365_Actual,

    /// The 'Act/365F' day count, which divides the actual number of days by 365 (fixed).
    Actual_365_Fixed,

    /// The 'Act/365L' day count, which divides the actual number of days by 365 or 366.
    Actual_365_Leap,

    /// The 'Act/Act AFB' day count, which divides the actual number of days by 366
    /// if a leap day is contained, or by 365 if not, with additional rules for periods over one year.
    Actual_Actual_AFB,

    /// The 'Act/Act ICMA' day count, which divides the actual number of days by
    /// the actual number of days in the coupon period multiplied by the frequency.
    Actual_Actual_ICMA,

    /// The 'Act/Act ISDA' day count, which divides the actual number of days in a
    /// leap year by 366 and the actual number of days in a standard year by 365.
    Actual_Actual_ISDA,

    /// The 'NL/360' day count, which divides the actual number of days omitting leap days by 360.
    No_Leap_360,

    /// The 'NL/365' day count, which divides the actual number of days omitting leap days by 365.
    No_Leap_365,

    /// The '30/360 ISDA' day count, which treats input day-of-month 31 specially.
    Thirty_360_ISDA,

    /// The '30E/360' day count, which treats input day-of-month 31 specially.
    Thirty_E_360,

    /// The '30E/360 ISDA' day count, which treats input day-of-month 31 and end of February specially.
    Thirty_E_360_ISDA,

    /// The '30E/365' day count, which treats input day-of-month 31 and end of February specially.
    Thirty_E_365,

    /// The '30E+/360' day count, which treats input day-of-month 31 specially.
    Thirty_E_Plus_360,

    /// The '30U/360' day count, which treats input day-of-month 31 and end of February specially.
    Thirty_U_360,
}

/// `DayCounter` trait.
///
/// This trait is used to compute:
///     - Day count fraction (fraction of year between two dates).
///     - Business day count (number of days between two dates, excluding weekends and holidays).
///     - Calendar day count (number of days between two dates).
pub trait DayCounter {
    /// Compute the number of calendar days between two dates.
    fn calendar_day_count(&self, date1: Date, date2: Date) -> i64;

    /// Compute the number of business days between two dates.
    fn business_day_count(&self, date1: Date, date2: Date) -> i64;

    /// Compute the day count factor between two dates.
    fn day_count_factor(&self, date1: Date, date2: Date, convention: &DayCountConvention) -> f64;

    /// Compute the number of calendar days between each date in a vector of dates.
    fn calendar_day_counts(&self, dates: &[Date]) -> Vec<i64>;

    /// Compute the number of business days between two dates.
    fn business_day_counts(&self, dates: &[Date]) -> Vec<i64>;

    /// Compute the day count factor between each date in a vector of dates.
    fn day_count_factors(&self, dates: &[Date], convention: &DayCountConvention) -> Vec<f64>;
}

impl fmt::Display for DayCountConvention {
    #[rustfmt::skip]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::One_One               => write!(f, "1 / 1"),
            Self::Actual_360            => write!(f, "Actual / 360"),
            Self::Actual_364            => write!(f, "Actual / 364"),
            Self::Actual_366            => write!(f, "Actual / 366"),
            Self::Actual_365_25         => write!(f, "Actual / 365.25"),
            Self::Actual_365_Actual     => write!(f, "Actual / 365 Actual"),
            Self::Actual_365_Fixed      => write!(f, "Actual / 365F"),
            Self::Actual_365_Leap       => write!(f, "Actual / 365L"),
            Self::Actual_Actual_AFB     => write!(f, "Actual / Actual AFB"),
            Self::Actual_Actual_ICMA    => write!(f, "Actual / Actual ICMA"),
            Self::Actual_Actual_ISDA    => write!(f, "Actual / Actual ISDA"),
            Self::No_Leap_360           => write!(f, "No Leap / 360"),
            Self::No_Leap_365           => write!(f, "No Leap / 365"),
            Self::Thirty_360_ISDA       => write!(f, "30 / 360 ISDA"),
            Self::Thirty_E_360          => write!(f, "30 E / 360"),
            Self::Thirty_E_360_ISDA     => write!(f, "30 E / 360 ISDA"),
            Self::Thirty_E_365          => write!(f, "30 E / 365"),
            Self::Thirty_E_Plus_360     => write!(f, "30 E+ / 360"),
            Self::Thirty_U_360          => write!(f, "30 U / 360"),
        }
    }
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FUNCTIONS/METHODS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

impl<C> DayCounter for C
where
    C: Calendar,
{
    /// Compute the number of calendar days between two dates.
    ///
    /// # Arguments
    ///
    /// * `date1` - The first date.
    /// * `date2` - The second date.
    ///
    /// # Example
    ///
    /// ```
    /// use time::macros::date;
    /// use RustQuant::time::day_counting::DayCounter;
    /// use RustQuant::time::countries::oceania::australia::AustraliaCalendar;
    ///
    /// let date1 = date!(2023-01-01);
    /// let date2 = date!(2025-01-01);
    ///
    /// let calendar = AustraliaCalendar;
    ///
    /// assert_eq!(calendar.calendar_day_count(date1, date2), 731);
    /// ```
    fn calendar_day_count(&self, date1: Date, date2: Date) -> i64 {
        (date2 - date1).whole_days()
    }

    /// Compute the number of business days between two dates.
    ///
    /// # Arguments
    ///
    /// * `date1` - The first date.
    /// * `date2` - The second date.
    ///
    /// # Example
    ///
    /// ```
    /// use time::macros::date;
    /// use RustQuant::time::day_counting::DayCounter;
    /// use RustQuant::time::countries::oceania::australia::AustraliaCalendar;
    ///
    /// let date1 = date!(2023-01-01);
    /// let date2 = date!(2023-02-01);
    ///
    /// let calendar = AustraliaCalendar;
    ///
    /// assert_eq!(calendar.business_day_count(date1, date2), 21);
    /// ```
    fn business_day_count(&self, date1: Date, date2: Date) -> i64 {
        let mut count = 0;
        let mut temp_date = date1;

        while temp_date <= date2 {
            if self.is_business_day(temp_date) {
                count += 1;
            }
            temp_date += Duration::days(1);
        }

        count
    }

    /// Computes the day count factor between two dates.
    ///
    /// # Arguments
    ///
    /// * `date1` - The first date.
    /// * `date2` - The second date.
    /// * `convention` - The day count convention.
    ///
    /// # Example
    ///
    /// ```
    /// use time::macros::date;
    /// use RustQuant::time::day_counting::DayCounter;
    /// use RustQuant::time::countries::oceania::australia::AustraliaCalendar;
    /// use RustQuant::time::day_counting::DayCountConvention;
    ///
    /// let date1 = date!(2023-01-01);
    /// let date2 = date!(2024-01-01);
    ///
    /// let calendar = AustraliaCalendar;
    /// let convention = DayCountConvention::Actual_365_Actual;
    ///
    /// assert_eq!(calendar.day_count_factor(date1, date2, &convention), 0.997_267_759_562_841_5);
    /// ```
    fn day_count_factor(&self, date1: Date, date2: Date, convention: &DayCountConvention) -> f64 {
        convention.day_count_factor(date1, date2)
    }

    /// Compute the number of calendar days between each date in a vector of dates.
    ///
    /// # Arguments
    ///
    /// * `dates` - A vector of dates.
    ///
    /// # Example
    ///
    /// ```
    /// use time::macros::date;
    /// use RustQuant::time::day_counting::DayCounter;
    /// use RustQuant::time::countries::oceania::australia::AustraliaCalendar;
    ///
    /// let date1 = date!(2023-01-01);
    /// let date2 = date!(2024-01-01);
    /// let date3 = date!(2025-01-01);
    ///
    /// let dates = &[date1, date2, date3];
    /// let expected = vec![365, 366];
    ///
    /// let calendar = AustraliaCalendar;
    ///
    /// assert_eq!(calendar.calendar_day_counts(dates), expected);
    /// ```
    fn calendar_day_counts(&self, dates: &[Date]) -> Vec<i64> {
        dates
            .windows(2)
            .map(|window| self.calendar_day_count(window[0], window[1]))
            .collect()
    }

    /// Compute the number of calendar days between each date in a vector of dates.
    ///
    /// # Arguments
    ///
    /// * `dates` - A vector of dates.
    ///
    /// # Example
    ///
    /// ```
    /// use time::macros::date;
    /// use RustQuant::time::day_counting::DayCounter;
    /// use RustQuant::time::countries::oceania::australia::AustraliaCalendar;
    ///
    /// let date1 = date!(2023-01-01);
    /// let date2 = date!(2023-02-01);
    /// let date3 = date!(2023-03-01);
    ///
    /// let dates = &[date1, date2, date3];
    /// let expected = vec![21, 21];
    ///
    /// let calendar = AustraliaCalendar;
    ///
    /// assert_eq!(calendar.business_day_counts(dates), expected);
    /// ```
    fn business_day_counts(&self, dates: &[Date]) -> Vec<i64> {
        dates
            .windows(2)
            .map(|window| self.business_day_count(window[0], window[1]))
            .collect()
    }

    /// Compute the day count factors between each date in a vector of dates.
    ///
    /// # Arguments
    ///
    /// * `dates` - A vector of dates.
    ///
    /// # Example
    ///
    /// ```
    /// use time::macros::date;
    /// use RustQuant::time::day_counting::DayCounter;
    /// use RustQuant::time::countries::oceania::australia::AustraliaCalendar;
    /// use RustQuant::time::day_counting::DayCountConvention;
    ///
    /// let date1 = date!(2023-01-01);
    /// let date2 = date!(2024-01-01);
    /// let date3 = date!(2025-01-01);
    ///
    /// let dates = &[date1, date2, date3];
    /// let expected = vec![0.997_267_759_562_841_5, 1.0];
    ///
    /// let calendar = AustraliaCalendar;
    /// let convention = DayCountConvention::Actual_365_Actual;
    ///
    /// assert_eq!(calendar.day_count_factors(dates, &convention), expected);
    /// ```
    fn day_count_factors(&self, dates: &[Date], convention: &DayCountConvention) -> Vec<f64> {
        dates
            .windows(2)
            .map(|window| self.day_count_factor(window[0], window[1], convention))
            .collect()
    }
}

impl Default for DayCountConvention {
    /// Default day count convention. Currently set to `Actual/Actual ISDA`.
    fn default() -> Self {
        Self::Actual_Actual_ISDA
    }
}

impl DayCountConvention {
    /// Entry point for day count factor calculation.
    #[rustfmt::skip]
    pub fn day_count_factor(&self, start_date: Date, end_date: Date) -> f64 {
        match self {
            Self::One_One               => Self::day_count_factor_one_one(start_date, end_date),
            Self::Actual_360            => Self::day_count_factor_actual_360(start_date, end_date),
            Self::Actual_364            => Self::day_count_factor_actual_364(start_date, end_date),
            Self::Actual_366            => Self::day_count_factor_actual_366(start_date, end_date),
            Self::Actual_365_25         => Self::day_count_factor_actual_365_25(start_date, end_date),
            Self::Actual_365_Actual     => Self::day_count_factor_actual_365_actual(start_date, end_date),
            Self::Actual_365_Fixed      => Self::day_count_factor_actual_365_fixed(start_date, end_date),
            Self::Actual_365_Leap       => Self::day_count_factor_actual_365_leap(start_date, end_date),
            Self::Actual_Actual_AFB     => Self::day_count_factor_actual_actual_afb(start_date, end_date),
            Self::Actual_Actual_ICMA    => Self::day_count_factor_actual_actual_icma(start_date, end_date),
            Self::Actual_Actual_ISDA    => Self::day_count_factor_actual_actual_isda(start_date, end_date),
            Self::No_Leap_360           => Self::day_count_factor_nl_360(start_date, end_date),
            Self::No_Leap_365           => Self::day_count_factor_nl_365(start_date, end_date),
            Self::Thirty_360_ISDA       => Self::day_count_factor_thirty_360_isda(start_date, end_date),
            Self::Thirty_E_360          => Self::day_count_factor_thirty_e_360(start_date, end_date),
            Self::Thirty_E_360_ISDA     => Self::day_count_factor_thirty_e_360_isda(start_date, end_date),
            Self::Thirty_E_365          => Self::day_count_factor_thirty_e_365(start_date, end_date),
            Self::Thirty_E_Plus_360     => Self::day_count_factor_thirty_e_plus_360(start_date, end_date),
            Self::Thirty_U_360          => Self::day_count_factor_thirty_u_360(start_date, end_date),
        }
    }
}

impl DayCountConvention {
    // Actual/Actual AFB day count factor calculation.
    pub(crate) fn day_count_factor_actual_actual_afb(start_date: Date, end_date: Date) -> f64 {
        let (y1, _y2) = (start_date.year(), end_date.year());
        let (_m1, m2) = (start_date.month(), end_date.month());
        let (_d1, d2) = (start_date.day(), end_date.day());

        let stub_date = if Date::from_calendar_date(y1, m2, d2).unwrap() < start_date {
            Date::from_calendar_date(y1 + 1, m2, d2).unwrap()
        } else {
            Date::from_calendar_date(y1, m2, d2).unwrap()
        };

        let initial_stub_days = (stub_date - start_date).whole_days() as f64;
        // let final_stub_days = (end_date - stub_date).whole_days() as f64;
        let final_stub_years = (end_date.year() - stub_date.year()) as f64;
        let initial_stub_contains_leap = contains_leap_year(start_date, stub_date);

        match initial_stub_contains_leap {
            true => final_stub_years + initial_stub_days / 366.0,
            false => (end_date - start_date).whole_days() as f64 / 365.0,
        }
    }

    // Actual/Actual ICMA day count factor calculation.
    pub(crate) fn day_count_factor_actual_actual_icma(_start_date: Date, _end_date: Date) -> f64 {
        todo!()
    }

    // Actual/Actual ISDA day count factor calculation.
    pub(crate) fn day_count_factor_actual_actual_isda(start_date: Date, end_date: Date) -> f64 {
        if start_date == end_date {
            return 0.0;
        }

        let (y1, y2) = (start_date.year(), end_date.year());

        let (dib1, dib2) = (
            if is_leap_year(y1) { 366.0 } else { 365.0 },
            if is_leap_year(y2) { 366.0 } else { 365.0 },
        );

        let mut sum: f64 = (y2 - y1 - 1) as f64;

        sum += days_between(
            start_date,
            Date::from_calendar_date(y1 + 1, Month::January, 1).unwrap(),
        ) as f64
            / dib1;

        sum += days_between(
            Date::from_calendar_date(y2, Month::January, 1).unwrap(),
            end_date,
        ) as f64
            / dib2;

        sum
    }

    // NL/360 day count factor calculation.
    pub(crate) fn day_count_factor_nl_360(start_date: Date, end_date: Date) -> f64 {
        let day_count = (end_date - start_date).whole_days() as f64;
        let leap_years = leap_year_count(start_date, end_date) as f64;

        (day_count - leap_years) / 360.0
    }

    // NL/365 day count factor calculation.
    pub(crate) fn day_count_factor_nl_365(start_date: Date, end_date: Date) -> f64 {
        let day_count = (end_date - start_date).whole_days() as f64;
        let leap_years = leap_year_count(start_date, end_date) as f64;

        (day_count - leap_years) / 365.0
    }

    // One/One day count factor calculation.
    pub(crate) fn day_count_factor_one_one(_start_date: Date, _end_date: Date) -> f64 {
        1.0
    }

    // Actual/360 day count factor calculation.
    pub(crate) fn day_count_factor_actual_360(start_date: Date, end_date: Date) -> f64 {
        (end_date - start_date).whole_days() as f64 / 360.0
    }

    // Actual/364 day count factor calculation.
    pub(crate) fn day_count_factor_actual_364(start_date: Date, end_date: Date) -> f64 {
        (end_date - start_date).whole_days() as f64 / 364.0
    }

    // Actual/365.25 day count factor calculation.
    pub(crate) fn day_count_factor_actual_365_25(start_date: Date, end_date: Date) -> f64 {
        (end_date - start_date).whole_days() as f64 / 365.25
    }

    // Actual/365 Actual day count factor calculation.
    pub(crate) fn day_count_factor_actual_365_actual(start_date: Date, end_date: Date) -> f64 {
        match contains_leap_year(start_date, end_date) {
            true => (end_date - start_date).whole_days() as f64 / 366.0,
            false => (end_date - start_date).whole_days() as f64 / 365.0,
        }
    }

    // Actual/365F day count factor calculation.
    pub(crate) fn day_count_factor_actual_365_fixed(start_date: Date, end_date: Date) -> f64 {
        (end_date - start_date).whole_days() as f64 / 365.0
    }

    // Actual/365L day count factor calculation.
    pub(crate) fn day_count_factor_actual_365_leap(start_date: Date, end_date: Date) -> f64 {
        match contains_leap_year(start_date, end_date) {
            true => (end_date - start_date).whole_days() as f64 / 366.0,
            false => (end_date - start_date).whole_days() as f64 / 365.0,
        }
    }

    // Actual/366 day count factor calculation.
    pub(crate) fn day_count_factor_actual_366(start_date: Date, end_date: Date) -> f64 {
        (end_date - start_date).whole_days() as f64 / 366.0
    }

    // 30/360 ISDA day count factor calculation.
    pub(crate) fn day_count_factor_thirty_360_isda(start_date: Date, end_date: Date) -> f64 {
        let (y1, m1, mut d1) = Self::thirty_360_unpack_date(start_date);
        let (y2, m2, mut d2) = Self::thirty_360_unpack_date(end_date);

        if d1 == 31 {
            d1 = 30;
        }

        if d1 == 30 && d2 == 31 {
            d2 = 30;
        }

        Self::thirty_360_numerator(y1, y2, m1, m2, d1, d2) / 360.0
    }

    // 30E/360 day count factor calculation.
    pub(crate) fn day_count_factor_thirty_e_360(start_date: Date, end_date: Date) -> f64 {
        let (y1, m1, mut d1) = Self::thirty_360_unpack_date(start_date);
        let (y2, m2, mut d2) = Self::thirty_360_unpack_date(end_date);

        if d1 == 31 {
            d1 = 30;
        }

        if d2 == 31 {
            d2 = 30;
        }

        Self::thirty_360_numerator(y1, y2, m1, m2, d1, d2) / 360.0
    }

    // 30E/360 ISDA day count factor calculation.
    pub(crate) fn day_count_factor_thirty_e_360_isda(start_date: Date, end_date: Date) -> f64 {
        let (y1, m1, mut d1) = Self::thirty_360_unpack_date(start_date);
        let (y2, m2, mut d2) = Self::thirty_360_unpack_date(end_date);

        if d1 == 31 || is_last_day_of_february(start_date) {
            d1 = 30;
        }

        if d2 == 31 || is_last_day_of_february(end_date) {
            d2 = 30;
        }

        Self::thirty_360_numerator(y1, y2, m1, m2, d1, d2) / 360.0
    }

    // 30E+/360 day count factor calculation.
    pub(crate) fn day_count_factor_thirty_e_plus_360(start_date: Date, end_date: Date) -> f64 {
        let (y1, m1, mut d1) = Self::thirty_360_unpack_date(start_date);
        let (mut y2, mut m2, mut d2) = Self::thirty_360_unpack_date(end_date);

        if d1 == 31 {
            d1 = 30;
        }

        if d2 == 31 {
            (y2, m2, d2) = Self::thirty_360_unpack_date(end_date.next_day().unwrap());
        }

        Self::thirty_360_numerator(y1, y2, m1, m2, d1, d2) / 360.0
    }

    // 30U/360 day count factor calculation.
    pub(crate) fn day_count_factor_thirty_u_360(start_date: Date, end_date: Date) -> f64 {
        let (y1, m1, mut d1) = Self::thirty_360_unpack_date(start_date);
        let (y2, m2, mut d2) = Self::thirty_360_unpack_date(end_date);

        if d1 == 31 || is_last_day_of_february(start_date) {
            d1 = 30;
        }

        if d2 == 31 && d1 == 30 || is_last_day_of_february(end_date) {
            d2 = 30;
        }

        Self::thirty_360_numerator(y1, y2, m1, m2, d1, d2) / 360.0
    }

    // 30E/365 day count factor calculation.
    pub(crate) fn day_count_factor_thirty_e_365(start_date: Date, end_date: Date) -> f64 {
        let (y1, m1, mut d1) = Self::thirty_360_unpack_date(start_date);
        let (y2, m2, mut d2) = Self::thirty_360_unpack_date(end_date);

        if d1 == 31 || is_last_day_of_february(start_date) {
            d1 = 30;
        }

        if d2 == 31 || is_last_day_of_february(end_date) {
            d2 = 30;
        }

        Self::thirty_360_numerator(y1, y2, m1, m2, d1, d2) / 365.0
    }

    /// Function to comput the 30/360 numerator.
    pub(crate) fn thirty_360_numerator(
        y1: i32,
        y2: i32,
        m1: i32,
        m2: i32,
        d1: i32,
        d2: i32,
    ) -> f64 {
        (360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)) as f64
    }

    /// Function to unpack the date components for 30/360 calculation.
    pub(crate) fn thirty_360_unpack_date(date: Date) -> (i32, i32, i32) {
        (date.year(), date.month() as i32, date.day() as i32)
    }
}

// UNIT TESTS

#[cfg(test)]
mod TESTS_thirty_360 {
    use crate::DayCountConvention;
    use time::macros::date;
    use RustQuant_utils::assert_approx_equal;
    use RustQuant_utils::RUSTQUANT_EPSILON;

    #[test]
    fn thirty_e_365() {
        let start_date = date!(2011 - 06 - 17);
        let end_date = date!(2012 - 12 - 30);

        let dcf = DayCountConvention::day_count_factor_thirty_e_365(start_date, end_date);

        assert_approx_equal!(dcf, 1.515_068_493, RUSTQUANT_EPSILON);
    }
}

#[cfg(test)]
mod TESTS_actual_constant {
    use crate::DayCountConvention;
    use time::macros::date;
    use RustQuant_utils::assert_approx_equal;
    use RustQuant_utils::RUSTQUANT_EPSILON;

    #[test]
    fn actual_365_25() {
        // Test cases from QuantLib.
        let test_dates: Vec<time::Date> = vec![
            date!(2002 - 02 - 1),
            date!(2002 - 02 - 4),
            date!(2003 - 05 - 16),
            date!(2003 - 12 - 17),
            date!(2004 - 12 - 17),
            date!(2005 - 12 - 19),
            date!(2006 - 01 - 02),
            date!(2006 - 03 - 13),
            date!(2006 - 05 - 15),
            date!(2006 - 03 - 17),
            date!(2006 - 05 - 15),
            date!(2006 - 07 - 26),
            date!(2007 - 06 - 28),
            date!(2009 - 09 - 16),
            date!(2016 - 07 - 26),
        ];

        let expected: Vec<f64> = vec![
            0.0082135523613963,
            1.27583846680356,
            0.588637919233402,
            1.00205338809035,
            1.00479123887748,
            0.0383299110198494,
            0.191649555099247,
            0.172484599589322,
            -0.161533196440794,
            0.161533196440794,
            0.197125256673511,
            0.922655715263518,
            2.22039698836413,
            6.85831622176591,
        ];

        for i in 1..test_dates.len() {
            let dcf = DayCountConvention::day_count_factor_actual_365_25(
                test_dates[i - 1],
                test_dates[i],
            );

            assert_approx_equal!(dcf, expected[i - 1], RUSTQUANT_EPSILON);
        }
    }

    #[test]
    fn actual_366() {
        // Test cases from QuantLib.
        let test_dates: Vec<time::Date> = vec![
            date!(2002 - 02 - 1),
            date!(2002 - 02 - 4),
            date!(2003 - 05 - 16),
            date!(2003 - 12 - 17),
            date!(2004 - 12 - 17),
            date!(2005 - 12 - 19),
            date!(2006 - 01 - 02),
            date!(2006 - 03 - 13),
            date!(2006 - 05 - 15),
            date!(2006 - 03 - 17),
            date!(2006 - 05 - 15),
            date!(2006 - 07 - 26),
            date!(2007 - 06 - 28),
            date!(2009 - 09 - 16),
            date!(2016 - 07 - 26),
        ];

        let expected: Vec<f64> = vec![
            0.00819672131147541,
            1.27322404371585,
            0.587431693989071,
            1.0000000000000,
            1.00273224043716,
            0.0382513661202186,
            0.191256830601093,
            0.172131147540984,
            -0.16120218579235,
            0.16120218579235,
            0.19672131147541,
            0.920765027322404,
            2.21584699453552,
            6.84426229508197,
        ];

        for i in 1..test_dates.len() {
            let dcf =
                DayCountConvention::day_count_factor_actual_366(test_dates[i - 1], test_dates[i]);

            assert_approx_equal!(dcf, expected[i - 1], RUSTQUANT_EPSILON);
        }
    }
}

#[cfg(test)]
mod TESTS_actual_actual {
    use crate::DayCountConvention;
    use time::macros::date;
    use RustQuant_utils::assert_approx_equal;
    use RustQuant_utils::RUSTQUANT_EPSILON;

    const DATE_1: time::Date = date!(2003 - 11 - 1);
    const DATE_2: time::Date = date!(2004 - 5 - 1);

    #[test]
    fn actual_actual_isda() {
        // Test cases from QuantLib.
        assert_approx_equal!(
            DayCountConvention::day_count_factor_actual_actual_isda(DATE_1, DATE_2),
            0.497724380567,
            RUSTQUANT_EPSILON
        );
    }

    #[test]
    fn actual_actual_icma() {
        // Test cases from QuantLib.
        assert_approx_equal!(
            DayCountConvention::day_count_factor_actual_actual_isda(DATE_1, DATE_2),
            0.497724380567,
            RUSTQUANT_EPSILON
        );
    }

    #[test]
    fn actual_actual_afb() {
        // Test cases from QuantLib.
        assert_approx_equal!(
            DayCountConvention::day_count_factor_actual_actual_afb(DATE_1, DATE_2),
            0.497267759563,
            RUSTQUANT_EPSILON
        );
    }
}