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
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc = include_str!("../README.md")]

use chrono::{Datelike, NaiveDate, Weekday};

mod arithmetic;
pub use arithmetic::DeltaBusinessDays;

mod iter;
mod luts;
use luts::{CAL2BUS, CALENDAR};

pub use iter::BusDaysIter;

pub type Result<T> = std::result::Result<T, OutOfRange>;

/// Holidays observed by the NYSE
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Holiday {
    NewYearsDay,
    MartinLutherKingJrDay,
    WashingtonsBirthday,
    GoodFriday,
    MemorialDay,
    Juneteenth,
    IndependenceDay,
    LaborDay,
    ThanksgivingDay,
    ChristmasDay,
}

/// Error type indicating that a date was outside the range of the existing NYSE holiday calendar
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OutOfRange;

/// Determine NYSE holiday information for dates
pub trait HolidayCal {
    /// Try to determine holiday information for this day.
    ///
    /// If it is not possible to determine whether the day is an NYSE market holiday, return
    /// `Err(OutOfRange)`. This will be the case if the date falls before [`MIN_YEAR`] or after
    /// [`MAX_YEAR`]. Otherwise return an `Option<Holiday>` describing which holiday it is:
    ///
    /// | Input | Output |
    /// | ----- | ------ |
    /// | Holiday status indefinite | `Err(OutOfRange)` |
    /// | Definite holiday | `Ok(Some(x))` where `x` identifies which holiday it is
    /// | Definite non-holiday | `Ok(None)` |
    ///
    /// Note: Weekends are **not** considered NYSE holidays.
    ///
    /// ## Examples
    /// ```
    /// use nyse_holiday_cal::{HolidayCal, OutOfRange, Holiday::*};
    /// use chrono::NaiveDate;
    ///
    /// // Holidays
    /// assert_eq!(NaiveDate::from_ymd_opt(2023, 4,  7).unwrap().holiday(), Ok(Some(GoodFriday)));
    /// assert_eq!(NaiveDate::from_ymd_opt(2023, 7,  4).unwrap().holiday(), Ok(Some(IndependenceDay)));
    /// assert_eq!(NaiveDate::from_ymd_opt(2024, 1,  1).unwrap().holiday(), Ok(Some(NewYearsDay)));
    /// assert_eq!(NaiveDate::from_ymd_opt(2025, 5, 26).unwrap().holiday(), Ok(Some(MemorialDay)));
    ///
    /// // Non-holidays
    /// assert_eq!(NaiveDate::from_ymd_opt(2023, 4, 20).unwrap().holiday(), Ok(None));
    /// assert_eq!(NaiveDate::from_ymd_opt(2025, 5,  1).unwrap().holiday(), Ok(None));
    ///
    ///
    /// // Out of range dates return Err
    /// assert_eq!(NaiveDate::from_ymd_opt(2027, 1, 1).unwrap().holiday(), Err(OutOfRange));
    /// assert_eq!(NaiveDate::from_ymd_opt(2016, 1, 1).unwrap().holiday(), Err(OutOfRange));
    /// ```
    fn holiday(&self) -> Result<Option<Holiday>>;

    /// Determine if `self` is in range of the existing holiday calendar. In general, it is not
    /// possible to determine if a date is an NYSE holiday if it is not in range.
    fn is_in_range(&self) -> bool;

    /// Determine if `self` is a weekend
    fn is_weekend(&self) -> bool;

    /// Get business day ordinal of a specific calendar date
    ///
    /// If `self` is a business day, return `Some(n)` such that `self` is the `n`<sup>th</sup>
    /// business day of the calendar month containing `self`, otherwise return `None`
    fn cal2bus(&self) -> Option<u8>;

    /// Get the day-of-month of the last business day of the calendar month containing `self`,
    /// or, if the date is out of range, return `Err(OutOfRange)`
    fn bus_month_end(&self) -> Result<u8>;

    /// Get the day-of-month of the first business day of the calendar month containing `self`,
    /// or, if the date is out of range, return `Err(OutOfRange)`
    fn bus_month_begin(&self) -> Result<u8>;

    /// Determine if `self` is an NYSE holiday
    fn is_holiday(&self) -> Result<bool> {
        Ok(self.holiday()?.is_some())
    }

