Skip to content

Commit

Permalink
Revise for pandas 2.0
Browse files Browse the repository at this point in the history
Changes to accommodate changes in pandas 2.0. Mainly
responding to pandas default tz changing from `pytz.UTC` to
`datetime.timezone.utc`. These revisions retain all timezones
as pytz in `exchange_calendars`.

Also:
* makes changes in light of new pandas Warnings.
* resolves #294 which moved from `FutureWarning` to Error
when `CustomBusinessDay.apply` was deprecated in pandas 2.0.
  • Loading branch information
maread99 committed Apr 9, 2023
1 parent a9d8c52 commit 5a611c9
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 11 deletions.
6 changes: 3 additions & 3 deletions exchange_calendars/calendar_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ def trading_index(self) -> pd.DatetimeIndex:
index = self._trading_index()
if self.has_break:
index.sort()
index = pd.DatetimeIndex(index, tz="UTC")
index = pd.DatetimeIndex(index, tz=pytz.UTC)
return self.curtail_for_times(index)

@contextlib.contextmanager
Expand Down Expand Up @@ -718,7 +718,7 @@ def trading_index_intervals(self) -> pd.IntervalIndex:
else:
raise errors.IntervalsOverlapError()

left = pd.DatetimeIndex(left, tz="UTC")
right = pd.DatetimeIndex(right, tz="UTC")
left = pd.DatetimeIndex(left, tz=pytz.UTC)
right = pd.DatetimeIndex(right, tz=pytz.UTC)
index = pd.IntervalIndex.from_arrays(left, right, self.closed)
return self.curtail_for_times(index)
2 changes: 1 addition & 1 deletion exchange_calendars/pandas_extensions/offsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def _apply(self, other):
bday, interval = self._custom_business_day_for(
other, remaining, with_interval=True
)
result = bday.apply(other)
result = bday + other
while not interval.left <= result <= interval.right:
previous_other = other
if result < interval.left:
Expand Down
2 changes: 1 addition & 1 deletion exchange_calendars/utils/pandas_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def longest_run(ser: pd.Series) -> pd.Index:
... | ((ser >= 55) & (ser < 61))
... )
>>> longest_run(bv)
Int64Index([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40], dtype='int64')
Index([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40], dtype='int32')
>>> pd.testing.assert_index_equal(longest_run(bv), ser.index[30:41])
"""
# group Trues by only adding to sum when value False.
Expand Down
2 changes: 1 addition & 1 deletion tests/test_calendar_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,7 @@ def bounds(start: pd.Series, end: pd.Series, force: bool, align: pd.Timedelta):

if curtail and not (force_close and force_break_close):
indices = lower_bounds.argsort()
lower_bounds.sort_values(inplace=True)
lower_bounds = lower_bounds.sort_values()
upper_bounds = upper_bounds[indices]
curtail_mask = upper_bounds > lower_bounds.shift(-1)
if curtail_mask.any():
Expand Down
16 changes: 11 additions & 5 deletions tests/test_exchange_calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# limitations under the License.
from __future__ import annotations

import datetime
import functools
import itertools
import pathlib
Expand Down Expand Up @@ -181,7 +182,6 @@ def get_csv(name: str) -> pd.DataFrame:
path,
index_col=0,
parse_dates=[0, 1, 2, 3, 4],
infer_datetime_format=True,
)
# Necessary for csv saved prior to v4.0
if df.index.tz is not None:
Expand All @@ -190,6 +190,8 @@ def get_csv(name: str) -> pd.DataFrame:
for col in df:
if df[col].dt.tz is None:
df[col] = df[col].dt.tz_localize(UTC)
elif df[col].dt.tz is datetime.timezone.utc:
df[col] = df[col].dt.tz_convert(UTC)
return df


Expand Down Expand Up @@ -2146,7 +2148,7 @@ def late_opens(
date_to = pd.Timestamp.max
dtis: list[pd.DatetimeIndex] = []
# For each period over which a distinct open time prevails...
for date_from, time_ in s.iteritems():
for date_from, time_ in s.items():
opens = ans.opens[date_from:date_to]
sessions = opens.index
td = pd.Timedelta(hours=time_.hour, minutes=time_.minute)
Expand Down Expand Up @@ -2186,7 +2188,7 @@ def early_closes(

date_to = pd.Timestamp.max
dtis: list[pd.DatetimeIndex] = []
for date_from, time_ in s.iteritems():
for date_from, time_ in s.items():
closes = ans.closes[date_from:date_to] # index to tz-naive
sessions = closes.index
td = pd.Timedelta(hours=time_.hour, minutes=time_.minute)
Expand Down Expand Up @@ -3837,14 +3839,18 @@ def unite(dtis: list[pd.DatetimeIndex]) -> pd.DatetimeIndex:
else:
ends = ans.closes
# index for a 'left' calendar, add end so evaluated as if 'both'
index = index.append(pd.DatetimeIndex([ends[session]]))
index = index.append(
pd.DatetimeIndex([ends[session]], tz=pytz.UTC)
)

index = index[::mins] # only want every period
if not index[-1] == ends[session]:
# if period doesn't coincide with end, add right side of
# last interval which lies beyond end.
last_indice = index[-1] + period
index = index.append(pd.DatetimeIndex([last_indice]))
index = index.append(
pd.DatetimeIndex([last_indice], tz=pytz.UTC)
)
dtis.append(index)

both_index = unite(dtis)
Expand Down

0 comments on commit 5a611c9

Please sign in to comment.