Debian Codegraph @

exchange_calendars/pandas_extensions/holiday.py

raw
1 # https://github.com/pandas-dev/pandas/blob/master/pandas/tseries/holiday.py
2
3 import warnings
4
5 from pandas.tseries.holiday import (
6 Holiday as PandasHoliday,
7 AbstractHolidayCalendar as PandasAbstractHolidayCalendar,
8 )
9 from pandas.tseries.offsets import BaseOffset
10 from pandas import (
11 DatetimeIndex,
12 Series,
13 Timestamp,
14 )
15 from pandas.errors import PerformanceWarning
16
17 from .offsets import _is_normalized
18
19
20 class Holiday(PandasHoliday):
21 """
22 This extension allows to have both offset and observance while the original
23 Holiday does not. The order of application is offset => observance.
24 """
25
26 def __init__(
27 self,
28 name,
29 year=None,
30 month=None,
31 day=None,
32 offset=None,
33 observance=None,
34 start_date=None,
35 end_date=None,
36 days_of_week=None,
37 tz=None,
38 ):
39 super().__init__(
40 name,
41 year,
42 month,
43 day,
44 None,
45 None,
46 start_date,
47 end_date,
48 days_of_week,
49 )
50 self.offset = offset
51 self.observance = observance
52 self.tz = tz
53 if self.start_date is not None:
54 if self.tz is None and self.start_date.tz is not None:
55 self.tz = start_date.tz
56 if self.start_date.tz is None and self.tz is not None:
57 self.start_date = self.start_date.tz_localize(self.tz)
58 assert self.tz == self.start_date.tz
59 if self.end_date is not None:
60 if self.tz is None and self.end_date.tz is not None:
61 self.tz = end_date.tz
62 if self.end_date.tz is None and self.tz is not None:
63 self.end_date = self.end_date.tz_localize(self.tz)
64 assert self.tz == self.end_date.tz
65 if self.start_date is not None and self.end_date is not None:
66 assert self.start_date.tz == self.end_date.tz
67
68 def __repr__(self) -> str:
69 info = ""
70 if self.year is not None:
71 info += f"year={self.year}, "
72 info += f"month={self.month}, day={self.day}"
73
74 if self.offset is not None:
75 info += f", offset={self.offset}"
76
77 if self.observance is not None:
78 info += f", observance={self.observance}"
79
80 return f"{self.__class__.__name__}: {self.name} ({info})"
81
82 def dates(self, start_date, end_date, return_name=False):
83 start_date = Timestamp(start_date)
84 end_date = Timestamp(end_date)
85 assert start_date.tz == self.tz
86 assert _is_normalized(start_date)
87 assert end_date.tz == self.tz
88 assert _is_normalized(end_date)
89 return super().dates(start_date, end_date, return_name=return_name)
90
91 def _apply_offset(self, dates):
92 if self.offset is not None:
93 if not isinstance(self.offset, list):
94 offsets = [self.offset]
95 else:
96 offsets = self.offset
97 for offset in offsets:
98 # If we are adding a non-vectorized value
99 # ignore the PerformanceWarnings:
100 with warnings.catch_warnings():
101 warnings.simplefilter("ignore", PerformanceWarning)
102 dates += offset
103 return dates
104
105 def _apply_observance(self, dates):
106 if self.observance is not None:
107 if not isinstance(self.observance, list):
108 observances = [self.observance]
109 else:
110 observances = self.observance
111 for observance in observances:
112 if isinstance(observance, BaseOffset):
113 offset = observance
114
115 def f(d):
116 return d + offset # noqa: B023
117
118 observance = f # noqa: PLW2901
119 dates = dates.map(observance)
120 return dates
121
122 def _apply_rule(self, dates, apply_offset=True, apply_observance=True):
123 if apply_offset:
124 dates = self._apply_offset(dates)
125 if apply_observance:
126 dates = self._apply_observance(dates)
127 return dates
128
129
130 def combine(pre_holidays):
131 combined = Series(index=DatetimeIndex([]), dtype=object)
132 for holidays in pre_holidays:
133 combined = combined.combine_first(holidays)
134 return combined
135
136
137 class AbstractHolidayCalendar(PandasAbstractHolidayCalendar):
138 """
139 This extension allows to have overlaps between calculated holidays while
140 the original AbstractHolidayCalendar does not.
141 """
142
143 def holidays(self, start=None, end=None, return_name=False):
144 """
145 Returns a curve with holidays between start_date and end_date
146 Parameters
147 ----------
148 start : starting date, datetime-like, optional
149 end : ending date, datetime-like, optional
150 return_name : bool, optional
151 If True, return a series that has dates and holiday names.
152 False will only return a DatetimeIndex of dates.
153 Returns
154 -------
155 DatetimeIndex of holidays
156 """
157 if self.rules is None:
158 raise Exception(
159 f"Holiday Calendar {self.name} does not have any rules specified"
160 )
161
162 if start is None:
163 start = AbstractHolidayCalendar.start_date
164
165 if end is None:
166 end = AbstractHolidayCalendar.end_date
167
168 start = Timestamp(start)
169 end = Timestamp(end)
170
171 # If we don't have a cache or the dates are outside the prior cache, we
172 # get them again
173 if self._cache is None or start < self._cache[0] or end > self._cache[1]:
174 pre_holidays = [
175 rule.dates(start, end, return_name=True) for rule in self.rules
176 ]
177 if pre_holidays:
178 # This line's behavior is changed to use custom combine()
179 # function instead of the original concat() function
180 holidays = combine(pre_holidays)
181 else:
182 holidays = Series(index=DatetimeIndex([]), dtype=object)
183
184 self._cache = (start, end, holidays.sort_index())
185
186 holidays = self._cache[2]
187 holidays = holidays[start:end]
188
189 if return_name:
190 return holidays
191 return holidays.index