    /// Determine if the NYSE is open for trading on a certain day.
    ///
    /// When it is possible to determine with certainty whether the NYSE is open for trading on
    /// `self`, return `Ok(b)` with the inner value indicating whether the date is an open market
    /// day. When it is not possible to determine, return `Err(OutOfRange)`. This is similar to
    /// [`Self::is_holiday`] except that it accounts for weekends as non-business days.
    ///
    /// Note: **all** weekends are considered definite non-business days even if they are outside
    /// the range of the calendar because the NYSE will never trade on a weekend.
    fn is_busday(&self) -> Result<bool> {
        Ok(!(self.is_weekend() || self.is_holiday()?))
    }

    /// Return an iterator of business days occuring after `self`. If reversed, it becomes an
    /// iterator over business days occuring before `self`. See the documentation for the return
    /// type [`BusDaysIter`] for details
    fn busday_iter(&self) -> crate::iter::BusDaysIter<Self>
    where
        iter::BusDaysIter<Self>: DoubleEndedIterator<Item = Self>,
        Self: Sized + Copy,
    {
        iter::BusDaysIter(*self)
    }

    /// Get the calendar day of a specific business day
    ///
    /// Return the calendar day (i.e. day-of-month) which is the `n`<sup>th</sup> business day of
    /// the `m`<sup>th</sup> month of year `y`.
    fn bus2cal(y: u16, m: u8, n: u8) -> Result<u8> {
        luts::BUS2CAL.get(&(y, m, n)).copied().ok_or(OutOfRange)
    }
}

/// Beginning of NYSE holiday calendar.
///
/// It is not possible to determine if a date is an NYSE market holiday if it is before 1 Jan of
/// this year
pub const MIN_YEAR: u16 = 2021;
/// End of NYSE holiday calendar.
///
/// It is not possible to determine if a date is an NYSE market holiday if it is after 31 Dec of
/// this year
pub const MAX_YEAR: u16 = 2026;

const RANGE: std::ops::RangeInclusive<u16> = MIN_YEAR..=MAX_YEAR;

impl HolidayCal for NaiveDate {
    fn holiday(&self) -> Result<Option<Holiday>> {
        if !self.is_in_range() {
            return Err(OutOfRange);
        }
        Ok(CALENDAR.get(self).copied())
    }

    fn is_in_range(&self) -> bool {
        self.year()
            .try_into()
            .map_or(false, |x: u16| RANGE.contains(&x))
    }

    fn is_weekend(&self) -> bool {
        use Weekday::*;
        self.weekday() == Sat || self.weekday() == Sun
    }

    fn cal2bus(&self) -> Option<u8> {
        CAL2BUS.get(self).copied()
    }

    fn bus_month_end(&self) -> Result<u8> {
        let month = (
            self.year().try_into().unwrap(),
            self.month().try_into().unwrap(),
        );
        luts::MONTH_BUS_RANGE
            .get(&month)
            .map(|x| *x.end())
            .ok_or(OutOfRange)
    }

    fn bus_month_begin(&self) -> Result<u8> {
        let month = (
            self.year().try_into().unwrap(),
            self.month().try_into().unwrap(),
        );
        luts::MONTH_BUS_RANGE
            .get(&month)
            .map(|x| *x.start())
            .ok_or(OutOfRange)
    }
}

#[cfg(feature = "time")]
impl HolidayCal for time::Date {
    fn holiday(&self) -> Result<Option<Holiday>> {
        if !self.is_in_range() {
            return Err(OutOfRange);
        }
        let (y, d) = (self.year(), self.day().into());
        let m: u8 = self.month().into();
        let naive_date = NaiveDate::from_ymd_opt(y, m.into(), d).unwrap();
        Ok(CALENDAR.get(&naive_date).copied())
    }
    fn is_in_range(&self) -> bool {
        self.year()
            .try_into()
            .map_or(false, |x: u16| RANGE.contains(&x))
    }
    fn is_weekend(&self) -> bool {
        use time::Weekday::*;
        self.weekday() == Saturday || self.weekday() == Sunday
    }

