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
//! 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 chrono::{Datelike, Duration, NaiveDate, Weekday};
use std::collections::BTreeSet;
use serde::{Deserialize,Serialize};
use computus;

/// Specify a day count method
#[derive(Deserialize, Serialize, Debug)]
pub enum DayCountConv {
    #[serde(rename = "act/act icma")]
    #[serde(alias = "Act/Act")]
    #[serde(alias = "Act/Act ICMA")]
    ActActICMA,
    #[serde(rename = "act/365")]
    Act365,
    #[serde(rename = "30/360")]
    D30_360,
    #[serde(rename = "30E/360")]
    D30E360,
}

/// Rules to adjust dates to business days
/// The rule "Modified Preceding" commonly referred to in text books
/// was intentionally left out since 
#[derive(Deserialize, Serialize, Debug)]
pub enum DayAdjust {
    #[serde(rename = "following")]
    Following,
    #[serde(rename = "preceding")]
    Preceding,
    /// Next business day, if it falls in the same month, otherwise preceding business day
    #[serde(rename = "modified")]
    #[serde(alias = "modified following")]
    Modified,
}

/// Specifies the nth week of a month
pub enum NthWeek {
    First,
    Second,
    Third,
    Fourth,
    Last,
}

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: u32,
        day: u32,
        first: Option<i32>,
        last: Option<i32>,
    },
    /// Occurs every year, but is moved to next non-weekend day if it falls on a weekday.
    /// 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: u32,
        day: u32,
        first: Option<i32>,
        last: Option<i32>,
    },
    /// A single holiday which is valid only once in time.
    SingularDay(NaiveDate),
    /// A holiday that is defined in relative days (e.g. -2 for Good Friday) to Easter (Sunday).
    EasterOffset(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: u32,
        weekday: Weekday,
        nth: NthWeek,
        first: Option<i32>,
        last: Option<i32>,
    },
}

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

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: &Vec<Holiday>, start: i32, end: i32) -> 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.clone());
                    }
                }
                Holiday::WeekDay(weekday) => {
                    weekdays.push(weekday.clone());
                }
                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(NaiveDate::from_ymd(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 = NaiveDate::from_ymd(year, *month, *day);
                        // must not fall on weekend, but also not on another holiday! (not yet implemented)
                        let mut date = match date.weekday() {
                            Weekday::Sat => date.succ().succ(),
                            Weekday::Sun => date.succ(),
                            _ => date,
                        };
                        while holidays.get(&date).is_some() {
                            date = date.succ();
                        }
                        holidays.insert(date);
                    }
                }
                Holiday::EasterOffset(offset) => {
                    for year in start..end + 1 {
                        let easter = computus::gregorian(year).unwrap();
                        let easter = NaiveDate::from_ymd(easter.year, easter.month, easter.day);
                        let date = easter
                            .checked_add_signed(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),
                        };
                        let mut date = NaiveDate::from_ymd(year, *month, day);
                        while date.weekday() != *weekday {
                            date = match nth {
                                NthWeek::Last => date.pred(),
                                _ => date.succ(),
                            }
                        }
                        holidays.insert(date);
                    }
                }
            }
        }
        Calendar {
            holidays: holidays,
            weekdays: weekdays,
        }
    }

    /// Calculate the next business day
    pub fn next_bday(&self, mut date: NaiveDate) -> NaiveDate {
        date = date.succ();
        while !self.is_business_day(date) {
            date = date.succ();
        }
        date
    }

    /// Calculate the previous business day
    pub fn prev_bday(&self, mut date: NaiveDate) -> NaiveDate {
        date = date.pred();
        while !self.is_business_day(date) {
            date = date.pred();
        }
        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: NaiveDate) -> 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: NaiveDate) -> bool {
        self.holidays.get(&date).is_some()
    }

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

/// 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 {
    NaiveDate::from_ymd_opt(year, 2, 29).is_some()
}

