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
//! Implementation of (bank) holidays.
//! Calendars are required to verify whether an exchange is open or if a certain
//! cash flow could be settled on a specific day. They are also needed to calculate
//! the amount of business days between to given dates.
//! Because of the settlement rules, bank holidays have an impact on how to
//! rollout cash flows from fixed income products.
//! The approach taken here is to define a set of rules to determine bank holidays.
//! From this set of rules, a calendar is generated by calculating all bank holidays
//! within a given range of years for fast access.

use time::{Date, Duration, Weekday};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use std::collections::BTreeSet;

mod calendar_definitions;

pub use calendar_definitions::*;


#[derive(Error, Debug)]
/// Error class for calendar calculation
pub enum CalendarError {
    #[error("calendar could not been found")]
    CalendarNotFound,
    #[error("failed to create invalid date")]
    OutOfBound(#[from]time::error::ComponentRange),
    #[error("try to proceed beyond max date")]
    MaxDay,
    #[error("try to proceed before min date")]
    MinDay,
}

type Result<T> = std::result::Result<T, CalendarError>;

/// Specifies the nth week of a month
#[derive(Deserialize, Serialize, Debug, PartialEq)]
pub enum NthWeek {
    First,
    Second,
    Third,
    Fourth,
    Last,
    SecondLast,
    ThirdLast,
    FourthLast,
}

#[derive(Deserialize, Serialize, Debug, PartialEq)]
pub enum Holiday {
    /// Though weekends are no holidays, they need to be specified in the calendar. Weekends are assumed to be non-business days.
    /// In most countries, weekends include Saturday (`Sat`) and Sunday (`Sun`). Unfortunately, there are a few exceptions.
    WeekDay(Weekday),
    /// A holiday that occurs every year on the same day.
    /// `first` and `last` are the first and last year this day is a holiday (inclusively).
    YearlyDay {
        month: u8,
        day: u8,
        first: Option<i32>,
        last: Option<i32>,
    },
    /// Occurs every year, but is moved to next non-weekend day if it falls on a weekend.
    /// Note that Saturday and Sunday here assumed to be weekend days, even if these days
    /// are not defined as weekends in this calendar. If the next Monday is already a holiday,
    /// the date will be moved to the next available business day.
    /// `first` and `last` are the first and last year this day is a holiday (inclusively).
    MovableYearlyDay {
        month: u8,
        day: u8,
        first: Option<i32>,
        last: Option<i32>,
    },
    /// Occurs every year, but is moved to previous Friday if it falls on Saturday
    /// and to the next Monday if it falls on a Sunday.
    /// `first` and `last` are the first and last year this day is a holiday (inclusively).
    ModifiedMovableYearlyDay {
        month: u8,
        day: u8,
        first: Option<i32>,
        last: Option<i32>,
    },
    /// A single holiday which is valid only once in time.
    SingularDay(Date),
    /// A holiday that is defined in relative days (e.g. -2 for Good Friday) to Easter (Sunday).
    EasterOffset {
        offset: i32,
        first: Option<i32>,
        last: Option<i32>,
    },
    /// A holiday that falls on the nth (or last) weekday of a specific month, e.g. the first Monday in May.
    /// `first` and `last` are the first and last year this day is a holiday (inclusively).
    MonthWeekday {
        month: u8,
        weekday: Weekday,
        nth: NthWeek,
        first: Option<i32>,
        last: Option<i32>,
    },
}

/// Calendar for arbitrary complex holiday rules
#[derive(Debug, Clone)]
pub struct Calendar {
    holidays: BTreeSet<Date>,
    weekdays: Vec<Weekday>,
}

fn new_date(year: i32, month: u8, day: u8) -> Result<Date> {
    Ok(Date::from_calendar_date(year, month.try_into()?, day)?)
}

impl Calendar {
    /// Calculate all holidays and recognize weekend days for a given range of years
    /// from `start` to `end` (inclusively). The calculation is performed on the basis
    /// of a vector of holiday rules.
    pub fn calc_calendar(holiday_rules: &[Holiday], start: i32, end: i32) -> Result<Calendar> {
        let mut holidays = BTreeSet::new();
        let mut weekdays = Vec::new();

        for rule in holiday_rules {
            match rule {
                Holiday::SingularDay(date) => {
                    let year = date.year();
                    if year >= start && year <= end {
                        holidays.insert(*date);
                    }
                }
                Holiday::WeekDay(weekday) => {
                    weekdays.push(*weekday);
                }
                Holiday::YearlyDay {
                    month,
                    day,
                    first,
                    last,
                } => {
                    let (first, last) = Self::calc_first_and_last(start, end, first, last);
                    for year in first..last + 1 {
                        holidays.insert( new_date(year, *month, *day)?);
                    }
                }
                Holiday::MovableYearlyDay {
                    month,
                    day,
                    first,
                    last,
                } => {
                    let (first, last) = Self::calc_first_and_last(start, end, first, last);
                    for year in first..last + 1 {
                        let date = new_date(year, *month, *day)?;
                        let mut date = match date.weekday() {
                            Weekday::Saturday => date.next_day().ok_or(CalendarError::MaxDay)?.next_day().ok_or(CalendarError::MaxDay)?,
                            Weekday::Sunday => date.next_day().ok_or(CalendarError::MaxDay)?,
                            _ => date,
                        };
                        while holidays.get(&date).is_some() {
                            date = date.next_day().ok_or(CalendarError::MaxDay)?;
                        }
                        holidays.insert(date);
                    }
                }
                Holiday::ModifiedMovableYearlyDay {
                    month,
                    day,
                    first,
                    last,
                } => {
                    let (first, last) = Self::calc_first_and_last(start, end, first, last);
                    for year in first..last + 1 {
                        let date = new_date(year, *month, *day)?;
                        let moved_date = match date.weekday() {
                            Weekday::Saturday => date.previous_day().ok_or(CalendarError::MinDay)?,
                            Weekday::Sunday => date.next_day().ok_or(CalendarError::MaxDay)?,
                            _ => date,
                        };
                        if moved_date.month() == date.month() {
                            holidays.insert(moved_date);
                        } else {
                            holidays.insert(date);
                        }
                    }
                }
                Holiday::EasterOffset {
                    offset,
                    first,
                    last,
                } => {
                    let (first, last) = Self::calc_first_and_last(start, end, first, last);
                    for year in first..last + 1 {
                        let easter = computus::gregorian(year).unwrap();
                        let easter = new_date(easter.year, easter.month as u8, easter.day as u8)?;
                        let date = easter.checked_add(Duration::days(*offset as i64)).unwrap();
                        holidays.insert(date);
                    }
                }
                Holiday::MonthWeekday {
                    month,
                    weekday,
                    nth,
                    first,
                    last,
                } => {
                    let (first, last) = Self::calc_first_and_last(start, end, first, last);
                    for year in first..last + 1 {
                        let day = match nth {
                            NthWeek::First => 1,
                            NthWeek::Second => 8,
                            NthWeek::Third => 15,
                            NthWeek::Fourth => 22,
                            NthWeek::Last => last_day_of_month(year, *month),
                            NthWeek::SecondLast => last_day_of_month(year, *month)-7,
                            NthWeek::ThirdLast => last_day_of_month(year, *month)-14,
                            NthWeek::FourthLast => last_day_of_month(year, *month)-21,
                        };
                        let mut date = new_date(year, *month, day)?;
                        while date.weekday() != *weekday {
                            date = match nth {
                                NthWeek::Last 
                                | NthWeek::SecondLast
                                | NthWeek::ThirdLast
                                | NthWeek::FourthLast => date.previous_day().ok_or(CalendarError::MinDay)?,
                                _ => date.next_day().ok_or(CalendarError::MaxDay)?,
                            }
                        }
                        holidays.insert(date);
                    }
                }
            }
        }
        Ok(Calendar { holidays, weekdays })
    }

