| 1 |
import datetime |
| 2 |
from zoneinfo import ZoneInfo |
| 3 |
|
| 4 |
import numpy as np |
| 5 |
import pandas as pd |
| 6 |
|
| 7 |
from exchange_calendars.calendar_helpers import UTC |
| 8 |
|
| 9 |
|
| 10 |
def days_at_time( |
| 11 |
dates: pd.DatetimeIndex, |
| 12 |
time: datetime.time | None, |
| 13 |
tz: ZoneInfo, |
| 14 |
day_offset: int, |
| 15 |
) -> pd.DatetimeIndex: |
| 16 |
"""Return UTC DatetimeIndex of given dates at a given time. |
| 17 |
|
| 18 |
Parameters |
| 19 |
---------- |
| 20 |
dates |
| 21 |
Dates or date (timezone naive with no time component). |
| 22 |
|
| 23 |
time |
| 24 |
The time to apply as an offset to each day in `dates`. |
| 25 |
|
| 26 |
tz |
| 27 |
The timezone in which to interpret `time`. |
| 28 |
|
| 29 |
day_offset |
| 30 |
Number of days by which to offset each date in `dates`. |
| 31 |
|
| 32 |
Returns |
| 33 |
------- |
| 34 |
pd.DatetimeIndex |
| 35 |
DatetimeIndex comprising Timestamp evaluted from `dates` and `time` |
| 36 |
with `dates` offset by `day_offset` and `time` interpreted as having |
| 37 |
timezone `tz`. DatetimeIndex has UTC timezone. |
| 38 |
|
| 39 |
Examples |
| 40 |
-------- |
| 41 |
In the example below, the times switch from 13:45 to 12:45 UTC because |
| 42 |
March 13th is the daylight savings transition for America/New_York. All |
| 43 |
the times are still 8:45 when interpreted in America/New_York. |
| 44 |
|
| 45 |
>>> import pandas as pd; import datetime; import pprint |
| 46 |
>>> dts = pd.date_range('2016-03-12', '2016-03-14') |
| 47 |
>>> dts_845 = days_at_time(dts, datetime.time(8, 45), 'America/New_York', 0) |
| 48 |
>>> pprint.pprint([str(dt) for dt in dts_845]) |
| 49 |
['2016-03-12 13:45:00+00:00', |
| 50 |
'2016-03-13 12:45:00+00:00', |
| 51 |
'2016-03-14 12:45:00+00:00'] |
| 52 |
""" |
| 53 |
if time is None: |
| 54 |
return pd.DatetimeIndex([None for _ in dates]).tz_localize(UTC) |
| 55 |
|
| 56 |
if len(dates) == 0: |
| 57 |
return dates.tz_localize(UTC) |
| 58 |
|
| 59 |
# Offset days without tz to avoid timezone issues. |
| 60 |
delta = pd.Timedelta( |
| 61 |
days=day_offset, |
| 62 |
hours=time.hour, |
| 63 |
minutes=time.minute, |
| 64 |
seconds=time.second, |
| 65 |
) |
| 66 |
return (dates + delta).tz_localize(tz).tz_convert(UTC) |
| 67 |
|
| 68 |
|
| 69 |
def vectorized_sunday_to_monday(dtix): |
| 70 |
"""A vectorized implementation of |
| 71 |
:func:`pandas.tseries.holiday.sunday_to_monday`. |
| 72 |
|
| 73 |
Parameters |
| 74 |
---------- |
| 75 |
dtix : pd.DatetimeIndex |
| 76 |
The index to shift sundays to mondays. |
| 77 |
|
| 78 |
Returns |
| 79 |
------- |
| 80 |
sundays_as_mondays : pd.DatetimeIndex |
| 81 |
``dtix`` with all sundays moved to the next monday. |
| 82 |
""" |
| 83 |
values = dtix.values.copy() |
| 84 |
values[dtix.weekday == 6] += np.timedelta64(1, "D") |
| 85 |
return pd.DatetimeIndex(values) |
| 86 |
|
| 87 |
|
| 88 |
def longest_run(ser: pd.Series) -> pd.Index: |
| 89 |
"""Get the longest run of consecutive True values in a Series. |
| 90 |
|
| 91 |
Function can be used to find the longest run of values that meet a |
| 92 |
condition. |
| 93 |
|
| 94 |
Parameters |
| 95 |
---------- |
| 96 |
ser |
| 97 |
pd.Series of bool dtype. |
| 98 |
Index should reflect values against which a condition was |
| 99 |
assessed. |
| 100 |
Values should reflect whether corresponding index value |
| 101 |
met the condition. |
| 102 |
|
| 103 |
Return |
| 104 |
------ |
| 105 |
pd.Index |
| 106 |
Slice of `ser` index that corresponds with the longest run of |
| 107 |
consecutive True values. |
| 108 |
|
| 109 |
Examples |
| 110 |
-------- |
| 111 |
>>> arr = np.arange(0, 88) |
| 112 |
>>> ser = pd.Series(arr, index=arr) |
| 113 |
>>> bv = ( |
| 114 |
... ((ser >= 10) & (ser < 16)) |
| 115 |
... | ((ser >= 30) & (ser <= 40)) |
| 116 |
... | ((ser >= 55) & (ser < 61)) |
| 117 |
... ) |
| 118 |
>>> longest_run(bv) |
| 119 |
Index([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40], dtype='int64') |
| 120 |
>>> pd.testing.assert_index_equal(longest_run(bv), ser.index[30:41]) |
| 121 |
""" |
| 122 |
# group Trues by only adding to sum when value False. |
| 123 |
trues_grouped = (~ser).cumsum()[ser] # and only take True Values |
| 124 |
group_sizes = trues_grouped.value_counts() # count each run |
| 125 |
max_run_size = group_sizes.max() |
| 126 |
max_run_group_id = group_sizes[group_sizes == max_run_size].index[0] |
| 127 |
return trues_grouped[trues_grouped == max_run_group_id].index |
| 128 |
|
| 129 |
|
| 130 |
def indexes_union(indexes: list[pd.Index]) -> pd.Index: |
| 131 |
"""Return union of multiple pd.Index objects. |
| 132 |
|
| 133 |
Parameters |
| 134 |
---------- |
| 135 |
indexes |
| 136 |
Index objects to be joined. All indexes must be of same dtype. |
| 137 |
|
| 138 |
Examples |
| 139 |
-------- |
| 140 |
>>> index1 = pd.date_range('2021-05-01 12:20', periods=2, freq='1h') |
| 141 |
>>> index2 = pd.date_range('2021-05-02 17:10', periods=2, freq='22min') |
| 142 |
>>> index3 = pd.date_range('2021-05-03', periods=2, freq='1D') |
| 143 |
>>> indexes_union([index1, index2, index3]) |
| 144 |
DatetimeIndex(['2021-05-01 12:20:00', '2021-05-01 13:20:00', |
| 145 |
'2021-05-02 17:10:00', '2021-05-02 17:32:00', |
| 146 |
'2021-05-03 00:00:00', '2021-05-04 00:00:00'], |
| 147 |
dtype='datetime64[us]', freq=None) |
| 148 |
""" |
| 149 |
index = indexes[0] |
| 150 |
for indx in indexes[1:]: |
| 151 |
index = index.union(indx) |
| 152 |
return index |