| 1 |
# https://github.com/pandas-dev/pandas/blob/master/pandas/tseries/offsets.py |
| 2 |
# https://github.com/pandas-dev/pandas/blob/master/pandas/_libs/tslibs/offsets.pyx |
| 3 |
|
| 4 |
import contextlib |
| 5 |
from datetime import date, datetime, timedelta |
| 6 |
|
| 7 |
import numpy as np |
| 8 |
import pandas as pd |
| 9 |
import toolz |
| 10 |
from dateutil.easter import EASTER_ORTHODOX, easter |
| 11 |
from pandas._libs.tslibs.conversion import localize_pydatetime |
| 12 |
from pandas._libs.tslibs.offsets import apply_wraps |
| 13 |
from pandas.tseries.offsets import BaseOffset, CustomBusinessDay |
| 14 |
|
| 15 |
|
| 16 |
class CompositeCustomBusinessDay(CustomBusinessDay): |
| 17 |
_prefix = "C" |
| 18 |
_attributes = ( |
| 19 |
"n", |
| 20 |
"normalize", |
| 21 |
"weekmask", |
| 22 |
"holidays", |
| 23 |
"calendar", |
| 24 |
"offset", |
| 25 |
"business_days", |
| 26 |
) |
| 27 |
|
| 28 |
def __init__( |
| 29 |
self, |
| 30 |
n=1, |
| 31 |
normalize=False, |
| 32 |
weekmask="Mon Tue Wed Thu Fri", |
| 33 |
holidays=None, |
| 34 |
calendar=None, |
| 35 |
offset=timedelta(0), |
| 36 |
business_days=None, |
| 37 |
): |
| 38 |
CustomBusinessDay.__init__( |
| 39 |
self, n, normalize, weekmask, holidays, calendar, offset |
| 40 |
) |
| 41 |
self.business_days = business_days |
| 42 |
|
| 43 |
def __setstate__(self, state): |
| 44 |
self.business_days = state.pop("business_days") |
| 45 |
CustomBusinessDay.__setstate__(self, state) |
| 46 |
|
| 47 |
@property |
| 48 |
def business_days(self): |
| 49 |
""" |
| 50 |
Returns list of tuples of (start_date, end_date, custom_business_day) |
| 51 |
which overrides default behavior for the given interval, which starts |
| 52 |
from start_date to end_date, inclusive in both sides. |
| 53 |
""" |
| 54 |
return tuple(self._business_days) |
| 55 |
|
| 56 |
@business_days.setter |
| 57 |
def business_days(self, business_days): |
| 58 |
self._business_days = [] |
| 59 |
self._business_days_index = pd.IntervalIndex([], closed="both") |
| 60 |
self._business_days_all_index = pd.IntervalIndex([], closed="both") |
| 61 |
if business_days is not None: |
| 62 |
self._business_days = business_days |
| 63 |
business_days_intervals = [] |
| 64 |
for start_date, end_date, _ in self._business_days: |
| 65 |
if start_date is None: |
| 66 |
start_date = pd.Timestamp.min # noqa: PLW2901 |
| 67 |
else: |
| 68 |
start_date = pd.Timestamp(start_date) # noqa: PLW2901 |
| 69 |
if end_date is None: |
| 70 |
end_date = pd.Timestamp.max # noqa: PLW2901 |
| 71 |
else: |
| 72 |
end_date = pd.Timestamp(end_date) # noqa: PLW2901 |
| 73 |
interval = pd.Interval(start_date, end_date, closed="both") |
| 74 |
business_days_intervals.append(interval) |
| 75 |
self._business_days_index = pd.IntervalIndex( |
| 76 |
business_days_intervals, closed="both" |
| 77 |
) |
| 78 |
business_days_all_intervals = [] |
| 79 |
right = self._business_days_index[0] |
| 80 |
if pd.Timestamp.min < right.left: |
| 81 |
interval = pd.Interval( |
| 82 |
pd.Timestamp.min, right.left - pd.Timedelta(1, unit="D") |
| 83 |
) |
| 84 |
business_days_all_intervals.append(interval) |
| 85 |
business_days_all_intervals.append(right) |
| 86 |
for left, right in toolz.sliding_window( |
| 87 |
2, toolz.concatv(self._business_days_index) |
| 88 |
): |
| 89 |
if pd.Timestamp( |
| 90 |
(right.left - left.right).days, unit="D" |
| 91 |
) > pd.Timestamp(1, unit="D"): |
| 92 |
interval = pd.Interval( |
| 93 |
left.right + pd.Timedelta(1, unit="D"), |
| 94 |
right.left - pd.Timedelta(1, unit="D"), |
| 95 |
) |
| 96 |
business_days_all_intervals.append(interval) |
| 97 |
business_days_all_intervals.append(right) |
| 98 |
left = self._business_days_index[-1] |
| 99 |
if left.right < pd.Timestamp.max: |
| 100 |
interval = pd.Interval( |
| 101 |
left.right + pd.Timedelta(1, unit="D"), pd.Timestamp.max |
| 102 |
) |
| 103 |
business_days_all_intervals.append(interval) |
| 104 |
self._business_days_all_index = pd.IntervalIndex( |
| 105 |
business_days_all_intervals, closed="both" |
| 106 |
) |
| 107 |
|
| 108 |
def _as_custom_business_day(self): |
| 109 |
return CustomBusinessDay( |
| 110 |
self.n, |
| 111 |
self.normalize, |
| 112 |
self.weekmask, |
| 113 |
self.holidays, |
| 114 |
self.calendar, |
| 115 |
self.offset, |
| 116 |
) |
| 117 |
|
| 118 |
def _custom_business_day_for( |
| 119 |
self, other, n=None, is_edge=False, with_interval=False |
| 120 |
): |
| 121 |
loc = self._business_days_all_index.get_loc(other) |
| 122 |
if is_edge and n is not None: |
| 123 |
loc += np.sign(n) |
| 124 |
interval = self._business_days_all_index[loc] |
| 125 |
try: |
| 126 |
loc = self._business_days_index.get_loc(interval.left) |
| 127 |
except KeyError: |
| 128 |
bday = self._as_custom_business_day() |
| 129 |
else: |
| 130 |
bday = self._business_days[loc][-1] |
| 131 |
if n is not None: |
| 132 |
bday = bday.base * n |
| 133 |
if with_interval: |
| 134 |
return bday, interval |
| 135 |
return bday |
| 136 |
|
| 137 |
def _moved(self, from_date, to_date, bday): |
| 138 |
return np.busday_count( |
| 139 |
np.datetime64(from_date.date()), |
| 140 |
np.datetime64(to_date.date()), |
| 141 |
busdaycal=bday.calendar, |
| 142 |
) |
| 143 |
|
| 144 |
@apply_wraps |
| 145 |
def _apply(self, other): |
| 146 |
if isinstance(other, datetime): |
| 147 |
moved = 0 |
| 148 |
remaining = self.n - moved |
| 149 |
bday, interval = self._custom_business_day_for( |
| 150 |
other, remaining, with_interval=True |
| 151 |
) |
| 152 |
result = bday + other |
| 153 |
while not interval.left <= result <= interval.right: |
| 154 |
previous_other = other |
| 155 |
if result < interval.left: |
| 156 |
other = interval.left |
| 157 |
elif result > interval.right: |
| 158 |
other = interval.right |
| 159 |
else: |
| 160 |
raise RuntimeError("Should not reach here") |
| 161 |
moved += self._moved(previous_other, other, bday) |
| 162 |
remaining = self.n - moved |
| 163 |
if remaining == 0: |
| 164 |
break |
| 165 |
bday, interval = self._custom_business_day_for( |
| 166 |
other, remaining, is_edge=True, with_interval=True |
| 167 |
) |
| 168 |
result = bday._apply(other) # noqa: SLF001 |
| 169 |
return result |
| 170 |
return super().apply(other) |
| 171 |
|
| 172 |
# backwards compat |
| 173 |
apply = _apply |
| 174 |
|
| 175 |
def is_on_offset(self, dt): |
| 176 |
if self.normalize and not _is_normalized(dt): |
| 177 |
return False |
| 178 |
day64 = _to_dt64D(dt) |
| 179 |
bday = self._custom_business_day_for(day64) |
| 180 |
return np.is_busday(day64, busdaycal=bday.calendar) |
| 181 |
|
| 182 |
|
| 183 |
def _is_normalized(dt): |
| 184 |
if dt.hour != 0 or dt.minute != 0 or dt.second != 0 or dt.microsecond != 0: |
| 185 |
# Regardless of whether dt is datetime vs Timestamp |
| 186 |
return False |
| 187 |
if isinstance(dt, pd.Timestamp): |
| 188 |
return dt.nanosecond == 0 |
| 189 |
return True |
| 190 |
|
| 191 |
|
| 192 |
def _to_dt64D(dt): # noqa: N802 |
| 193 |
# Currently |
| 194 |
# > np.datetime64(dt.datetime(2013,5,1),dtype='datetime64[D]') |
| 195 |
# numpy.datetime64('2013-05-01T02:00:00.000000+0200') |
| 196 |
# Thus astype is needed to cast datetime to datetime64[D] |
| 197 |
if getattr(dt, "tzinfo", None) is not None: |
| 198 |
# Get the nanosecond timestamp, |
| 199 |
# equiv `Timestamp(dt).value` or `dt.timestamp() * 10**9` |
| 200 |
dt = pd.Timestamp(dt).value |
| 201 |
dt = np.int64(dt).astype("datetime64[ns]") |
| 202 |
else: |
| 203 |
dt = np.datetime64(dt) |
| 204 |
if dt.dtype.name != "datetime64[D]": |
| 205 |
dt = dt.astype("datetime64[D]") |
| 206 |
return dt |
| 207 |
|
| 208 |
|
| 209 |
def _get_calendar(weekmask, holidays, calendar): |
| 210 |
""" |
| 211 |
Generate busdaycalendar |
| 212 |
""" |
| 213 |
if isinstance(calendar, np.busdaycalendar): |
| 214 |
if not holidays: |
| 215 |
holidays = tuple(calendar.holidays) |
| 216 |
elif not isinstance(holidays, tuple): |
| 217 |
holidays = tuple(holidays) |
| 218 |
else: |
| 219 |
# Trust that calendar.holidays and holidays are |
| 220 |
# consistent |
| 221 |
pass |
| 222 |
# Update weekmask if applicable (added) |
| 223 |
calendar = np.busdaycalendar(weekmask, holidays) |
| 224 |
return calendar, holidays |
| 225 |
|
| 226 |
if holidays is None: |
| 227 |
holidays = [] |
| 228 |
# Handle non list holidays also (added) |
| 229 |
if isinstance(holidays, pd.DatetimeIndex): |
| 230 |
holidays = holidays.tolist() |
| 231 |
with contextlib.suppress(AttributeError): |
| 232 |
holidays = holidays + calendar.holidays().tolist() |
| 233 |
holidays = [_to_dt64D(dt) for dt in holidays] |
| 234 |
holidays = tuple(sorted(holidays)) |
| 235 |
|
| 236 |
kwargs = {"weekmask": weekmask} |
| 237 |
if holidays: |
| 238 |
kwargs["holidays"] = holidays |
| 239 |
|
| 240 |
busdaycalendar = np.busdaycalendar(**kwargs) |
| 241 |
return busdaycalendar, holidays |
| 242 |
|
| 243 |
|
| 244 |
class MultipleWeekmaskCustomBusinessDay(CompositeCustomBusinessDay): |
| 245 |
_prefix = "C" |
| 246 |
_attributes = ( |
| 247 |
"n", |
| 248 |
"normalize", |
| 249 |
"weekmask", |
| 250 |
"holidays", |
| 251 |
"calendar", |
| 252 |
"offset", |
| 253 |
"business_days", |
| 254 |
"weekmasks", |
| 255 |
) |
| 256 |
|
| 257 |
def __init__( |
| 258 |
self, |
| 259 |
n=1, |
| 260 |
normalize=False, |
| 261 |
weekmask="Mon Tue Wed Thu Fri", |
| 262 |
holidays=None, |
| 263 |
calendar=None, |
| 264 |
offset=timedelta(0), |
| 265 |
business_days=None, |
| 266 |
weekmasks=None, |
| 267 |
): |
| 268 |
self._weekmasks = weekmasks |
| 269 |
if business_days is None and weekmasks is not None: |
| 270 |
calendars = [ |
| 271 |
_get_calendar(weekmask=weekmask, holidays=holidays, calendar=calendar) |
| 272 |
for _start_date, _end_date, weekmask in weekmasks |
| 273 |
] |
| 274 |
business_days = [ |
| 275 |
( |
| 276 |
start_date, |
| 277 |
end_date, |
| 278 |
CustomBusinessDay( |
| 279 |
n, normalize, weekmask, holidays, calendar, offset |
| 280 |
), |
| 281 |
) |
| 282 |
for (start_date, end_date, weekmask), (calendar, holidays) in zip( |
| 283 |
weekmasks, calendars, strict=False |
| 284 |
) |
| 285 |
] |
| 286 |
CompositeCustomBusinessDay.__init__( |
| 287 |
self, n, normalize, weekmask, holidays, calendar, offset, business_days |
| 288 |
) |
| 289 |
|
| 290 |
def __setstate__(self, state): |
| 291 |
self.weekmasks = state.pop("weekmasks") |
| 292 |
CompositeCustomBusinessDay.__setstate__(self, state) |
| 293 |
|
| 294 |
@property |
| 295 |
def weekmasks(self): |
| 296 |
return tuple(self._weekmasks) |
| 297 |
|
| 298 |
@weekmasks.setter |
| 299 |
def weekmasks(self, weekmasks): |
| 300 |
self._weekmasks = weekmasks |
| 301 |
|
| 302 |
|
| 303 |
class SingleConstructorOffset(BaseOffset): |
| 304 |
def __reduce__(self): ... |
| 305 |
|
| 306 |
|
| 307 |
class OrthodoxEaster(SingleConstructorOffset): |
| 308 |
""" |
| 309 |
DateOffset for the Orthodox Easter holiday. |
| 310 |
""" |
| 311 |
|
| 312 |
def __setstate__(self, state): |
| 313 |
self.n = state.pop("n") |
| 314 |
self.normalize = state.pop("normalize") |
| 315 |
|
| 316 |
@apply_wraps |
| 317 |
def _apply(self, other: datetime) -> datetime: |
| 318 |
current_easter = easter(other.year, method=EASTER_ORTHODOX) |
| 319 |
current_easter = datetime( |
| 320 |
current_easter.year, current_easter.month, current_easter.day |
| 321 |
) |
| 322 |
current_easter = localize_pydatetime(current_easter, other.tzinfo) |
| 323 |
|
| 324 |
n = self.n |
| 325 |
if n >= 0 and other < current_easter: |
| 326 |
n -= 1 |
| 327 |
elif n < 0 and other > current_easter: |
| 328 |
n += 1 |
| 329 |
|
| 330 |
new = easter(other.year + n, method=EASTER_ORTHODOX) |
| 331 |
return datetime( |
| 332 |
new.year, |
| 333 |
new.month, |
| 334 |
new.day, |
| 335 |
other.hour, |
| 336 |
other.minute, |
| 337 |
other.second, |
| 338 |
other.microsecond, |
| 339 |
) |
| 340 |
|
| 341 |
def is_on_offset(self, dt: datetime) -> bool: |
| 342 |
if self.normalize and not _is_normalized(dt): |
| 343 |
return False |
| 344 |
|
| 345 |
return date(dt.year, dt.month, dt.day) == easter( |
| 346 |
dt.year, method=EASTER_ORTHODOX |
| 347 |
) |