    /// Calculate the next business day
    pub fn next_bday(&self, date: Date) -> Result<Date> {
        let mut date = date.next_day().ok_or(CalendarError::MaxDay)?;
        while !self.is_business_day(date) {
            date = date.next_day().ok_or(CalendarError::MaxDay)?;
        }
        Ok(date)
    }

    /// Calculate the previous business day
    pub fn prev_bday(&self, date: Date) -> Result<Date> {
        let mut date = date.previous_day().ok_or(CalendarError::MinDay)?;
        while !self.is_business_day(date) {
            date = date.previous_day().ok_or(CalendarError::MinDay)?;
        }
        Ok(date)
    }

    fn calc_first_and_last(
        start: i32,
        end: i32,
        first: &Option<i32>,
        last: &Option<i32>,
    ) -> (i32, i32) {
        let first = match first {
            Some(year) => std::cmp::max(start, *year),
            _ => start,
        };
        let last = match last {
            Some(year) => std::cmp::min(end, *year),
            _ => end,
        };
        (first, last)
    }

    /// Returns true if the date falls on a weekend
    pub fn is_weekend(&self, day: Date) -> bool {
        let weekday = day.weekday();
        for w_day in &self.weekdays {
            if weekday == *w_day {
                return true;
            }
        }
        false
    }