    fn cal2bus(&self) -> Option<u8> {
        let (y, d) = (self.year(), self.day().into());
        let m: u8 = self.month().into();
        let naive_date = NaiveDate::from_ymd_opt(y, m.into(), d).unwrap();
        CAL2BUS.get(&naive_date).copied()
    }

    fn bus_month_end(&self) -> Result<u8> {
        let month = (self.year().try_into().unwrap(), self.month().into());
        luts::MONTH_BUS_RANGE
            .get(&month)
            .map(|x| *x.end())
            .ok_or(OutOfRange)
    }

    fn bus_month_begin(&self) -> Result<u8> {
        let month = (self.year().try_into().unwrap(), self.month().into());
        luts::MONTH_BUS_RANGE
            .get(&month)
            .map(|x| *x.start())
            .ok_or(OutOfRange)
    }
}

#[cfg(test)]
mod tests {
    use chrono::NaiveDate;
    use lazy_static::lazy_static;

    mod naive_date;

    #[cfg(feature = "time")]
    mod date;

    lazy_static! {
        #[rustfmt::skip]
        static ref WEEKENDS_VECTORS: [NaiveDate; 20] = [
            NaiveDate::from_ymd_opt(2023,  1,  1).unwrap(),
            NaiveDate::from_ymd_opt(2023,  1,  7).unwrap(),
            NaiveDate::from_ymd_opt(2023,  1,  8).unwrap(),
            NaiveDate::from_ymd_opt(2023,  1, 14).unwrap(),
            NaiveDate::from_ymd_opt(2023,  1, 15).unwrap(),
            NaiveDate::from_ymd_opt(2023,  1, 21).unwrap(),
            NaiveDate::from_ymd_opt(2023,  2,  4).unwrap(),
            NaiveDate::from_ymd_opt(2023,  2,  5).unwrap(),
            NaiveDate::from_ymd_opt(2023,  2, 26).unwrap(),
            NaiveDate::from_ymd_opt(2023,  6, 18).unwrap(),
            NaiveDate::from_ymd_opt(2023,  6, 24).unwrap(),
            NaiveDate::from_ymd_opt(2023,  6, 25).unwrap(),
            NaiveDate::from_ymd_opt(2023, 11,  4).unwrap(),
            NaiveDate::from_ymd_opt(2023, 11,  5).unwrap(),
            NaiveDate::from_ymd_opt(2023, 11, 11).unwrap(),
            NaiveDate::from_ymd_opt(2023, 11, 12).unwrap(),
            NaiveDate::from_ymd_opt(2023, 11, 18).unwrap(),
            NaiveDate::from_ymd_opt(2023, 11, 19).unwrap(),
            NaiveDate::from_ymd_opt(2023, 11, 25).unwrap(),
            NaiveDate::from_ymd_opt(2023, 11, 26).unwrap(),
        ];

        #[rustfmt::skip]
        static ref BUSDAYS: [NaiveDate; 15] = [
            NaiveDate::from_ymd_opt(2023,  1,  3).unwrap(),
            NaiveDate::from_ymd_opt(2023,  1,  4).unwrap(),
            NaiveDate::from_ymd_opt(2023,  1,  5).unwrap(),
            NaiveDate::from_ymd_opt(2023,  1,  6).unwrap(),
            NaiveDate::from_ymd_opt(2023,  1,  9).unwrap(),
            NaiveDate::from_ymd_opt(2023,  3,  7).unwrap(),
            NaiveDate::from_ymd_opt(2023,  3, 27).unwrap(),
            NaiveDate::from_ymd_opt(2023,  3, 28).unwrap(),
            NaiveDate::from_ymd_opt(2024,  6,  7).unwrap(),
            NaiveDate::from_ymd_opt(2024,  7,  8).unwrap(),
            NaiveDate::from_ymd_opt(2024,  7,  9).unwrap(),
            NaiveDate::from_ymd_opt(2024,  7, 12).unwrap(),
            NaiveDate::from_ymd_opt(2024, 10, 10).unwrap(),
            NaiveDate::from_ymd_opt(2024, 10, 11).unwrap(),
            NaiveDate::from_ymd_opt(2024, 10, 14).unwrap(), // Columbus Day, not a NYSE holiday
        ];
    }
}