/// Calculate the last day of a given month in a given year
pub fn last_day_of_month(year: i32, month: u32) -> u32 {
    NaiveDate::from_ymd_opt(year, month + 1, 1)
        .unwrap_or(NaiveDate::from_ymd(year + 1, 1, 1))
        .pred()
        .day()
}

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

    #[test]
    fn fixed_dates_calendar() {
        let holidays = vec![
            Holiday::SingularDay(NaiveDate::from_ymd(2019, 11, 20)),
            Holiday::SingularDay(NaiveDate::from_ymd(2019, 11, 24)),
            Holiday::SingularDay(NaiveDate::from_ymd(2019, 11, 25)),
            Holiday::WeekDay(Weekday::Sat),
            Holiday::WeekDay(Weekday::Sun),
        ];
        let cal = Calendar::calc_calendar(&holidays, 2019, 2019);

        assert_eq!(false, cal.is_business_day(NaiveDate::from_ymd(2019, 11, 20)));
        assert_eq!(true, cal.is_business_day(NaiveDate::from_ymd(2019, 11, 21)));
        assert_eq!(true, cal.is_business_day(NaiveDate::from_ymd(2019, 11, 22)));
        // weekend
        assert_eq!(false, cal.is_business_day(NaiveDate::from_ymd(2019, 11, 23)));
        assert_eq!(true, cal.is_weekend(NaiveDate::from_ymd(2019, 11, 23)));
        assert_eq!(false, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 23)));
        // weekend and holiday
        assert_eq!(false, cal.is_business_day(NaiveDate::from_ymd(2019, 11, 24)));
        assert_eq!(true, cal.is_weekend(NaiveDate::from_ymd(2019, 11, 24)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 24)));
        assert_eq!(false, cal.is_business_day(NaiveDate::from_ymd(2019, 11, 25)));
        assert_eq!(true, cal.is_business_day(NaiveDate::from_ymd(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);
        
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2018, 11, 1)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 1)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2020, 11, 1)));

        assert_eq!(false, cal.is_holiday(NaiveDate::from_ymd(2018, 11, 2)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 2)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2020, 11, 2)));

        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2018, 11, 3)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 3)));
        assert_eq!(false, cal.is_holiday(NaiveDate::from_ymd(2020, 11, 3)));

        assert_eq!(false, cal.is_holiday(NaiveDate::from_ymd(2018, 11, 4)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 4)));
        assert_eq!(false, cal.is_holiday(NaiveDate::from_ymd(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);
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2018, 11, 1)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2018, 11, 2)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 1)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 4)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2020, 11, 2)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2020, 11, 3)));

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

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

    #[test]
    fn test_month_weekday() {        
        let holidays = vec![
            Holiday::MonthWeekday{month: 11, weekday: Weekday::Mon, nth: NthWeek::First, first: None, last: None },
            Holiday::MonthWeekday{month: 11, weekday: Weekday::Tue, nth: NthWeek::Second, first: None, last: None },
            Holiday::MonthWeekday{month: 11, weekday: Weekday::Wed, nth: NthWeek::Third, first: None, last: None },
            Holiday::MonthWeekday{month: 11, weekday: Weekday::Thu, nth: NthWeek::Fourth, first: None, last: None },
            Holiday::MonthWeekday{month: 11, weekday: Weekday::Fri, nth: NthWeek::Last, first: None, last: None },

            Holiday::MonthWeekday{month: 11, weekday: Weekday::Sat, nth: NthWeek::First, first: None, last: Some(2018) },
            Holiday::MonthWeekday{month: 11, weekday: Weekday::Sun, nth: NthWeek::Last, first: Some(2020), last: None },
        ];
        let cal = Calendar::calc_calendar(&holidays, 2018, 2020);
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 4)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 12)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 20)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 28)));
        assert_eq!(true, cal.is_holiday(NaiveDate::from_ymd(2019, 11, 29)));

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