    /// Returns true if the specified day is a bank holiday
    pub fn is_holiday(&self, date: Date) -> bool {
        self.holidays.get(&date).is_some()
    }

    /// Returns true if the specified day is a business day
    pub fn is_business_day(&self, date: Date) -> bool {
        !self.is_weekend(date) && !self.is_holiday(date)
    }
}

pub trait CalendarProvider {
    fn get_calendar(&self, calendar_name: &str) -> Result<&Calendar>;
}

/// Returns true if the specified year is a leap year (i.e. Feb 29th exists for this year)
pub fn is_leap_year(year: i32) -> bool {
    new_date(year, 2, 29).is_ok()
}

/// Calculate the last day of a given month in a given year
pub fn last_day_of_month(year: i32, month: u8) -> u8 {
    if let Ok(date) = new_date(year, month + 1, 1) {
        date.previous_day().unwrap().day()
    } else {
        // last day of December
        31
    }
}

pub struct SimpleCalendar {
    cal: Calendar,
}

impl SimpleCalendar {
    pub fn new(cal: &Calendar) -> SimpleCalendar {
        SimpleCalendar { cal: cal.clone() }
    }
}

impl CalendarProvider for SimpleCalendar {
    fn get_calendar(&self, _calendar_name: &str) -> Result<&Calendar> {
        Ok(&self.cal)
    }
}

impl Default for SimpleCalendar {
    fn default() -> SimpleCalendar {
        SimpleCalendar {
            cal: Calendar::calc_calendar(&[], 2020, 2021).unwrap(),
        }
    }
}

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

    #[test]
    fn fixed_dates_calendar() {
        let holidays = vec![
            Holiday::SingularDay(date!(2019-11-20)),
            Holiday::SingularDay(date!(2019-11-24)),
            Holiday::SingularDay(date!(2019-11-25)),
            Holiday::WeekDay(Weekday::Saturday),
            Holiday::WeekDay(Weekday::Sunday),
        ];
        let cal = Calendar::calc_calendar(&holidays, 2019, 2019).unwrap();

        assert_eq!(
            false,
            cal.is_business_day(date!(2019-11-20))
        );
        assert_eq!(true, cal.is_business_day(date!(2019-11-21)));
        assert_eq!(true, cal.is_business_day(date!(2019-11-22)));
        // weekend
        assert_eq!(
            false,
            cal.is_business_day(date!(2019-11-23))
        );
        assert_eq!(true, cal.is_weekend(date!(2019-11-23)));
        assert_eq!(false, cal.is_holiday(date!(2019-11-23)));
        // weekend and holiday
        assert_eq!(
            false,
            cal.is_business_day(date!(2019-11-24))
        );
        assert_eq!(true, cal.is_weekend(date!(2019-11-24)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-24)));
        assert_eq!(
            false,
            cal.is_business_day(date!(2019-11-25))
        );
        assert_eq!(true, cal.is_business_day(date!(2019-11-26)));
    }

    #[test]
    fn test_yearly_day() {
        let holidays = vec![
            Holiday::YearlyDay {
                month: 11,
                day: 1,
                first: None,
                last: None,
            },
            Holiday::YearlyDay {
                month: 11,
                day: 2,
                first: Some(2019),
                last: None,
            },
            Holiday::YearlyDay {
                month: 11,
                day: 3,
                first: None,
                last: Some(2019),
            },
            Holiday::YearlyDay {
                month: 11,
                day: 4,
                first: Some(2019),
                last: Some(2019),
            },
        ];
        let cal = Calendar::calc_calendar(&holidays, 2018, 2020).unwrap();

        assert_eq!(true, cal.is_holiday(date!(2018-11-1)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-1)));
        assert_eq!(true, cal.is_holiday(date!(2020-11-1)));

        assert_eq!(false, cal.is_holiday(date!(2018-11-2)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-2)));
        assert_eq!(true, cal.is_holiday(date!(2020-11-2)));

        assert_eq!(true, cal.is_holiday(date!(2018-11-3)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-3)));
        assert_eq!(false, cal.is_holiday(date!(2020-11-3)));

        assert_eq!(false, cal.is_holiday(date!(2018-11-4)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-4)));
        assert_eq!(false, cal.is_holiday(date!(2020-11-4)));
    }

    #[test]
    fn test_movable_yearly_day() {
        let holidays = vec![
            Holiday::MovableYearlyDay {
                month: 11,
                day: 1,
                first: None,
                last: None,
            },
            Holiday::MovableYearlyDay {
                month: 11,
                day: 2,
                first: None,
                last: None,
            },
            Holiday::MovableYearlyDay {
                month: 11,
                day: 10,
                first: None,
                last: Some(2019),
            },
            Holiday::MovableYearlyDay {
                month: 11,
                day: 17,
                first: Some(2019),
                last: None,
            },
            Holiday::MovableYearlyDay {
                month: 11,
                day: 24,
                first: Some(2019),
                last: Some(2019),
            },
        ];
        let cal = Calendar::calc_calendar(&holidays, 2018, 2020).unwrap();
        assert_eq!(true, cal.is_holiday(date!(2018-11-1)));
        assert_eq!(true, cal.is_holiday(date!(2018-11-2)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-1)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-4)));
        assert_eq!(true, cal.is_holiday(date!(2020-11-2)));
        assert_eq!(true, cal.is_holiday(date!(2020-11-3)));

        assert_eq!(true, cal.is_holiday(date!(2018-11-12)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-11)));
        assert_eq!(false, cal.is_holiday(date!(2020-11-10)));
        assert_eq!(false, cal.is_holiday(date!(2018-11-19)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-18)));
        assert_eq!(true, cal.is_holiday(date!(2020-11-17)));
        assert_eq!(false, cal.is_holiday(date!(2018-11-26)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-25)));
        assert_eq!(false, cal.is_holiday(date!(2020-11-24)));
    }

    #[test]
    /// Good Friday example
    fn test_easter_offset() {
        let holidays = vec![Holiday::EasterOffset {
            offset: -2,
            first: None,
            last: None,
        }];
        let cal = Calendar::calc_calendar(&holidays, 2019, 2020).unwrap();
        assert_eq!(false, cal.is_business_day(date!(2019-4-19)));
        assert_eq!(false, cal.is_business_day(date!(2020-4-10)));
    }

    #[test]
    fn test_month_weekday() {
        let holidays = vec![
            Holiday::MonthWeekday {
                month: 11,
                weekday: Weekday::Monday,
                nth: NthWeek::First,
                first: None,
                last: None,
            },
            Holiday::MonthWeekday {
                month: 11,
                weekday: Weekday::Tuesday,
                nth: NthWeek::Second,
                first: None,
                last: None,
            },
            Holiday::MonthWeekday {
                month: 11,
                weekday: Weekday::Wednesday,
                nth: NthWeek::Third,
                first: None,
                last: None,
            },
            Holiday::MonthWeekday {
                month: 11,
                weekday: Weekday::Thursday,
                nth: NthWeek::Fourth,
                first: None,
                last: None,
            },
            Holiday::MonthWeekday {
                month: 11,
                weekday: Weekday::Friday,
                nth: NthWeek::Last,
                first: None,
                last: None,
            },
            Holiday::MonthWeekday {
                month: 11,
                weekday: Weekday::Saturday,
                nth: NthWeek::First,
                first: None,
                last: Some(2018),
            },
            Holiday::MonthWeekday {
                month: 11,
                weekday: Weekday::Sunday,
                nth: NthWeek::Last,
                first: Some(2020),
                last: None,
            },
        ];
        let cal = Calendar::calc_calendar(&holidays, 2018, 2020).unwrap();
        assert_eq!(true, cal.is_holiday(date!(2019-11-4)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-12)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-20)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-28)));
        assert_eq!(true, cal.is_holiday(date!(2019-11-29)));

        assert_eq!(true, cal.is_holiday(date!(2018-11-3)));
        assert_eq!(false, cal.is_holiday(date!(2019-11-2)));
        assert_eq!(false, cal.is_holiday(date!(2020-11-7)));
        assert_eq!(false, cal.is_holiday(date!(2018-11-25)));
        assert_eq!(false, cal.is_holiday(date!(2019-11-24)));
        assert_eq!(true, cal.is_holiday(date!(2020-11-29)));
    }

    #[test]
    /// Testing serialization and deserialization of holidays definitions
    fn serialize_cal_definition() {
        let holidays = vec![
            Holiday::MonthWeekday {
                month: 11,
                weekday: Weekday::Monday,
                nth: NthWeek::First,
                first: None,
                last: None,
            },
            Holiday::MovableYearlyDay {
                month: 11,
                day: 1,
                first: Some(2016),
                last: None,
            },
            Holiday::YearlyDay {
                month: 11,
                day: 3,
                first: None,
                last: Some(2019),
            },
            Holiday::SingularDay(date!(2019-11-25)),
            Holiday::WeekDay(Weekday::Saturday),
            Holiday::EasterOffset {
                offset: -2,
                first: None,
                last: None,
            },
        ];
        let json = serde_json::to_string_pretty(&holidays).unwrap();
        assert_eq!(
            json,
            r#"[
  {
    "MonthWeekday": {
      "month": 11,
      "weekday": 1,
      "nth": "First",
      "first": null,
      "last": null
    }
  },
  {
    "MovableYearlyDay": {
      "month": 11,
      "day": 1,
      "first": 2016,
      "last": null
    }
  },
  {
    "YearlyDay": {
      "month": 11,
      "day": 3,
      "first": null,
      "last": 2019
    }
  },
  {
    "SingularDay": [
      2019,
      329
    ]
  },
  {
    "WeekDay": 6
  },
  {
    "EasterOffset": {
      "offset": -2,
      "first": null,
      "last": null
    }
  }
]"#
        );
        let holidays2: Vec<Holiday> = serde_json::from_str(&json).unwrap();
        assert_eq!(holidays.len(), holidays2.len());
        for i in 0..holidays.len() {
            assert_eq!(holidays[i], holidays2[i]);
        }
    }

    #[test]
    fn test_modified_movable() {
        let holidays = vec![
            Holiday::ModifiedMovableYearlyDay {
                month: 12,
                day: 25,
                first: None,
                last: None,
            },
            Holiday::ModifiedMovableYearlyDay {
                month: 1,
                day: 1,
                first: None,
                last: None,
            },
        ];
        let cal = Calendar::calc_calendar(&holidays, 2020, 2023).unwrap();
        assert!(cal.is_holiday(date!(2020-12-25)));
        assert!(cal.is_holiday(date!(2021-12-24)));
        assert!(cal.is_holiday(date!(2022-12-26)));
        assert!(cal.is_holiday(date!(2023-12-25)));
        assert!(cal.is_holiday(date!(2020-1-1)));
        assert!(cal.is_holiday(date!(2021-1-1)));
        assert!(cal.is_holiday(date!(2022-1-1)));
        assert!(cal.is_holiday(date!(2023-1-2)));
    }
}