Debian Codegraph @

exchange_calendars/exchange_calendar.py

raw symbols SCIP
1 # Copyright 2018 Quantopian, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 from __future__ import annotations
15
16 from abc import ABC, abstractmethod
17 from calendar import day_name
18 import collections
19 import functools
20 import operator
21 from typing import TYPE_CHECKING, Literal, Any
22 import warnings
23
24 import numpy as np
25 import pandas as pd
26 import toolz
27 from pandas.tseries.holiday import AbstractHolidayCalendar
28 from pandas.tseries.offsets import CustomBusinessDay
29
30 from exchange_calendars import errors
31 from .calendar_helpers import (
32 UTC,
33 NANOSECONDS_PER_MINUTE,
34 NP_NAT,
35 Date,
36 Minute,
37 Session,
38 TradingMinute,
39 _TradingIndex,
40 compute_minutes,
41 next_divider_idx,
42 one_minute_earlier,
43 one_minute_later,
44 parse_date,
45 parse_session,
46 parse_timestamp,
47 parse_trading_minute,
48 previous_divider_idx,
49 )
50 from .utils.pandas_utils import days_at_time
51
52 if TYPE_CHECKING:
53 from zoneinfo import ZoneInfo
54 import datetime
55 from collections.abc import Sequence, Callable
56 from pandas._libs.tslibs.nattype import NaTType
57
58
59 GLOBAL_DEFAULT_START = pd.Timestamp.now().floor("D") - pd.DateOffset(years=20)
60 # Give an aggressive buffer for logic that needs to use the next trading
61 # day or minute.
62 GLOBAL_DEFAULT_END = pd.Timestamp.now().floor("D") + pd.DateOffset(years=1)
63
64 ONE_MINUTE = pd.Timedelta(1, "min")
65 ONE_HOUR = pd.Timedelta("1h")
66 NANOS_IN_MINUTE = 60000000000
67 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = range(7)
68 WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY)
69 WEEKENDS = (SATURDAY, SUNDAY)
70
71
72 def selection(
73 arr: pd.DatetimeIndex, start: pd.Timestamp, end: pd.Timestamp
74 ) -> pd.DatetimeIndex:
75 predicates = []
76 if start is not None:
77 predicates.append(start <= arr)
78 if end is not None:
79 predicates.append(arr < end)
80
81 if not predicates:
82 return arr
83
84 return arr[np.all(predicates, axis=0)]
85
86
87 def _group_times(
88 sessions: pd.DatetimeIndex,
89 times: None | Sequence[tuple[pd.Timestamp | None, datetime.time]],
90 tz: ZoneInfo,
91 offset: int = 0,
92 ) -> pd.DatetimeIndex | None:
93 """Evaluate standard times for a specific session bound.
94
95 For example, if `times` passed as standard times for session opens then
96 will return a DatetimeIndex describing standard open times for each
97 session.
98 """
99 if times is None:
100 return None
101 elements = [
102 days_at_time(selection(sessions, start, end), time, tz, offset)
103 for (start, time), (end, _) in toolz.sliding_window(
104 2, toolz.concatv(times, [(None, None)])
105 )
106 ]
107 return elements[0].append(elements[1:])
108
109
110 class deprecate: # noqa: N801
111 """Decorator for deprecated ExchangeCalendar methods."""
112
113 def __init__(
114 self,
115 deprecated_release: str = "4.0",
116 message: str | None = None,
117 ):
118 self.deprecated_release = "release " + deprecated_release
119 self.message = message
120
121 def __call__(self, f: Callable) -> Callable:
122 @functools.wraps(f)
123 def wrapped_f(*args, **kwargs):
124 warnings.warn(self._message(f), FutureWarning) # noqa: B028
125 return f(*args, **kwargs)
126
127 return wrapped_f
128
129 def _message(self, f: Callable) -> str:
130 msg = (
131 f"`{f.__name__}` was deprecated in {self.deprecated_release}"
132 f" and will be removed in a future release."
133 )
134 if self.message is not None:
135 msg += " " + self.message
136 return msg
137
138
139 class HolidayCalendar(AbstractHolidayCalendar):
140 def __init__(self, rules):
141 super().__init__(rules=rules)
142
143
144 class ExchangeCalendar(ABC):
145 """Representation of timing information of a single market exchange.
146
147 The timing information comprises sessions, open/close times and, for
148 exchanges that observe an intraday break, break_start/break_end times.
149
150 For exchanges that do not observe an intraday break a session
151 represents a contiguous set of minutes. Where an exchange observes
152 an intraday break a session represents two contiguous sets of minutes
153 separated by the intraday break.
154
155 Each session is labeled as the date that the session represents.
156
157 For each session, we store the open and close time together with, for
158 those exchanges with breaks, the break start and break end. All times
159 are defined as UTC.
160
161 Note that a session may start on the day prior to the session label or
162 end on the day following the session label. Such behaviour is common
163 for calendars that represent futures exchanges.
164
165 Parameters
166 ----------
167 start : default: later of 20 years ago or first supported start date.
168 First calendar session will be `start`, if `start` is a session, or
169 first session after `start`. Cannot be earlier than any date
170 returned by class method `bound_min`.
171
172 end : default: earliest of 1 year from 'today' or last supported end
173 date. Last calendar session will be `end`, if `end` is a session,
174 or last session before `end`. Cannot be later than any date
175 returned by class method `bound_max`.
176
177 side : default: "left"
178 Define which of session open/close and break start/end should
179 be treated as a trading minute:
180 "left" - treat session open and break_start as trading minutes,
181 do not treat session close or break_end as trading minutes.
182 "right" - treat session close and break_end as trading minutes,
183 do not treat session open or break_start as tradng minutes.
184 "both" - treat all of session open, session close, break_start
185 and break_end as trading minutes.
186 "neither" - treat none of session open, session close,
187 break_start or break_end as trading minutes.
188
189 Raises
190 ------
191 ValueError
192 If `start` is earlier than the earliest supported start date.
193 If `end` is later than the latest supported end date.
194 If `start` parses to a later date than `end`.
195
196 Notes
197 -----
198 Exchange calendars were originally defined for the Zipline package from
199 Quantopian under the package 'trading_calendars'. Since 2021 they have
200 been maintained under the 'exchange_calendars' package (a fork of
201 'trading_calendars') by an active community of contributing users.
202
203 Some calendars have defined start and end bounds within which
204 contributors have endeavoured to ensure the calendar's accuracy and
205 outside of which the calendar would not be accurate. These bounds
206 are enforced such that passing `start` or `end` as dates that are
207 out-of-bounds will raise a ValueError. The bounds of each calendar are
208 exposed via the `bound_min` and `bound_max` class methods.
209
210 Many calendars do not have bounds defined (in these cases `bound_min`
211 and/or `bound_max` return None). These calendars can be created through
212 any date range although it should be noted that the earlier the start
213 date, the greater the potential for inaccuracies.
214
215 In all cases, no guarantees are offered as to the accuracy of any
216 calendar.
217
218
219 -- Internal method parameters --
220
221 _parse: bool
222 Determines if a `minute` or `session` parameter should be
223 parsed (default True). Passed as False:
224 - internally to prevent double parsing.
225 - by tests for efficiency.
226 """
227
228 _LEFT_SIDES = ["left", "both"]
229 _RIGHT_SIDES = ["right", "both"]
230
231 @classmethod
232 def bound_min(cls) -> pd.Timestamp | None:
233 """Earliest date from which calendar can be constructed.
234
235 Returns
236 -------
237 pd.Timestamp or None
238 Earliest date from which calendar can be constructed. Must be
239 timezone naive. None if no limit.
240
241 Notes
242 -----
243 To impose a constraint on the earliest date from which a calendar
244 can be constructed subclass should override this method and
245 optionally override `_bound_min_error_msg`.
246 """
247 return None
248
249 @classmethod
250 def bound_max(cls) -> pd.Timestamp | None:
251 """Latest date to which calendar can be constructed.
252
253 Returns
254 -------
255 pd.Timestamp or None
256 Latest date to which calendar can be constructed. Must be
257 timezone naive. None if no limit.
258
259 Notes
260 -----
261 To impose a constraint on the latest date to which a calendar can
262 be constructed subclass should override this method and optionally
263 override `_bound_max_error_msg`.
264 """
265 return None
266
267 @classmethod
268 def default_start(cls) -> pd.Timestamp:
269 """Return default calendar start date.
270
271 Calendar will start from this date if 'start' is not otherwise
272 passed to the constructor.
273 """
274 bound_min = cls.bound_min()
275 if bound_min is None:
276 return GLOBAL_DEFAULT_START
277 return max(GLOBAL_DEFAULT_START, bound_min)
278
279 @classmethod
280 def default_end(cls) -> pd.Timestamp:
281 """Return default calendar end date.
282
283 Calendar will end at this date if 'end' is not otherwise passed to
284 the constructor.
285 """
286 bound_max = cls.bound_max()
287 if bound_max is None:
288 return GLOBAL_DEFAULT_END
289 return min(GLOBAL_DEFAULT_END, bound_max)
290
291 def __init__( # noqa: PLR0915 # can lose noqa post changes when min pandas bumps to 2.0
292 self,
293 start: Date | None = None,
294 end: Date | None = None,
295 side: Literal["left", "right", "both", "neither"] = "left",
296 ):
297 if side not in self.valid_sides():
298 raise ValueError(
299 f"`side` must be in {self.valid_sides()} although received as {side}."
300 )
301 self._side = side
302
303 if start is None:
304 start = self.default_start()
305 else:
306 start = parse_date(start, "start", raise_oob=False)
307 bound_min = self.bound_min()
308 if bound_min is not None and start < bound_min:
309 raise ValueError(self._bound_min_error_msg(start))
310
311 if end is None:
312 end = self.default_end()
313 else:
314 end = parse_date(end, "end", raise_oob=False)
315 bound_max = self.bound_max()
316 if bound_max is not None and end > bound_max:
317 raise ValueError(self._bound_max_error_msg(end))
318
319 if start >= end:
320 raise ValueError(
321 "`start` must be earlier than `end` although `start` parsed as"
322 f" '{start}' and `end` as '{end}'."
323 )
324
325 _all_days = pd.date_range(start, end, freq=self.day) # session labels
326 if _all_days.empty:
327 raise errors.NoSessionsError(calendar_name=self.name, start=start, end=end)
328
329 # DatetimeIndex of standard times for each day.
330 self._opens = _group_times(
331 _all_days,
332 self.open_times,
333 self.tz,
334 self.open_offset,
335 )
336 self._break_starts = _group_times(
337 _all_days,
338 self.break_start_times,
339 self.tz,
340 )
341 self._break_ends = _group_times(
342 _all_days,
343 self.break_end_times,
344 self.tz,
345 )
346 self._closes = _group_times(
347 _all_days,
348 self.close_times,
349 self.tz,
350 self.close_offset,
351 )
352
353 # Apply any special offsets first
354 self.apply_special_offsets(_all_days, start, end)
355
356 # Series mapping sessions with non-standard opens/closes.
357 _special_opens = self._calculate_special_opens(start, end)
358 _special_closes = self._calculate_special_closes(start, end)
359
360 # Adjust for special opens and closes.
361 self._opens = _adjust_special_dates(_all_days, self._opens, _special_opens)
362 self._closes = _adjust_special_dates(_all_days, self._closes, _special_closes)
363 self._break_starts = _remove_breaks_for_special_dates(
364 _all_days, self._break_starts, _special_closes
365 )
366 self._break_ends = _remove_breaks_for_special_dates(
367 _all_days, self._break_ends, _special_closes
368 )
369
370 break_starts = (
371 self._break_starts
372 if self._break_starts is not None
373 else pd.DatetimeIndex([np.nan] * len(_all_days), tz=UTC)
374 )
375 break_ends = (
376 self._break_ends
377 if self._break_ends is not None
378 else pd.DatetimeIndex([np.nan] * len(_all_days), tz=UTC)
379 )
380
381 # NOTE can lose this if line when min supported version of pandas bumps to
382 # 2.0 (`as_unit` introduced in pandas 2.0) and just dedent the content.
383 # NB pre v3.0 pandas infers resolution here as "ns", not so in v3 which would
384 # otherwise infer as "us".
385 if pd.__version__ >= "3.0.0":
386 _all_days = _all_days.as_unit("ns")
387 self._opens = self._opens.as_unit("ns")
388 self._closes = self._closes.as_unit("ns")
389 break_starts = break_starts.as_unit("ns")
390 break_ends = break_ends.as_unit("ns")
391 self.schedule = pd.DataFrame(
392 index=_all_days,
393 data=collections.OrderedDict(
394 [
395 ("open", self._opens),
396 ("break_start", break_starts),
397 ("break_end", break_ends),
398 ("close", self._closes),
399 ]
400 ),
401 )
402
403 self.opens_nanos = self.schedule.open.values.astype(np.int64)
404 self.break_starts_nanos = self.schedule.break_start.values.astype(np.int64)
405 self.break_ends_nanos = self.schedule.break_end.values.astype(np.int64)
406 self.closes_nanos = self.schedule.close.values.astype(np.int64)
407
408 _check_breaks_match(self.break_starts_nanos, self.break_ends_nanos)
409
410 # NOTE If / when min pandas bumps to 2.0 can reduce all the following to just
411 # the content of the if clause. (`as_unit`` introduced in pandas 2.0).
412 # NB pre v3.0 pandas infers resolution here as "ns", not so in v3.
413 if pd.__version__ >= "3.0.0":
414 self._late_opens = _special_opens.index.as_unit("ns")
415 self._early_closes = _special_closes.index.as_unit("ns")
416 else:
417 self._late_opens = _special_opens.index
418 self._early_closes = _special_closes.index
419
420 # --------------- Calendar definition methods/properties --------------
421 # Methods and properties in this section should be overriden or
422 # extended by subclass if and as required.
423
424 @property
425 @abstractmethod
426 def name(self) -> str:
427 """Calendar name."""
428 raise NotImplementedError
429
430 def _bound_min_error_msg(self, start: pd.Timestamp) -> str:
431 """Return error message to handle `start` being out-of-bounds.
432
433 See Also
434 --------
435 bound_min
436 """
437 return (
438 f"The earliest date from which calendar {self.name} can be"
439 f" evaluated is {self.bound_min()}, although received `start` as"
440 f" {start}."
441 )
442
443 def _bound_max_error_msg(self, end: pd.Timestamp) -> str:
444 """Return error message to handle `end` being out-of-bounds.
445
446 See Also
447 --------
448 bound_max
449 """
450 return (
451 f"The latest date to which calendar {self.name} can be evaluated"
452 f" is {self.bound_max()}, although received `end` as {end}."
453 )
454
455 @property
456 @abstractmethod
457 def tz(self) -> ZoneInfo:
458 """Calendar timezone."""
459 raise NotImplementedError
460
461 @property
462 @abstractmethod
463 def open_times(self) -> Sequence[tuple[pd.Timestamp | None, datetime.time]]:
464 """Local open time(s).
465
466 Returns
467 -------
468 Sequence[tuple[pd.Timestamp | None, datetime.time]]:
469 Sequence of tuples representing (start_date, open_time) where:
470 start_date: date from which `open_time` applies. Must be
471 timezone-naive. None for first item.
472 open_time: exchange's local open time.
473
474 Notes
475 -----
476 Examples for concreting `open_times` on a subclass.
477
478 Example where open time is constant throughout period covered by
479 calendar:
480 open_times = ((None, datetime.time(9)),)
481
482 Example where open times have varied over period covered by
483 calendar:
484 open_times = (
485 (None, time(9, 30)),
486 (pd.Timestamp("1978-04-01"), datetime.time(10, 0)),
487 (pd.Timestamp("1986-04-01"), datetime.time(9, 40)),
488 (pd.Timestamp("1995-01-01"), datetime.time(9, 30)),
489 (pd.Timestamp("1998-12-07"), datetime.time(9, 0)),
490 )
491 """
492 raise NotImplementedError
493
494 @property
495 def break_start_times(
496 self,
497 ) -> None | Sequence[tuple[pd.Timestamp | None, datetime.time]]:
498 """Local break start time(s).
499
500 As `close_times` although times represent the close of the morning
501 subsession. None if exchange does not observe a break.
502 """
503 return None
504
505 @property
506 def break_end_times(
507 self,
508 ) -> None | Sequence[tuple[pd.Timestamp | None, datetime.time]]:
509 """Local break end time(s).
510
511 As `open_times` although times represent the open of the afternoon
512 subsession. None if exchange does not observe a break.
513 """
514 return None
515
516 @property
517 @abstractmethod
518 def close_times(self) -> Sequence[tuple[pd.Timestamp | None, datetime.time]]:
519 """Local close time(s).
520
521 Returns
522 -------
523 Sequence[tuple[pd.Timestamp | None, datetime.time]]:
524 Sequence of tuples representing (start_date, close_time) where:
525 start_date: date from which `close_time` applies. Must be
526 timezone naive. None for first item.
527 close_time: exchange's local close time.
528
529 Notes
530 -----
531 Examples for concreting `close_times` on a subclass.
532
533 Example where close time is constant throughout period covered by
534 calendar:
535 close_times = ((None, time(17, 30)),)
536
537 Example where close times have varied over period covered by
538 calendar:
539 close_times = (
540 (None, datetime.time(17, 30)),
541 (pd.Timestamp("1986-04-01"), datetime.time(17, 20)),
542 (pd.Timestamp("1995-01-01"), datetime.time(17, 0)),
543 (pd.Timestamp("2016-08-01"), datetime.time(17, 30)),
544 )
545 """
546 raise NotImplementedError
547
548 @property
549 def weekmask(self) -> str:
550 """Indicator of weekdays on which the exchange is open.
551
552 Default is '1111100' (i.e. Monday-Friday).
553
554 See Also
555 --------
556 numpy.busdaycalendar
557 """
558 return "1111100"
559
560 @property
561 def open_offset(self) -> int:
562 """Day offset of open time(s) relative to session.
563
564 Returns
565 -------
566 int
567 0 if the date components of local open times are as the
568 corresponding session labels.
569
570 -1 if the date components of local open times are the day
571 before the corresponding session labels.
572 """
573 return 0
574
575 @property
576 def close_offset(self) -> int:
577 """Day offset of close time(s) relative to session.
578
579 Returns
580 -------
581 int
582 0 if the date components of local close times are as the
583 corresponding session labels.
584
585 1 if the date components of local close times are the day
586 after the corresponding session labels.
587 """
588 return 0
589
590 @property
591 def regular_holidays(self) -> HolidayCalendar | None:
592 """Holiday calendar representing calendar's regular holidays."""
593 return None
594
595 @property
596 def adhoc_holidays(self) -> list[pd.Timestamp]:
597 """List of non-regular holidays.
598
599 Returns
600 -------
601 list[pd.Timestamp]
602 List of tz-naive timestamps representing non-regular holidays.
603 """
604 return []
605
606 @property
607 def special_opens(self) -> list[tuple[datetime.time, HolidayCalendar] | int]:
608 """Regular non-standard open times.
609
610 Example of what would be defined as a special open:
611 "EVERY YEAR on national lie-in day the exchange opens
612 at 13:00 rather than the standard 09:00".
613
614 "Every Monday the exchange opens late, at 10:30 rather than
615 the standard 09:00".
616
617 Returns
618 -------
619 list[tuple[datetime.time, HolidayCalendar | int]]:
620 list of tuples each describing a regular non-standard open:
621 [0] datetime.time: regular non-standard open time.
622
623 [1] Describes dates with regular non-standard open time
624 as [0]. As either:
625 HolidayCalendar: defines annual dates by rules.
626
627 int : integer defines a weekday with a regular
628 non-standard open (0 - Monday, ..., 6 - Sunday).
629
630 The same date may be described by more than one tuple, for
631 example, if a late open on an annual holiday coincides with
632 a weekday late open. In this case the time assigned to the
633 date will be that defined by the tuple with the lowest index
634 in the returned list.
635 """
636 return []
637
638 @property
639 def special_opens_adhoc(
640 self,
641 ) -> list[tuple[datetime.time, pd.DatetimeIndex]]:
642 """Adhoc non-standard open times.
643
644 Defines non-standard open times that cannot be otherwise codified
645 within within `special_opens`.
646
647 Example of an event to define as an adhoc special open:
648 "On 2022-02-14 due to a typhoon the exchange opened at 13:00,
649 rather than the standard 09:00".
650
651 Returns
652 -------
653 list[tuple[datetime.time, pd.DatetimeIndex]]:
654 List of tuples each describing an adhoc non-standard open time:
655 [0] datetime.time: non-standard open time.
656
657 [1] pd.DatetimeIndex: date or dates corresponding with the
658 non-standard open time. (Must be timezone-naive.)
659 """
660 return []
661
662 @property
663 def special_closes(self) -> list[tuple[datetime.time, HolidayCalendar | int]]:
664 """Regular non-standard close times.
665
666 Examples of what would be defined as a special close:
667 "On christmas eve the exchange closes at 14:00 rather than
668 the standard 17:00".
669
670 "Every Friday the exchange closes early, at 14:00 rather than
671 the standard 17:00".
672
673 Returns
674 -------
675 list[tuple[datetime.time, HolidayCalendar | int]]:
676 list of tuples each describing a regular non-standard close:
677 [0] datetime.time: regular non-standard close time.
678
679 [1] Describes dates with regular non-standard close time
680 as [0]. As either:
681 HolidayCalendar: defines annual dates by rules.
682
683 int : integer defines a weekday with a regular
684 non-standard close (0 - Monday, ..., 6 - Sunday).
685
686 The same date may be described by more than one tuple, for
687 example, if an early close on an annual holiday coincides with
688 a weekday early close. In this case the time assigned to the
689 date will be that defined by the tuple with the lowest index
690 in the returned list.
691 """
692 return []
693
694 @property
695 def special_closes_adhoc(
696 self,
697 ) -> list[tuple[datetime.time, pd.DatetimeIndex]]:
698 """Adhoc non-standard close times.
699
700 Defines non-standard close times that cannot be otherwise codified
701 within within `special_closes`.
702
703 Example of an event to define as an adhoc special close:
704 "On 2022-02-19 due to a typhoon the exchange closed at 12:00,
705 rather than the standard 16:00".
706
707 Returns
708 -------
709 list[tuple[datetime.time, pd.DatetimeIndex]]:
710 List of tuples each describing an adhoc non-standard close
711 time:
712 [0] datetime.time: non-standard close time.
713
714 [1] pd.DatetimeIndex: date or dates corresponding with the
715 non-standard close time. (Must be timezone-naive.)
716 """
717 return []
718
719 def apply_special_offsets(
720 self,
721 sessions: pd.DatetimeIndex, # noqa: ARG002
722 start: pd.Timestamp, # noqa: ARG002
723 end: pd.Timestamp, # noqa: ARG002
724 ) -> None:
725 """Hook for subclass to apply changes.
726
727 Method executed by constructor prior to overwritting special dates.
728
729 Parameters
730 ----------
731 sessions
732 All calendar sessions.
733
734 start
735 Date from which special offsets to be applied.
736
737 end
738 Date through which special offsets to be applied.
739
740 Notes
741 -----
742 Incorporated to provide hook to `exchange_calendar_xkrx`.
743 """
744 return
745
746 # ------------------------------------------------------------------
747 # -- NO method below this line should be overriden on a subclass! --
748 # ------------------------------------------------------------------
749
750 # Methods and properties that define calendar (continued...).
751
752 @functools.cached_property
753 def day(self) -> CustomBusinessDay:
754 """CustomBusinessDay instance representing calendar sessions."""
755 return CustomBusinessDay(
756 holidays=self.adhoc_holidays,
757 calendar=self.regular_holidays,
758 weekmask=self.weekmask,
759 )
760
761 @classmethod
762 def valid_sides(cls) -> list[str]:
763 """List of valid `side` options."""
764 if cls.close_times == cls.open_times:
765 return ["left", "right"]
766 return ["both", "left", "right", "neither"]
767
768 @property
769 def side(self) -> Literal["left", "right", "both", "neither"]:
770 """Side on which sessions are closed.
771
772 Returns
773 -------
774 str
775 "left" - Session open and break_start are trading minutes.
776 Session close and break_end are not trading minutes.
777 "right" - Session close and break_end are trading minutes,
778 Session open and break_start are not tradng minutes.
779 "both" - Session open, session close, break_start and
780 break_end are all trading minutes.
781 "neither" - Session open, session close, break_start and
782 break_end are all not trading minutes.
783
784 Notes
785 -----
786 Subclasses should NOT override this method.
787 """
788 return self._side
789
790 # Properties covering all sessions.
791
792 @property
793 def sessions(self) -> pd.DatetimeIndex:
794 """All calendar sessions."""
795 return self.schedule.index
796
797 @functools.cached_property
798 def sessions_nanos(self) -> np.ndarray:
799 """All calendar sessions as nano seconds."""
800 return self.sessions.values.astype("int64")
801
802 @property
803 def opens(self) -> pd.Series:
804 """Open time of each session.
805
806 Returns
807 -------
808 pd.Series
809 index : pd.DatetimeIndex
810 All sessions.
811 dtype : datetime64[ns, UTC]
812 UTC open time of corresponding session.
813 """
814 return self.schedule.open
815
816 @property
817 def closes(self) -> pd.Series:
818 """Close time of each session.
819
820 Returns
821 -------
822 pd.Series
823 index : pd.DatetimeIndex
824 All sessions.
825 dtype : datetime64[ns, UTC]
826 UTC close time of corresponding session.
827 """
828 return self.schedule.close
829
830 @property
831 def break_starts(self) -> pd.Series:
832 """Break start time of each session.
833
834 Returns
835 -------
836 pd.Series
837 index : pd.DatetimeIndex
838 All sessions.
839 dtype : datetime64[ns, UTC]
840 UTC break-start time of corresponding session. Value is
841 missing (pd.NaT) for any session that does not have a
842 break.
843 """
844 return self.schedule.break_start
845
846 @property
847 def break_ends(self) -> pd.Series:
848 """Break end time of each session.
849
850 Returns
851 -------
852 pd.Series
853 index : pd.DatetimeIndex
854 All sessions.
855 dtype : datetime64[ns, UTC]
856 UTC break-end time of corresponding session.Value is
857 missing (pd.NaT) for any session that does not have a
858 break.
859 """
860 return self.schedule.break_end
861
862 @functools.cached_property
863 def first_minutes_nanos(self) -> np.ndarray:
864 """Each session's first minute as an integer."""
865 if self.side in self._LEFT_SIDES:
866 return self.opens_nanos
867 return one_minute_later(self.opens_nanos)
868
869 @functools.cached_property
870 def last_minutes_nanos(self) -> np.ndarray:
871 """Each session's last minute as an integer."""
872 if self.side in self._RIGHT_SIDES:
873 return self.closes_nanos
874 return one_minute_earlier(self.closes_nanos)
875
876 @functools.cached_property
877 def last_am_minutes_nanos(self) -> np.ndarray:
878 """Each morning subsessions's last minute as an integer."""
879 if self.side in self._RIGHT_SIDES:
880 return self.break_starts_nanos
881 return one_minute_earlier(self.break_starts_nanos)
882
883 @functools.cached_property
884 def first_pm_minutes_nanos(self) -> np.ndarray:
885 """Each afternoon subsessions's first minute as an integer."""
886 if self.side in self._LEFT_SIDES:
887 return self.break_ends_nanos
888 return one_minute_later(self.break_ends_nanos)
889
890 def _minutes_as_series(self, nanos: np.ndarray, name: str) -> pd.Series:
891 """Convert trading minute nanos to pd.Series."""
892 ser = pd.Series(pd.DatetimeIndex(nanos, tz=UTC), index=self.sessions)
893 ser.name = name
894 return ser
895
896 @property
897 def first_minutes(self) -> pd.Series:
898 """First trading minute of each session."""
899 return self._minutes_as_series(self.first_minutes_nanos, "first_minutes")
900
901 @property
902 def last_minutes(self) -> pd.Series:
903 """Last trading minute of each session."""
904 return self._minutes_as_series(self.last_minutes_nanos, "last_minutes")
905
906 @property
907 def last_am_minutes(self) -> pd.Series:
908 """Last am trading minute of each session."""
909 return self._minutes_as_series(self.last_am_minutes_nanos, "last_am_minutes")
910
911 @property
912 def first_pm_minutes(self) -> pd.Series:
913 """First pm trading minute of each session."""
914 return self._minutes_as_series(self.first_pm_minutes_nanos, "first_pm_minutes")
915
916 # Properties covering all minutes.
917
918 def _minutes(
919 self, side: Literal["left", "right", "both", "neither"]
920 ) -> pd.DatetimeIndex:
921 return pd.DatetimeIndex(
922 compute_minutes(
923 self.opens_nanos,
924 self.break_starts_nanos,
925 self.break_ends_nanos,
926 self.closes_nanos,
927 side,
928 ),
929 tz=UTC,
930 )
931
932 @functools.cached_property
933 def minutes(self) -> pd.DatetimeIndex:
934 """All trading minutes."""
935 return self._minutes(self.side)
936
937 @functools.cached_property
938 def minutes_nanos(self) -> np.ndarray:
939 """All trading minutes as nanoseconds."""
940 return self.minutes.values.astype(np.int64)
941
942 # Calendar properties.
943
944 @property
945 def first_session(self) -> pd.Timestamp:
946 """First calendar session."""
947 return self.sessions[0]
948
949 @property
950 def last_session(self) -> pd.Timestamp:
951 """Last calendar session."""
952 return self.sessions[-1]
953
954 @property
955 def first_session_open(self) -> pd.Timestamp:
956 """Open time of calendar's first session."""
957 return self.opens.iloc[0]
958
959 @property
960 def last_session_close(self) -> pd.Timestamp:
961 """Close time of calendar's last session."""
962 return self.closes.iloc[-1]
963
964 @property
965 def first_minute(self) -> pd.Timestamp:
966 """Calendar's first trading minute."""
967 return pd.Timestamp(self.minutes_nanos[0], tz=UTC)
968
969 @property
970 def last_minute(self) -> pd.Timestamp:
971 """Calendar's last trading minute."""
972 return pd.Timestamp(self.minutes_nanos[-1], tz=UTC)
973
974 @property
975 def has_break(self) -> bool:
976 """Query if any calendar session has a break."""
977 return self.sessions_has_break(
978 self.first_session, self.last_session, _parse=False
979 )
980
981 @property
982 def late_opens(self) -> pd.DatetimeIndex:
983 """Sessions that open later than the prevailing normal open.
984
985 NB. Prevailing normal open as defined by `open_times`.
986 """
987 return self._late_opens
988
989 @property
990 def early_closes(self) -> pd.DatetimeIndex:
991 """Sessions that close earlier than the prevailing normal close.
992
993 NB. Prevailing normal close as defined by `close_times`.
994 """
995 return self._early_closes
996
997 # Methods that interrogate a given session.
998
999 def _get_session_idx(self, session: Date, _parse=True) -> int:
1000 """Index position of a session."""
1001 session_ = parse_session(self, session) if _parse else session
1002 if TYPE_CHECKING:
1003 assert isinstance(session_, pd.Timestamp)
1004 return self.sessions_nanos.searchsorted(session_.value, side="left")
1005
1006 def session_open(self, session: Session, _parse: bool = True) -> pd.Timestamp:
1007 """Return open time for a given session."""
1008 if _parse:
1009 session = parse_session(self, session, "session")
1010 return self.schedule.loc[session, "open"]
1011
1012 def session_close(self, session: Session, _parse: bool = True) -> pd.Timestamp:
1013 """Return close time for a given session."""
1014 if _parse:
1015 session = parse_session(self, session, "session")
1016 return self.schedule.loc[session, "close"]
1017
1018 def session_break_start(
1019 self, session: Session, _parse: bool = True
1020 ) -> pd.Timestamp | NaTType:
1021 """Return break-start time for a given session.
1022
1023 Returns pd.NaT if no break.
1024 """
1025 if _parse:
1026 session = parse_session(self, session, "session")
1027 return self.schedule.loc[session, "break_start"]
1028
1029 def session_break_end(
1030 self, session: Session, _parse: bool = True
1031 ) -> pd.Timestamp | NaTType:
1032 """Return break-end time for a given session.
1033
1034 Returns pd.NaT if no break.
1035 """
1036 if _parse:
1037 session = parse_session(self, session, "session")
1038 return self.schedule.loc[session, "break_end"]
1039
1040 def session_open_close(
1041 self, session: Session, _parse: bool = True
1042 ) -> tuple[pd.Timestamp, pd.Timestamp]:
1043 """Return open and close times for a given session.
1044
1045 Parameters
1046 ----------
1047 session
1048 Session for which require open and close.
1049
1050 Returns
1051 -------
1052 tuple[pd.Timestamp, pd.Timestamp]
1053 [0] Open time of `session`.
1054 [1] Close time of `session`.
1055 """
1056 if _parse:
1057 session = parse_session(self, session)
1058 return self.session_open(session), self.session_close(session)
1059
1060 def session_break_start_end(
1061 self, session: Session, _parse: bool = True
1062 ) -> tuple[pd.Timestamp | NaTType, pd.Timestamp | NaTType]:
1063 """Return break-start and break-end times for a given session.
1064
1065 Parameters
1066 ----------
1067 session
1068 Session for which require break-start and break-end.
1069
1070 Returns
1071 -------
1072 tuple[pd.Timestamp | NaTType, pd.Timestamp | NaTType]
1073 [0] Break-start time of `session`, or pd.NaT if no break.
1074 [1] Close time of `session`, or pd.NaT if no break.
1075 """
1076 if _parse:
1077 session = parse_session(self, session)
1078 return self.session_break_start(session), self.session_break_end(session)
1079
1080 def _get_session_minute_from_nanos(
1081 self, session: Session, nanos: np.ndarray, _parse: bool
1082 ) -> pd.Timestamp:
1083 idx = self._get_session_idx(session, _parse=_parse)
1084 return pd.Timestamp(nanos[idx], tz=UTC)
1085
1086 def session_first_minute(
1087 self, session: Session, _parse: bool = True
1088 ) -> pd.Timestamp:
1089 """Return first trading minute of a given session."""
1090 nanos = self.first_minutes_nanos
1091 return self._get_session_minute_from_nanos(session, nanos, _parse)
1092
1093 def session_last_minute(
1094 self, session: Session, _parse: bool = True
1095 ) -> pd.Timestamp:
1096 """Return last trading minute of a given session."""
1097 nanos = self.last_minutes_nanos
1098 return self._get_session_minute_from_nanos(session, nanos, _parse)
1099
1100 def session_last_am_minute(
1101 self, session: Session, _parse: bool = True
1102 ) -> pd.Timestamp | pd.NaT:
1103 """Return last trading minute of am subsession of a given session."""
1104 nanos = self.last_am_minutes_nanos
1105 return self._get_session_minute_from_nanos(session, nanos, _parse)
1106
1107 def session_first_pm_minute(
1108 self, session: Session, _parse: bool = True
1109 ) -> pd.Timestamp | pd.NaT:
1110 """Return first trading minute of pm subsession of a given session."""
1111 nanos = self.first_pm_minutes_nanos
1112 return self._get_session_minute_from_nanos(session, nanos, _parse)
1113
1114 def session_first_last_minute(
1115 self,
1116 session: Session,
1117 _parse: bool = True,
1118 ) -> tuple[pd.Timestamp, pd.Timestamp]:
1119 """Return first and last trading minutes of a given session."""
1120 idx = self._get_session_idx(session, _parse=_parse)
1121 first = pd.Timestamp(self.first_minutes_nanos[idx], tz=UTC)
1122 last = pd.Timestamp(self.last_minutes_nanos[idx], tz=UTC)
1123 return (first, last)
1124
1125 def session_has_break(self, session: Session, _parse: bool = True) -> bool:
1126 """Query if a given session has a break.
1127
1128 Parameters
1129 ----------
1130 session
1131 Session to query.
1132
1133 Returns
1134 -------
1135 bool
1136 True if `session` has a break, false otherwise.
1137 """
1138 if _parse:
1139 session = parse_session(self, session)
1140 return bool(pd.notna(self.session_break_start(session)))
1141
1142 def next_session(self, session: Session, _parse: bool = True) -> pd.Timestamp:
1143 """Return session that immediately follows a given session.
1144
1145 Parameters
1146 ----------
1147 session
1148 Session whose next session is desired.
1149
1150 Raises
1151 ------
1152 errors.RequestedSessionOutOfBounds
1153 If `session` is the last calendar session.
1154
1155 See Also
1156 --------
1157 date_to_session
1158 """
1159 idx = self._get_session_idx(session, _parse=_parse)
1160 try:
1161 return self.schedule.index[idx + 1]
1162 except IndexError:
1163 if idx == len(self.schedule.index) - 1:
1164 raise errors.RequestedSessionOutOfBounds(
1165 self, too_early=False
1166 ) from None
1167 raise
1168
1169 def previous_session(self, session: Session, _parse: bool = True) -> pd.Timestamp:
1170 """Return session that immediately preceeds a given session.
1171
1172 Parameters
1173 ----------
1174 session
1175 Session whose previous session is desired.
1176
1177 Raises
1178 ------
1179 errors.RequestedSessionOutOfBounds
1180 If `session` is the first calendar session.
1181
1182 See Also
1183 --------
1184 date_to_session
1185 """
1186 idx = self._get_session_idx(session, _parse=_parse)
1187 if not idx:
1188 raise errors.RequestedSessionOutOfBounds(self, too_early=True)
1189 return self.schedule.index[idx - 1]
1190
1191 def session_minutes(
1192 self, session: Session, _parse: bool = True
1193 ) -> pd.DatetimeIndex:
1194 """Return trading minutes corresponding to a given session.
1195
1196 Parameters
1197 ----------
1198 session
1199 Session for which require trading minutes.
1200
1201 Returns
1202 -------
1203 pd.DateTimeIndex
1204 Trading minutes for `session`.
1205 """
1206 first, last = self.session_first_last_minute(session, _parse=_parse)
1207 return self.minutes_in_range(start=first, end=last)
1208
1209 def session_offset(
1210 self, session: Session, count: int, _parse: bool = True
1211 ) -> pd.Timestamp:
1212 """Offset a given session by a number of sessions.
1213
1214 Parameters
1215 ----------
1216 session
1217 Session from which to offset.
1218
1219 count
1220 Number of sessions to offset `session`. Positive to offset
1221 forwards, negative to offset backwards.
1222
1223 Returns
1224 -------
1225 pd.Timestamp
1226 Offset session.
1227
1228 Raises
1229 ------
1230 exchange_calendars.errors.RequestedSessionOutOfBounds
1231 If offset session would be either before the calendar's first
1232 session or after the calendar's last session.
1233 """
1234 idx = self._get_session_idx(session, _parse=_parse) + count
1235 if idx >= len(self.sessions):
1236 raise errors.RequestedSessionOutOfBounds(self, too_early=False)
1237 if idx < 0:
1238 raise errors.RequestedSessionOutOfBounds(self, too_early=True)
1239 return self.sessions[idx]
1240
1241 # Methods that interrogate a date.
1242
1243 def _get_date_idx(self, date: Date, _parse=True) -> int:
1244 """Index position of a date.
1245
1246 Returns
1247 -------
1248 Index position of session if `date` represents a session,
1249 otherwise index position of session that immediately
1250 follows `date`.
1251 """
1252 date_ = parse_date(date, "date", self) if _parse else date
1253 if TYPE_CHECKING:
1254 assert isinstance(date_, pd.Timestamp)
1255 return self.sessions_nanos.searchsorted(date_.value, side="left")
1256
1257 def _date_oob(self, date: pd.Timestamp) -> bool:
1258 """Is `date` out-of-bounds."""
1259 return (
1260 date.value < self.sessions_nanos[0] or date.value > self.sessions_nanos[-1]
1261 )
1262
1263 def is_session(self, date: Date, _parse: bool = True) -> bool:
1264 """Query if a date is a valid session.
1265
1266 Parameters
1267 ----------
1268 date
1269 Date to be queried.
1270
1271 Return
1272 ------
1273 bool
1274 True if `date` is a session, False otherwise.
1275 """
1276 if _parse:
1277 date = parse_date(date, "date", self)
1278 idx = self._get_date_idx(date, _parse=False)
1279 return bool(self.sessions_nanos[idx] == date.value) # convert from np.bool_
1280
1281 def date_to_session(
1282 self,
1283 date: Date,
1284 direction: Literal["next", "previous", "none"] = "none",
1285 _parse: bool = True,
1286 ) -> pd.Timestamp:
1287 """Return a session corresponding to a given date.
1288
1289 Parameters
1290 ----------
1291 date
1292 Date for which require session. Can be a date that does not
1293 represent an actual session (see `direction`).
1294
1295 direction : default: "none"
1296 Defines behaviour if `date` does not represent a session:
1297 "next" - return first session following `date`.
1298 "previous" - return first session prior to `date`.
1299 "none" - raise ValueError.
1300
1301 See Also
1302 --------
1303 next_session
1304 previous_session
1305 """
1306 if _parse:
1307 date = parse_date(date, calendar=self)
1308 if self.is_session(date, _parse=False):
1309 return date
1310 if direction in ["next", "previous"]:
1311 idx = self._get_date_idx(date, _parse=False)
1312 if direction == "previous":
1313 idx -= 1
1314 return self.sessions[idx]
1315 if direction == "none":
1316 raise ValueError(
1317 f"`date` '{date}' does not represent a session. Consider passing"
1318 " a `direction`."
1319 )
1320 raise ValueError(
1321 f"'{direction}' is not a valid `direction`. Valid `direction`"
1322 ' values are "next", "previous" and "none".'
1323 )
1324
1325 # Methods that interrogate a given minute (trading or non-trading).
1326
1327 def _get_minute_idx(self, minute: Minute, _parse=True) -> int:
1328 """Index position of a minute.
1329
1330 Returns
1331 -------
1332 Index position of trading minute if `minute` represents a
1333 trading minute, otherwise index position of trading
1334 minute that immediately follows `minute`.
1335 """
1336 if _parse:
1337 minute = parse_timestamp(minute, "minute", self)
1338 return self.minutes_nanos.searchsorted(minute.value, side="left")
1339
1340 def _minute_oob(self, minute: Minute) -> bool:
1341 """Is `minute` out-of-bounds."""
1342 return (
1343 minute.value < self.minutes_nanos[0]
1344 or minute.value > self.minutes_nanos[-1]
1345 )
1346
1347 def is_trading_minute(self, minute: Minute, _parse: bool = True) -> bool:
1348 """Query if a given minute is a trading minute.
1349
1350 Minutes during breaks are not considered trading minutes.
1351
1352 Note: `self.side` determines whether exchange will be considered
1353 open or closed on session open, session close, break start and
1354 break end.
1355
1356 Parameters
1357 ----------
1358 minute
1359 Minute being queried.
1360
1361 Returns
1362 -------
1363 bool
1364 Boolean indicting if `minute` is a trading minute.
1365
1366 See Also
1367 --------
1368 is_open_on_minute
1369 is_open_at_time
1370 """
1371 if _parse:
1372 minute = parse_timestamp(minute, calendar=self)
1373 idx = self._get_minute_idx(minute, _parse=False)
1374 # convert from np.bool_
1375 return bool(self.minutes_nanos[idx] == minute.value)
1376
1377 def is_break_minute(self, minute: Minute, _parse: bool = True) -> bool:
1378 """Query if a given minute is within a break.
1379
1380 Note: `self.side` determines whether either, both or one of break
1381 start and break end are treated as break minutes.
1382
1383 Parameters
1384 ----------
1385 minute
1386 Minute being queried.
1387
1388 Returns
1389 -------
1390 bool
1391 Boolean indicting if `minute` is a break minute.
1392 """
1393 if _parse:
1394 minute = parse_timestamp(minute, calendar=self)
1395 session_idx = np.searchsorted(self.first_minutes_nanos, minute.value) - 1
1396 break_start = self.last_am_minutes_nanos[session_idx]
1397 break_end = self.first_pm_minutes_nanos[session_idx]
1398 # NaT comparisions evalute as False
1399 numpy_bool = break_start < minute.value < break_end
1400 return bool(numpy_bool)
1401
1402 def is_open_on_minute(
1403 self, minute: Minute, ignore_breaks: bool = False, _parse: bool = True
1404 ) -> bool:
1405 """Query if exchange is open on a given minute.
1406
1407 Note: `self.side` determines whether exchange will be considered
1408 open or closed on session open, session close, break start and
1409 break end.
1410
1411 Parameters
1412 ----------
1413 minute
1414 Minute being queried.
1415
1416 ignore_breaks
1417 Should exchange be considered open during any break?
1418 True - treat exchange as open during any break.
1419 False - treat exchange as closed during any break.
1420
1421 Returns
1422 -------
1423 bool
1424 Boolean indicting if exchange is open on `minute`.
1425
1426 See Also
1427 --------
1428 is_trading_minute
1429 is_open_at_time
1430 """
1431 if _parse:
1432 minute = parse_timestamp(minute, "minute", self)
1433
1434 is_trading_minute = self.is_trading_minute(minute, _parse=False)
1435 if is_trading_minute or not ignore_breaks:
1436 return is_trading_minute
1437 # not a trading minute although should return True if in break
1438 return self.is_break_minute(minute, _parse=False)
1439
1440 def is_open_at_time(
1441 self,
1442 timestamp: pd.Timestamp,
1443 side: Literal["left", "right", "both", "neither"] = "left",
1444 ignore_breaks: bool = False,
1445 ) -> bool:
1446 """Query if exchange is open at a given timestamp.
1447
1448 Note: method differs from `is_trading_minute` and
1449 `is_open_on_minute` in that it does not consider if the market is
1450 open over an evaluated minute, but rather as at a specific
1451 instance that can be of any resolution.
1452
1453 Parameters
1454 ----------
1455 timestamp
1456 Timestamp being queried.
1457
1458 Can have any resolution (i.e. can be defined with second and
1459 more accurate components).
1460
1461 If timezone naive then will be assumed as representing UTC.
1462
1463 side
1464 Determines whether the exchange will be considered open or
1465 closed on a session's open, close, break-start and break-end:
1466
1467 "left" - treat exchange as open on session open and
1468 any break-end, treat as closed on session close and any
1469 break-start.
1470
1471 "right" - treat exchange as open on session close and
1472 any break-start, treat as closed on session open and any
1473 break-end.
1474
1475 "both" (default) - treat exchange as open on all of session
1476 open, close and any break-start and break-end.
1477
1478 "neither" - treat exchange as closed on all of session
1479 open, close and any break-start and break-end.
1480
1481 ignore_breaks
1482 Should exchange be considered open during any break?
1483 True - treat exchange as open during any break.
1484 False - treat exchange as closed during any break.
1485
1486 Returns
1487 -------
1488 bool
1489 Boolean indicting if exchange is open at time.
1490
1491 See Also
1492 --------
1493 is_trading_minute
1494 is_open_on_minute
1495 """
1496 ts = timestamp
1497 if not isinstance(ts, pd.Timestamp):
1498 raise TypeError(
1499 "`timestamp` expected to receive type pd.Timestamp although"
1500 f" got type {type(ts)}."
1501 )
1502
1503 if ts.tz is not UTC:
1504 ts = ts.tz_localize(UTC) if ts.tz is None else ts.tz_convert(UTC)
1505
1506 if self._minute_oob(ts):
1507 raise errors.MinuteOutOfBounds(self, ts, "timestamp")
1508
1509 op_left = operator.le if side in self._LEFT_SIDES else operator.lt
1510 op_right = operator.le if side in self._RIGHT_SIDES else operator.lt
1511
1512 nano = ts.value
1513 if not self.has_break or ignore_breaks:
1514 # only one check requried
1515 bv = op_left(self.opens_nanos, nano) & op_right(nano, self.closes_nanos)
1516 return bool(bv.any())
1517
1518 break_starts_nanos = self.break_starts_nanos.copy()
1519 bv_missing = self.break_starts.isna()
1520 close_replacement = self.closes_nanos[bv_missing]
1521 break_starts_nanos[bv_missing] = close_replacement
1522 break_ends_nanos = self.break_ends_nanos.copy()
1523 break_ends_nanos[bv_missing] = close_replacement
1524
1525 bv_am = op_left(self.opens_nanos, nano) & op_right(nano, break_starts_nanos)
1526 bv_pm = op_left(break_ends_nanos, nano) & op_right(nano, self.closes_nanos)
1527 return bool((bv_am | bv_pm).any())
1528
1529 def next_open(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
1530 """Return next open that follows a given minute.
1531
1532 If `minute` is a session open, the next session's open will be
1533 returned.
1534
1535 Parameters
1536 ----------
1537 minute
1538 Minute for which to get the next open.
1539
1540 Returns
1541 -------
1542 pd.Timestamp
1543 UTC timestamp of the next open.
1544 """
1545 if _parse:
1546 minute = parse_timestamp(minute, "minute", self)
1547 try:
1548 idx = next_divider_idx(self.opens_nanos, minute.value)
1549 except IndexError:
1550 if minute >= self.opens.iloc[-1]:
1551 raise ValueError(
1552 "Minute cannot be the last open or later (received `minute`"
1553 f" parsed as '{minute}'.)"
1554 ) from None
1555 raise
1556
1557 return pd.Timestamp(self.opens_nanos[idx], tz=UTC)
1558
1559 def next_close(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
1560 """Return next close that follows a given minute.
1561
1562 If `minute` is a session close, the next session's close will be
1563 returned.
1564
1565 Parameters
1566 ----------
1567 minute
1568 Minute for which to get the next close.
1569
1570 Returns
1571 -------
1572 pd.Timestamp
1573 UTC timestamp of the next close.
1574 """
1575 if _parse:
1576 minute = parse_timestamp(minute, "minute", self)
1577 try:
1578 idx = next_divider_idx(self.closes_nanos, minute.value)
1579 except IndexError:
1580 if minute == self.closes.iloc[-1]:
1581 raise ValueError(
1582 "Minute cannot be the last close (received `minute` parsed as"
1583 f" '{minute}'.)"
1584 ) from None
1585 raise
1586 return pd.Timestamp(self.closes_nanos[idx], tz=UTC)
1587
1588 def previous_open(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
1589 """Return previous open that preceeds a given minute.
1590
1591 If `minute` is a session open, the previous session's open will be
1592 returned.
1593
1594 Parameters
1595 ----------
1596 minute
1597 Minute for which to get the previous open.
1598
1599 Returns
1600 -------
1601 pd.Timestamp
1602 UTC timestamp of the previous open.
1603 """
1604 if _parse:
1605 minute = parse_timestamp(minute, "minute", self)
1606 try:
1607 idx = previous_divider_idx(self.opens_nanos, minute.value)
1608 except ValueError:
1609 if minute == self.opens.iloc[0]:
1610 raise ValueError(
1611 "Minute cannot be the first open (received `minute` parsed as"
1612 f" '{minute}'.)"
1613 ) from None
1614 raise
1615
1616 return pd.Timestamp(self.opens_nanos[idx], tz=UTC)
1617
1618 def previous_close(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
1619 """Return previous close that preceeds a given minute.
1620
1621 If `minute` is a session close, the previous session's close will be
1622 returned.
1623
1624 Parameters
1625 ----------
1626 minute
1627 Minute for which to get the previous close.
1628
1629 Returns
1630 -------
1631 pd.Timestamp
1632 UTC timestamp of the previous close.
1633 """
1634 if _parse:
1635 minute = parse_timestamp(minute, "minute", self)
1636 try:
1637 idx = previous_divider_idx(self.closes_nanos, minute.value)
1638 except ValueError:
1639 if minute <= self.closes.iloc[0]:
1640 raise ValueError(
1641 "Minute cannot be the first close or earlier (received"
1642 f" `minute` parsed as '{minute}'.)"
1643 ) from None
1644 raise
1645
1646 return pd.Timestamp(self.closes_nanos[idx], tz=UTC)
1647
1648 def next_minute(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
1649 """Return trading minute that immediately follows a given minute.
1650
1651 Parameters
1652 ----------
1653 minute
1654 Minute for which to get next trading minute. Minute can be a
1655 trading or a non-trading minute.
1656
1657 Returns
1658 -------
1659 pd.Timestamp
1660 UTC timestamp of the next minute.
1661
1662 Raises
1663 ------
1664 errors.RequestedSessionOutOfBounds
1665 If `minute` is the last calendar minute.
1666 """
1667 if _parse:
1668 minute = parse_timestamp(minute, "minute", self)
1669 try:
1670 idx = next_divider_idx(self.minutes_nanos, minute.value)
1671 except IndexError:
1672 # dt > last_minute handled via parsing
1673 if minute == self.last_minute:
1674 raise errors.RequestedMinuteOutOfBounds(self, too_early=False) from None
1675 return self.minutes[idx]
1676
1677 def previous_minute(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
1678 """Return trading minute that immediately preceeds a given minute.
1679
1680 Parameters
1681 ----------
1682 minute
1683 Minute for which to get previous trading minute. Minute can be
1684 a trading or a non-trading minute.
1685
1686 Returns
1687 -------
1688 pd.Timestamp
1689 UTC timestamp of the previous minute.
1690
1691 Raises
1692 ------
1693 errors.RequestedSessionOutOfBounds
1694 If `minute` is the first calendar minute.
1695 """
1696 if _parse:
1697 minute = parse_timestamp(minute, "minute", self)
1698 try:
1699 idx = previous_divider_idx(self.minutes_nanos, minute.value)
1700 except ValueError:
1701 # dt < first_minute handled via parsing
1702 if minute == self.first_minute:
1703 raise errors.RequestedMinuteOutOfBounds(self, too_early=True) from None
1704 return self.minutes[idx]
1705
1706 def minute_to_session( # noqa: C901
1707 self,
1708 minute: Minute,
1709 direction: Literal["next", "previous", "none"] = "next",
1710 _parse: bool = True,
1711 ) -> pd.Timestamp:
1712 """Get session corresponding with a trading or break minute.
1713
1714 Parameters
1715 ----------
1716 minute
1717 Minute for which require corresponding session.
1718
1719 direction
1720 How to resolve session in event that `minute` is not a trading
1721 or break minute:
1722 "next" (default) - return first session subsequent to
1723 `minute`.
1724 "previous" - return first session prior to `minute`.
1725 "none" - raise ValueError.
1726
1727 Returns
1728 -------
1729 pd.Timestamp
1730 Corresponding session label.
1731
1732 Raises
1733 ------
1734 ValueError
1735 If `minute` is not a trading minute and `direction` is "none".
1736
1737 See Also
1738 --------
1739 minute_to_past_session
1740 minute_to_future_session
1741 session_offset
1742 """
1743 if _parse:
1744 minute = parse_timestamp(minute, calendar=self)
1745
1746 if minute.value < self.minutes_nanos[0]:
1747 # Resolve call here.
1748 if direction == "next":
1749 return self.first_session
1750 raise ValueError(
1751 f"Received `minute` as '{minute}' although this is earlier than the"
1752 f" calendar's first trading minute ({self.first_minute}). Consider"
1753 " passing `direction` as 'next' to get first session."
1754 )
1755
1756 if minute.value > self.minutes_nanos[-1]:
1757 # Resolve call here.
1758 if direction == "previous":
1759 return self.last_session
1760 raise ValueError(
1761 f"Received `minute` as '{minute}' although this is later than the"
1762 f" calendar's last trading minute ({self.last_minute}). Consider"
1763 " passing `direction` as 'previous' to get last session."
1764 )
1765
1766 idx = np.searchsorted(self.last_minutes_nanos, minute.value)
1767 current_or_next_session = self.schedule.index[idx]
1768
1769 if direction == "next":
1770 return current_or_next_session
1771 if direction == "previous":
1772 if not self.is_open_on_minute(minute, ignore_breaks=True, _parse=False):
1773 return self.schedule.index[idx - 1]
1774 elif direction == "none":
1775 if not self.is_open_on_minute(minute, ignore_breaks=True, _parse=False):
1776 # if the exchange is closed, blow up
1777 raise ValueError(
1778 f"`minute` '{minute}' is not a trading minute. Consider passing"
1779 " `direction` as 'next' or 'previous'."
1780 )
1781 else:
1782 # invalid direction
1783 raise ValueError(f"Invalid direction parameter: {direction}")
1784
1785 return current_or_next_session
1786
1787 def minute_to_past_session(
1788 self, minute: Minute, count: int = 1, _parse: bool = True
1789 ) -> pd.Timestamp:
1790 """Get a session that closed before a given minute.
1791
1792 Parameters
1793 ----------
1794 minute
1795 Minute for which to return a previous session. Can be a
1796 trading minute or non-trading minute.
1797 Note: if `minute` is a trading minute then returned session
1798 will not be the session of which `minute` is a trading minute,
1799 but rather a session that closed before `minute`.
1800
1801 count : default: 1
1802 Number of sessions prior to `minute` for which require session.
1803
1804 Returns
1805 -------
1806 pd.Timstamp
1807 Session that is `count` full sessions before `minute`.
1808
1809 See Also
1810 --------
1811 minute_to_session
1812 minute_to_future_session
1813 session_offset
1814 """
1815 if _parse:
1816 minute = parse_timestamp(minute, calendar=self)
1817 if count <= 0:
1818 raise ValueError("`count` must be higher than 0.")
1819 if self.is_open_on_minute(minute, ignore_breaks=True, _parse=False):
1820 current_session = self.minute_to_session(minute, _parse=False)
1821 base_session = self.previous_session(current_session, _parse=False)
1822 else:
1823 base_session = self.minute_to_session(minute, "previous", _parse=False)
1824 count -= 1
1825 return self.session_offset(base_session, -count, _parse=False)
1826
1827 def minute_to_future_session(
1828 self,
1829 minute: Minute,
1830 count: int = 1,
1831 _parse: bool = True,
1832 ) -> pd.Timestamp:
1833 """Get a session that opens after a given minute.
1834
1835 Parameters
1836 ----------
1837 minute
1838 Minute for which to return a future session. Can be a trading
1839 minute or non-trading minute.
1840 Note: if `minute` is a trading minute then returned session
1841 will not be the session of which `minute` is a trading minute,
1842 but rather a session that opens after `minute`.
1843
1844 count : default: 1
1845 Number of sessions following `minute` for which require
1846 session.
1847
1848 Returns
1849 -------
1850 pd.Timstamp
1851 Session that is `count` full sessions after `minute`.
1852
1853 See Also
1854 --------
1855 minute_to_session
1856 minute_to_past_session
1857 session_offset
1858 """
1859 if _parse:
1860 minute = parse_timestamp(minute, calendar=self)
1861 if count <= 0:
1862 raise ValueError("`count` must be higher than 0.")
1863 if self.is_open_on_minute(minute, ignore_breaks=True, _parse=False):
1864 current_session = self.minute_to_session(minute, _parse=False)
1865 base_session = self.next_session(current_session, _parse=False)
1866 else:
1867 base_session = self.minute_to_session(minute, "next", _parse=False)
1868 count -= 1
1869 return self.session_offset(base_session, count, _parse=False)
1870
1871 def minute_to_trading_minute(
1872 self,
1873 minute: Minute,
1874 direction: Literal["next", "previous", "none"] = "none",
1875 _parse: bool = True,
1876 ) -> pd.Timestamp:
1877 """Resolve a minute to a trading minute.
1878
1879 Differs from `previous_minute` and `next_minute` by returning
1880 `minute` unchanged if `minute` is a trading minute.
1881
1882 Parameters
1883 ----------
1884 minute
1885 Timestamp to be resolved to a trading minute.
1886
1887 direction:
1888 How to resolve `minute` if does not represent a trading minute:
1889 'next' - return trading minute that immediately follows
1890 `minute`.
1891 'previous' - return trading minute that immediately
1892 preceeds `minute`.
1893 'none' - raise KeyError
1894
1895 Returns
1896 -------
1897 pd.Timestamp
1898 Returns `minute` if `minute` is a trading minute otherwise
1899 first trading minute that, in accordance with `direction`,
1900 either immediately follows or preceeds `minute`.
1901
1902 Raises
1903 ------
1904 ValueError
1905 If `minute` is not a trading minute and `direction` is None.
1906
1907 See Also
1908 --------
1909 next_mintue
1910 previous_minute
1911 """
1912 if _parse:
1913 minute = parse_timestamp(minute, calendar=self)
1914 if self.is_trading_minute(minute, _parse=False):
1915 return minute
1916 if direction == "next":
1917 return self.next_minute(minute, _parse=False)
1918 if direction == "previous":
1919 return self.previous_minute(minute, _parse=False)
1920 raise ValueError(
1921 f"`minute` '{minute}' is not a trading minute. Consider passing"
1922 " `direction` as 'next' or 'previous'."
1923 )
1924
1925 def minute_offset(
1926 self, minute: TradingMinute, count: int, _parse: bool = True
1927 ) -> pd.Timestamp:
1928 """Offset a given trading minute by a number of trading minutes.
1929
1930 Parameters
1931 ----------
1932 minute
1933 Trading minute from which to offset.
1934
1935 count
1936 Number of trading minutes to offset `minute`. Positive to
1937 offset forwards, negative to offset backwards.
1938
1939 Returns
1940 -------
1941 pd.Timstamp
1942 Offset trading minute.
1943
1944 Raises
1945 ------
1946 ValueError
1947 If offset minute would be either before the calendar's first
1948 trading minute or after the calendar's last trading minute.
1949 """
1950 if _parse:
1951 minute = parse_trading_minute(self, minute)
1952 idx = self._get_minute_idx(minute) + count
1953 if idx >= len(self.minutes_nanos):
1954 raise errors.RequestedMinuteOutOfBounds(self, too_early=False)
1955 if idx < 0:
1956 raise errors.RequestedMinuteOutOfBounds(self, too_early=True)
1957 return self.minutes[idx]
1958
1959 def minute_offset_by_sessions( # noqa: C901, PLR0912
1960 self,
1961 minute: TradingMinute,
1962 count: int = 1,
1963 _parse: bool = True,
1964 ) -> pd.Timestamp:
1965 """Offset trading minute by a given number of sessions.
1966
1967 If trading minute is not represented in target session (due to a late
1968 open for example) then offset minute will be rolled (with respect to
1969 the target session):
1970 - forwards to first session minute, if offset minute otherwise
1971 falls earlier than first session minute.
1972 - back to last session minute, if offset minute otherwise falls
1973 later than last session minute.
1974 - back to last minute before break, if offset otherwise
1975 falls in session break.
1976
1977 Parameters
1978 ----------
1979 minute
1980 Trading minute to be offset.
1981
1982 count
1983 Number of sessions by which to offset trading minute. Negative
1984 to offset to an earlier session.
1985 """
1986 if _parse:
1987 minute = parse_trading_minute(self, minute)
1988 if not count:
1989 return minute
1990
1991 if count > 0:
1992 try:
1993 target_session = self.minute_to_future_session(minute, abs(count))
1994 except errors.RequestedSessionOutOfBounds:
1995 raise errors.RequestedMinuteOutOfBounds(self, too_early=False) from None
1996 else:
1997 try:
1998 target_session = self.minute_to_past_session(minute, abs(count))
1999 except errors.RequestedSessionOutOfBounds:
2000 raise errors.RequestedMinuteOutOfBounds(self, too_early=True) from None
2001
2002 base_session = self.minute_to_session(minute)
2003 day_offset = (minute.normalize() - base_session.tz_localize(UTC)).days
2004
2005 minute = target_session.replace(hour=minute.hour, minute=minute.minute)
2006 minute = minute.tz_localize(UTC)
2007 minute += pd.Timedelta(days=day_offset)
2008
2009 if self._minute_oob(minute):
2010 if minute.value < self.minutes_nanos[0]:
2011 errors.RequestedMinuteOutOfBounds(self, too_early=True)
2012 if minute.value > self.minutes_nanos[-1]:
2013 raise errors.RequestedMinuteOutOfBounds(self, too_early=False)
2014
2015 if self.is_trading_minute(minute, _parse=False) and (
2016 self.minute_to_session(minute, _parse=False) == target_session
2017 ):
2018 # this guard is necessary as minute can be for a different session than the
2019 # intended if the gap between sessions is less than any difference in the
2020 # open or close times (i.e. only relevant if base and target sessions have
2021 # different open/close times.
2022 return minute
2023 first_minute = self.session_first_minute(target_session, _parse=False)
2024 if minute < first_minute:
2025 return first_minute
2026 last_minute = self.session_last_minute(target_session, _parse=False)
2027 if minute > last_minute:
2028 return last_minute
2029 if self.is_break_minute(minute, _parse=False):
2030 return self.session_last_am_minute(target_session, _parse=False)
2031 raise AssertionError("offset minute should have resolved!")
2032
2033 # Methods that evaluate or interrogate a range of minutes.
2034
2035 def _get_minutes_slice(self, start: Minute, end: Minute, _parse=True) -> slice:
2036 """Slice representing a range of trading minutes."""
2037 if _parse:
2038 start = parse_timestamp(start, "start", self)
2039 end = parse_timestamp(end, "end", self)
2040 slice_start = self.minutes_nanos.searchsorted(start.value, side="left")
2041 slice_end = self.minutes_nanos.searchsorted(end.value, side="right")
2042 return slice(slice_start, slice_end)
2043
2044 def minutes_in_range(
2045 self, start: Minute, end: Minute, _parse: bool = True
2046 ) -> pd.DatetimeIndex:
2047 """Return all trading minutes between given minutes.
2048
2049 Parameters
2050 ----------
2051 start
2052 Minute representing start of desired range. Can be a trading
2053 minute or non-trading minute.
2054
2055 end
2056 Minute representing end of desired range. Can be a trading
2057 minute or non-trading minute.
2058 """
2059 slc = self._get_minutes_slice(start, end, _parse)
2060 return self.minutes[slc]
2061
2062 def minutes_window(
2063 self, minute: TradingMinute, count: int, _parse: bool = True
2064 ) -> pd.DatetimeIndex:
2065 """Return block of given size of consecutive trading minutes.
2066
2067 Parameters
2068 ----------
2069 minute
2070 Minute representing the first (if `count` positive) or last
2071 (if `count` negative) minute of minutes window.
2072
2073 count
2074 Number of mintues to include in window.
2075 Positive to return a block of minutes from `minute`
2076 Negative to return a block of minutes to `minute`.
2077 """
2078 if not count:
2079 raise ValueError("`count` cannot be 0.")
2080 if _parse:
2081 minute = parse_trading_minute(self, minute, "minute")
2082
2083 start_idx = self._get_minute_idx(minute, _parse=False)
2084 end_idx = start_idx + count + (-1 if count > 0 else 1)
2085
2086 if end_idx < 0:
2087 raise ValueError(
2088 f"Minutes window cannot begin before the calendar's first minute"
2089 f" ({self.first_minute}). `count` cannot be lower than"
2090 f" {count - end_idx} for `minute` '{minute}'."
2091 )
2092 if end_idx >= len(self.minutes_nanos):
2093 raise ValueError(
2094 f"Minutes window cannot end after the calendar's last minute"
2095 f" ({self.last_minute}). `count` cannot be higher than"
2096 f" {count - (end_idx - len(self.minutes_nanos) + 1)} for `minute`"
2097 f" '{minute}'."
2098 )
2099 return self.minutes[min(start_idx, end_idx) : max(start_idx, end_idx) + 1]
2100
2101 def minutes_distance(self, start: Minute, end: Minute, _parse: bool = True) -> int:
2102 """Return the number of minutes in a range.
2103
2104 Parameters
2105 ----------
2106 start
2107 Start of minute range (range inclusive of `start`).
2108
2109 end
2110 End of minute range (range inclusive of `end`).
2111
2112 Returns
2113 -------
2114 int
2115 Number of minutes in minute range, If `start` is later than
2116 `end` then return will be negated.
2117 """
2118 if _parse:
2119 start = parse_timestamp(start, "start", self)
2120 end = parse_timestamp(end, "end", self)
2121 negate = end < start
2122 if negate:
2123 start, end = end, start
2124 slc = self._get_minutes_slice(start, end, _parse=False)
2125 return slc.start - slc.stop if negate else slc.stop - slc.start
2126
2127 def minutes_to_sessions(self, minutes: pd.DatetimeIndex) -> pd.DatetimeIndex:
2128 """Return sessions corresponding to multiple trading minutes.
2129
2130 For the purpose of this method trading minutes are considered as:
2131 - Trading minutes as determined by `self.side`.
2132 - All minutes of any breaks.
2133
2134 Parameters
2135 ----------
2136 minutes
2137 Sorted DatetimeIndex representing market minutes for which to get
2138 corresponding sessions.
2139
2140 Returns
2141 -------
2142 pd.DatetimeIndex
2143 Sessions corresponding to `minutes`.
2144
2145 Raises
2146 ------
2147 ValueError
2148 If any indice of `minute` is not a trading minute.
2149 """
2150 if not minutes.is_monotonic_increasing:
2151 raise ValueError("`index` must be ordered.")
2152 # Find the indices of the previous first session minute and the next
2153 # last session minute for each minute.
2154 index_nanos = minutes.values.astype(np.int64)
2155 first_min_nanos = self.first_minutes_nanos
2156 last_min_nanos = self.last_minutes_nanos
2157 prev_first_mins_idxs = (
2158 first_min_nanos.searchsorted(index_nanos, side="right") - 1
2159 )
2160 next_last_mins_idxs = last_min_nanos.searchsorted(index_nanos, side="left")
2161
2162 # If they don't match, the minute is outside the trading day. Barf.
2163 mismatches = prev_first_mins_idxs != next_last_mins_idxs
2164 if mismatches.any():
2165 # Show the first bad minute in the error message.
2166 bad_ix = np.flatnonzero(mismatches)[0]
2167 example = minutes[bad_ix]
2168
2169 prev_session_idx = prev_first_mins_idxs[bad_ix]
2170 prev_first_min = pd.Timestamp(first_min_nanos[prev_session_idx], tz=UTC)
2171 prev_last_min = pd.Timestamp(last_min_nanos[prev_session_idx], tz=UTC)
2172 next_first_min = pd.Timestamp(first_min_nanos[prev_session_idx + 1], tz=UTC)
2173 next_last_min = pd.Timestamp(last_min_nanos[prev_session_idx + 1], tz=UTC)
2174
2175 raise ValueError(
2176 f"{mismatches.sum()} non-trading minutes in"
2177 f" minutes_to_sessions:\nFirst Bad Minute: {example}\n"
2178 f"Previous Session: {prev_first_min} -> {prev_last_min}\n"
2179 f"Next Session: {next_first_min} -> {next_last_min}"
2180 )
2181
2182 return self.schedule.index[prev_first_mins_idxs]
2183
2184 # Methods that evaluate or interrogate a range of sessions.
2185
2186 def _parse_start_end_dates(
2187 self, start: Date, end: Date, _parse: bool
2188 ) -> tuple[pd.Timestamp, pd.Timestamp]:
2189 if not _parse:
2190 return start, end
2191 return parse_date(start, "start", self), parse_date(end, "end", self)
2192
2193 def _get_sessions_slice(self, start: Date, end: Date, _parse=True) -> slice:
2194 """Slice representing a range of sessions."""
2195 start, end = self._parse_start_end_dates(start, end, _parse)
2196 slice_start = self.sessions_nanos.searchsorted(start.value, side="left")
2197 slice_end = self.sessions_nanos.searchsorted(end.value, side="right")
2198 return slice(slice_start, slice_end)
2199
2200 def sessions_in_range(
2201 self, start: Date, end: Date, _parse: bool = True
2202 ) -> pd.DatetimeIndex:
2203 """Return sessions within a given range.
2204
2205 Parameters
2206 ----------
2207 start
2208 Start of session range (range inclusive of `start`).
2209
2210 end
2211 End of session range (range inclusive of `end`).
2212
2213 Returns
2214 -------
2215 pd.DatetimeIndex
2216 Sessions from `start` through `end`.
2217 """
2218 slc = self._get_sessions_slice(start, end, _parse)
2219 return self.sessions[slc]
2220
2221 def sessions_has_break(self, start: Date, end: Date, _parse: bool = True) -> bool:
2222 """Query if at least one session in a session range has a break.
2223
2224 Parameters
2225 ----------
2226 start
2227 Start of session range (range inclusive of `start`).
2228
2229 end
2230 End of session range (range inclusive of `end`).
2231
2232 Returns
2233 -------
2234 bool
2235 True if any session in session range has a break, False otherwise.
2236 """
2237 slc = self._get_sessions_slice(start, end, _parse)
2238 return self.break_starts[slc].notna().any()
2239
2240 def sessions_window(
2241 self, session: Session, count: int, _parse: bool = True
2242 ) -> pd.DatetimeIndex:
2243 """Return block of given size of consecutive sessions.
2244
2245 Parameters
2246 ----------
2247 session
2248 Session representing the first (if `count` positive) or last
2249 (if `count` negative) session of session window.
2250
2251 count
2252 Number of sessions to include in window.
2253 Positive to return window of sessions from `session`
2254 Negative to return window of sessions to `session`.
2255 """
2256 if not count:
2257 raise ValueError("`count` cannot be 0.")
2258 if _parse:
2259 session = parse_session(self, session, "session")
2260 start_idx = self._get_session_idx(session, _parse=False)
2261 end_idx = start_idx + count + (-1 if count > 0 else 1)
2262 if end_idx < 0:
2263 raise ValueError(
2264 f"Sessions window cannot begin before the first calendar session"
2265 f" ({self.first_session}). `count` cannot be lower than"
2266 f" {count - end_idx} for `session` '{session}'."
2267 )
2268 if end_idx >= len(self.sessions):
2269 raise ValueError(
2270 f"Sessions window cannot end after the last calendar session"
2271 f" ({self.last_session}). `count` cannot be higher than"
2272 f" {count - (end_idx - len(self.sessions) + 1)} for"
2273 f" `session` '{session}'."
2274 )
2275 return self.sessions[min(start_idx, end_idx) : max(start_idx, end_idx) + 1]
2276
2277 def sessions_distance(self, start: Date, end: Date, _parse: bool = True) -> int:
2278 """Return the number of sessions in a range.
2279
2280 Parameters
2281 ----------
2282 start
2283 Start of session range (range inclusive of `start`).
2284
2285 end
2286 End of session range (range inclusive of `end`).
2287
2288 Returns
2289 -------
2290 int
2291 Number of sessions in session range, If `start` is later than
2292 `end` then return will be negated.
2293 """
2294 start, end = self._parse_start_end_dates(start, end, _parse)
2295 negate = end < start
2296 if negate:
2297 start, end = end, start
2298 slc = self._get_sessions_slice(start, end, _parse=False)
2299 dist = slc.start - slc.stop if negate else slc.stop - slc.start
2300 return int(dist) # otherwise returned as `numpy.int64`
2301
2302 def sessions_minutes(
2303 self, start: Date, end: Date, _parse: bool = True
2304 ) -> pd.DatetimeIndex:
2305 """Return trading minutes over a sessions range.
2306
2307 Parameters
2308 ----------
2309 start
2310 Start of session range (range inclusive of `start`).
2311
2312 end
2313 End of session range (range inclusive of `end`).
2314
2315 Returns
2316 -------
2317 pd.DatetimeIndex
2318 Trading minutes for sessions in range.
2319 """
2320 start, end = self._parse_start_end_dates(start, end, _parse)
2321 start = self.date_to_session(start, "next", _parse=False)
2322 end = self.date_to_session(end, "previous", _parse=False)
2323 first_minute = self.session_first_minute(start)
2324 last_minute = self.session_last_minute(end)
2325 return self.minutes_in_range(first_minute, last_minute)
2326
2327 def sessions_minutes_count(
2328 self, start: Date, end: Date, _parse: bool = True
2329 ) -> int:
2330 """Return number of trading minutes in a range of sessions.
2331
2332 Parameters
2333 ----------
2334 start
2335 Start of session range (range inclusive of `start`).
2336
2337 end
2338 End of session range (range inclusive of `end`).
2339
2340 Returns
2341 -------
2342 int
2343 Total number of trading minutes in sessions range.
2344 """
2345 slc = self._get_sessions_slice(start, end, _parse)
2346 session_diff = self.last_minutes_nanos[slc] - self.first_minutes_nanos[slc]
2347 session_diff += NANOSECONDS_PER_MINUTE
2348 break_diff = self.first_pm_minutes_nanos[slc] - self.last_am_minutes_nanos[slc]
2349 break_diff[break_diff != 0] -= NANOSECONDS_PER_MINUTE
2350 nanos = session_diff - break_diff
2351 return (nanos // NANOSECONDS_PER_MINUTE).sum()
2352
2353 def trading_index( # noqa: C901
2354 self,
2355 start: Date | Minute,
2356 end: Date | Minute,
2357 period: pd.Timedelta | str,
2358 intervals: bool = True,
2359 closed: Literal["left", "right", "both", "neither"] = "left",
2360 force_close: bool = False,
2361 force_break_close: bool = False,
2362 force: bool | None = None,
2363 curtail_overlaps: bool = False,
2364 ignore_breaks: bool = False,
2365 align: pd.Timedelta | str = ONE_MINUTE,
2366 align_pm: pd.Timedelta | bool = True,
2367 parse: bool = True,
2368 ) -> pd.DatetimeIndex | pd.IntervalIndex:
2369 """Create a trading index.
2370
2371 Create a trading index of given `period` over a given range of
2372 dates.
2373
2374 NB. Which minutes the calendar treats as trading minutes, according
2375 to `self.side`, is irrelevant in the evaluation of the trading
2376 index.
2377
2378 NB. Execution time is related to the number of indices created. The
2379 longer the range of dates covered and/or the shorter the period
2380 (i.e. higher the frequency), the longer the execution. Whilst an
2381 index with 4000 indices might be created in a couple of
2382 miliseconds, a high frequency index with 2 million indices might
2383 take a second or two.
2384
2385 Parameters
2386 ----------
2387 start
2388 Timestamp representing start of index.
2389
2390 If `start` is passed as a date then the first indice will be:
2391 if `start` is a session, then the first indice of that
2392 session (i.e. the left side of the first indice will be
2393 the session open).
2394 otherwise, the first indice of the nearest session
2395 following `start`.
2396
2397 If `start` is passed as a minute then the first indice will be:
2398 if `start` coincides with (the left side of*) an indice,
2399 then that indice.
2400 otherwise the nearest indice to `start` (with a left side*)
2401 that is later than `start`.
2402 * if `intervals` is True (default)
2403
2404 `start` will be interpreted as a date if it is timezone-naive
2405 and does not have a time component (or any time component is
2406 00:00). Otherwise `start` will be interpreted as a time.
2407
2408 If `period` is one day ("1D") then `start` must be passed as
2409 a date. The first indice will be either `start`, if `start` is
2410 a session, or otherwise the nearest session following `start`.
2411
2412 end
2413 Timestamp representing end of index.
2414
2415 If `end` is passed as a date then the last indice will be:
2416 if `end` is a session, then the last indice of that
2417 session (i.e. either the right side of the final indice
2418 will be the session close or the final indice will
2419 contain the session close).
2420 otherwise, the last indice of the nearest session
2421 preceeding `end`.
2422
2423 If `end` is passed as a minute then the last indice will be:
2424 if `end` coincides with (the right side of*) an indice,
2425 then that indice.
2426 otherwise the nearest indice to `end` (with a right side*)
2427 that is earlier than `end`.
2428 * if `intervals` is True (default)
2429
2430 `end` will be interpreted as a date if it is timezone-naive
2431 and does not have a time component (or any time component is
2432 00:00). Otherwise `start` will be interpreted as a time.
2433
2434 If `period` is one day ("1d") then `end` must be passed as
2435 a date. The last indice will be either `end`, if `end` is
2436 a session, or otherwise the nearest session prceeding `end`.
2437
2438 period
2439 If `intervals` is True, the length of each interval. If
2440 `intervals` is False, the distance between indices. Period
2441 should be passed as a pd.Timedelta or a str that's acceptable
2442 as a single input to pd.Timedelta. `period` cannot be greater
2443 than 1 day.
2444
2445 Examples of valid `period` input:
2446 pd.Timedelta(minutes=15), pd.Timedelta(minutes=15, hours=2)
2447 '15min', '15T', '1H', '4h', '1D', '30s', '2s', '500ms'.
2448 Examples of invalid `period` input:
2449 '15minutes', '2D'.
2450
2451 intervals : default: True
2452 True to return trading index as a pd.IntervalIndex with indices
2453 representing explicit intervals.
2454
2455 False to return trading index as a pd.DatetimeIndex with
2456 indices that implicitely represent a period according to
2457 `closed`.
2458
2459 If `period` is '1D' then trading index will be returned as a
2460 pd.DatetimeIndex.
2461
2462 closed : {"left", "right", "both", "neither"}
2463 (ignored if `period` is '1D'.)
2464
2465 If `intervals` is True, the side that intervals should be
2466 closed on. Must be either "left" or "right" (any time during a
2467 session must belong to one interval and one interval only).
2468
2469 If `intervals` is False, the side of each period that an
2470 indice should be defined. The first and last indices of each
2471 (sub)session will be defined according to:
2472 "left" - include left side of first period, do not include
2473 right side of last period.
2474 "right" - do not include left side of first period, include
2475 right side of last period.
2476 "both" - include both left side of first period and right
2477 side of last period.
2478 "neither" - do not include either left side of first period
2479 or right side of last period.
2480 NB if `period` is not a factor of the (sub)session length then
2481 "right" or "both" will result in an indice being defined after
2482 the (sub)session close. See `force_close` and
2483 `force_break_close`.
2484
2485 force_close : default: False
2486 (ignored if `force` is passed.)
2487 (ignored if `period` is '1D')
2488 (irrelevant if `intervals` is False and `closed` is "left" or
2489 "neither")
2490
2491 Defines behaviour if right side of a session's last period
2492 falls after the session close.
2493
2494 If True, defines right side of this period as session close.
2495
2496 If False, defines right side of this period after the session
2497 close. In this case the represented period will include a
2498 non-trading period.
2499
2500 force_break_close : default: False
2501 (ignored if `force` is passed.)
2502 (ignored if `period` is '1D'.)
2503 (irrelevant if `intervals` is False and `closed` is "left" or
2504 "neither.)
2505
2506 Defines behaviour if right side of last pre-break period falls
2507 after the start of the break.
2508
2509 If True, defines right side of this period as break start.
2510
2511 If False, defines right side of this period after the break
2512 start. In this case the represented period will include a
2513 non-trading period.
2514
2515 force : optional
2516 (ignored if `period` is '1D'.)
2517 (irrelevant if `intervals` is False and `closed` is "left" or
2518 "neither.)
2519
2520 Convenience option to set both `force_close` and
2521 `force_break_close`. If passed then values passsed to
2522 `force_close` and `force_break_close` will be ignored.
2523
2524 curtail_overlaps : default: False
2525 (ignored if `period` is '1D')
2526 (irrelevant if (`intervals` is False) or (`force_close` and
2527 `force_break_close` are both True).)
2528
2529 Defines action to take if a period ends after the start of the
2530 next period. (This can occur if `period` is longer
2531 than a break or the gap between one session's close and the
2532 next session's open.)
2533
2534 If True, the right of the earlier of two overlapping
2535 periods will be curtailed to the left of the latter period.
2536 (NB consequently the period length will not be constant for
2537 all periods.)
2538
2539 If False, will raise IntervalsOverlapError.
2540
2541 ignore_breaks : default: False
2542 (ignored if `period` is '1D')
2543 (irrelevant if no session has a break)
2544
2545 Defines whether trading index should respect session breaks.
2546
2547 If False, treat sessions with breaks as comprising independent
2548 morning and afternoon subsessions.
2549
2550 If True, treat all sessions as continuous, ignoring any
2551 breaks.
2552
2553 parse : default: True
2554 Determines if `start` and `end` values are parsed. If these
2555 arguments are passed as tz-naive pd.Timestamp with no time
2556 component then can pass `parse` as False to save around
2557 500µs on the execution.
2558
2559 align : default: pd.Timedelta(1, "min")
2560 Anchor the first indice of each session such that it aligns
2561 with the nearest occurrence of a specific fraction of an hour.
2562
2563 Pass as a pd.Timedelta or a str that's acceptable as a single
2564 input to pd.Timedelta. Pass +ve values to shift indices
2565 forwards, -ve values to shift indices backwards.
2566
2567 Valid values are (or equivalent):
2568 "2min", "3min", "4min", "5min", "6min", "10min", "12min",
2569 "15min", "20min", "30min", "-2min", "-4min", "-5min",
2570 "-6min", "-10min", "-12min", "-15min", "-20min", "-30min"
2571
2572 For example, if `intervals` is True and `period` is '5T' then
2573 the first interval of a session with open time as 07:59 would
2574 be:
2575 07:59 - 08:04 if `align` is pd.Timedelta(1, "min") (default)
2576 08:00 - 08:05 if `align` is '5T'
2577 07:55 - 08:00 if `align` is '-5T'
2578
2579 Subsequent indices will be similarly shifted.
2580
2581 Note: A session's indices will not be shifted if the session
2582 open already aligns with `align`. For example, if the open time
2583 were 08:00 then the first interval will always have a left side
2584 as 08:00 regardless of `align`.
2585
2586 align_pm : default: True
2587 (ignored if `ignore_break` is True)
2588 (irrelevant if no session has a break)
2589
2590 Anchor the first indice of each afternoon subsession such that
2591 it aligns with the nearest occurrence of a specific fraction of
2592 an hour.
2593
2594 True: (default) Treat as `align`.
2595
2596 False: Do not shift post-break indices.
2597
2598 pd.Timedelta or str: Align post-break indices to the
2599 nearest occurence of this fraction of an hour. Valid values
2600 as for `align`.
2601
2602 Returns
2603 -------
2604 pd.IntervalIndex or pd.DatetimeIndex
2605 Trading index.
2606
2607 If `intervals` is False or `period` is '1D' then returned as a
2608 pd.DatetimeIndex.
2609 If `intervals` is True (default) returned as pd.IntervalIndex.
2610
2611 Raises
2612 ------
2613 exchange_calendars.errors.IntervalsOverlapError
2614 If `intervals` is True and right side of one or more indices
2615 would fall after the left of the subsequent indice. This can
2616 occur if `period` is longer than a break or the gap between one
2617 session's close and the next session's open.
2618
2619 exchange_calendars.errors.IntervalsOverlapError
2620 If `intervals` is False and an indice would otherwise fall to
2621 the right of the subsequent indice. This can occur if `period`
2622 is longer than a break or the gap between one session's close
2623 and the next session's open.
2624
2625 Credit to @Stryder-Git at pandas_market_calendars for showing the
2626 way with a vectorised solution to creating trading indices (a
2627 variation of which is employed within the underlying _TradingIndex
2628 class).
2629 """
2630 if not isinstance(period, pd.Timedelta):
2631 try:
2632 period = pd.Timedelta(period)
2633 except ValueError:
2634 msg = (
2635 f"`period` receieved as '{period}' although takes type"
2636 " 'pd.Timedelta' or a 'str' that is valid as a single input"
2637 " to 'pd.Timedelta'. Examples of valid input: pd.Timestamp('15T'),"
2638 " '15min', '15T', '1H', '4h', '1D', '5s', 500ms'."
2639 )
2640 raise ValueError(msg) from None
2641
2642 if period > pd.Timedelta(1, "D"):
2643 msg = (
2644 "`period` cannot be greater than one day although received as"
2645 f" '{period}'."
2646 )
2647 raise ValueError(msg)
2648
2649 if period == pd.Timedelta(1, "D"):
2650 start, end = self._parse_start_end_dates(start, end, parse)
2651 return self.sessions_in_range(start, end)
2652
2653 if intervals and closed in ["both", "neither"]:
2654 raise ValueError(
2655 f"If `intervals` is True then `closed` cannot be '{closed}'."
2656 )
2657
2658 def get_align(name: Literal["align", "align_pm"], value: Any) -> pd.Timedelta:
2659 """Convert value received for an align parameter to Timestamp.
2660
2661 Raises `ValueError` if value is invalid or not of a valid type.
2662
2663 Parameters
2664 ----------
2665 name
2666 Parameter name.
2667
2668 value
2669 Value assigned to parameter.
2670 """
2671 try:
2672 value = pd.Timedelta(value)
2673 except ValueError:
2674 insert = " bool," if name == "align_pm" else ""
2675 msg = (
2676 f"`{name}` receieved as '{value}' although takes type{insert}"
2677 f" 'pd.Timedelta' or a 'str' that is valid as a single input"
2678 " to 'pd.Timedelta'. Examples of valid input: pd.Timestamp('5T'),"
2679 " '5min', '5T', pd.Timedelta('-5T'), '-5min', '-5T'."
2680 )
2681 raise ValueError(msg) from None
2682
2683 if value > ONE_HOUR or value < -ONE_HOUR or not value or (ONE_HOUR % value):
2684 raise ValueError(
2685 f"`{name}` must be factor of 1H although received '{value}'."
2686 )
2687
2688 if value % pd.Timedelta(1, "min"):
2689 raise ValueError(
2690 f"`{name}` cannot include a fraction of a minute although received"
2691 f" '{value}'."
2692 )
2693 return value
2694
2695 align = get_align("align", align)
2696
2697 if align_pm is False:
2698 align_pm = pd.Timedelta(1, "min")
2699 else:
2700 align_pm = align if align_pm is True else get_align("align_pm", align_pm)
2701
2702 if force is not None:
2703 force_close = force_break_close = force
2704
2705 # method exposes public methods of _TradingIndex.
2706 _trading_index = _TradingIndex(
2707 self,
2708 start,
2709 end,
2710 period,
2711 closed,
2712 force_close,
2713 force_break_close,
2714 curtail_overlaps,
2715 ignore_breaks,
2716 align,
2717 align_pm,
2718 )
2719
2720 if not intervals:
2721 return _trading_index.trading_index()
2722 return _trading_index.trading_index_intervals()
2723
2724 # Internal methods called by constructor.
2725
2726 def _special_dates(
2727 self,
2728 regular_dates: list[tuple[datetime.time, HolidayCalendar | int]],
2729 ad_hoc_dates: list[tuple[datetime.time, pd.DatetimeIndex]],
2730 start_date: pd.Timestamp,
2731 end_date: pd.Timestamp,
2732 ) -> pd.Series:
2733 """Evaluate times associated with special dates.
2734
2735 Parameters
2736 ----------
2737 regular_dates
2738 Regular non-standard times and corresponding HolidayCalendars
2739 or Int day-of-week.
2740
2741 ad_hoc_dates
2742 Adhoc non-standard times and corresponding sessions.
2743
2744 start_date
2745 Start of the range over which to evaluate special dates. Must
2746 be timezone naive.
2747
2748 end_date
2749 End of the range over which to evaluate special dates. Must be
2750 timezone naive.
2751
2752 Returns
2753 -------
2754 special_dates: pd.Series
2755 Series mapping trading sessions with special times.
2756
2757 Index is timezone naive.
2758 dtype is datetime64[ns, UTC].
2759 """
2760 # List of Series for regularly-scheduled times.
2761 regular = [
2762 scheduled_special_times(
2763 holiday_calendar,
2764 start_date,
2765 end_date,
2766 time_,
2767 self.tz,
2768 )
2769 for time_, holiday_calendar in regular_dates
2770 ]
2771
2772 # List of Series for ad-hoc times.
2773 ad_hoc = []
2774 for time_, dti in ad_hoc_dates:
2775 dti = dti[(dti >= start_date) & (dti <= end_date)] # noqa: PLW2901
2776 srs = pd.Series(index=dti, data=days_at_time(dti, time_, self.tz, 0))
2777 ad_hoc.append(srs)
2778
2779 merged = ad_hoc + regular
2780 if not merged:
2781 # Concat barfs if the input has length 0.
2782 return pd.Series(
2783 [], index=pd.DatetimeIndex([]), dtype="datetime64[ns, UTC]"
2784 )
2785
2786 result = pd.concat(merged)
2787 # where there are multiple occurrences of the same date, keep only the first
2788 result = result[~result.index.duplicated(keep="first")]
2789 result = result.sort_index()
2790 # exclude any special date that coincides with a holiday
2791 adhoc_holidays = pd.DatetimeIndex(self.adhoc_holidays)
2792 result = result[~result.index.isin(adhoc_holidays)]
2793 regular_holidays = self.regular_holidays
2794 if regular_holidays is not None:
2795 reg_holidays = regular_holidays.holidays(start_date, end_date)
2796 if not reg_holidays.empty:
2797 result = result[~result.index.isin(reg_holidays)]
2798 return result
2799
2800 def _calculate_special_opens(
2801 self, start: pd.Timestamp, end: pd.Timestamp
2802 ) -> pd.Series:
2803 return self._special_dates(
2804 self.special_opens,
2805 self.special_opens_adhoc,
2806 start,
2807 end,
2808 )
2809
2810 def _calculate_special_closes(
2811 self, start: pd.Timestamp, end: pd.Timestamp
2812 ) -> pd.Series:
2813 return self._special_dates(
2814 self.special_closes,
2815 self.special_closes_adhoc,
2816 start,
2817 end,
2818 )
2819
2820
2821 def _check_breaks_match(break_starts_nanos: np.ndarray, break_ends_nanos: np.ndarray):
2822 """Checks that break_starts_nanos and break_ends_nanos match."""
2823 nats_match = np.equal(break_starts_nanos == NP_NAT, break_ends_nanos == NP_NAT)
2824 if not nats_match.all():
2825 raise ValueError(
2826 f"""
2827 Mismatched market breaks
2828 Break starts:
2829 {break_starts_nanos[~nats_match]}
2830 Break ends:
2831 {break_ends_nanos[~nats_match]}
2832 """
2833 )
2834
2835
2836 def scheduled_special_times(
2837 special_days: HolidayCalendar | int,
2838 start: pd.Timestamp,
2839 end: pd.Timestamp,
2840 time: datetime.time,
2841 tz: ZoneInfo,
2842 ) -> pd.Series:
2843 """Return map of dates to special times.
2844
2845 Parameters
2846 ----------
2847 special_days
2848 Describes dates with a special time. Pass as either:
2849 HolidayCalendar : calendar with rules describing the dates on
2850 which special times apply
2851
2852 int : integer describing a weekday with a regular special
2853 time (0 - Monday, ..., 6 - Sunday).
2854
2855 start
2856 Date from which to evaluate mapping (inclusive of `start`).
2857
2858 end
2859 Date to which to evaluate mapping (inclusive of `end`).
2860
2861 time
2862 Special time for dates described by `special_days`.
2863
2864 tz
2865 The timezone in which to interpret `time`.
2866
2867 Returns
2868 -------
2869 pd.Series
2870 Series mapping dates to special times.
2871
2872 Index is timezone naive.
2873 dtype is datetime64[ns, UTC].
2874 """
2875 if isinstance(special_days, int):
2876 day_str = "W-" + day_name[special_days].upper()[0:3]
2877 days = pd.date_range(start, end, freq=day_str)
2878 else:
2879 days = special_days.holidays(start, end)
2880 if not isinstance(days, pd.DatetimeIndex):
2881 # days will be pd.Index if empty
2882 days = pd.DatetimeIndex(days)
2883 return pd.Series(
2884 index=days,
2885 data=days_at_time(days, time, tz=tz, day_offset=0),
2886 )
2887
2888
2889 def _adjust_special_dates(
2890 session_labels: pd.DatetimeIndex,
2891 standard_times: pd.DatetimeIndex,
2892 special_times: pd.Series,
2893 ) -> pd.DatetimeIndex:
2894 """Adjust standard times of a session bound with special times.
2895
2896 `session_labels` required for alignment.
2897 """
2898 # Short circuit when nothing to apply.
2899 if special_times.empty:
2900 return standard_times
2901
2902 len_m, len_oc = len(session_labels), len(standard_times)
2903 if len_m != len_oc:
2904 raise ValueError(
2905 "Found misaligned dates while building calendar.\nExpected"
2906 " session_labels to be the same length as open_or_closes but,\n"
2907 f"len(session_labels)={len_m}, len(open_or_closes)={len_oc}"
2908 )
2909
2910 # Find the array indices corresponding to each special date.
2911 indexer = session_labels.get_indexer(special_times.index)
2912
2913 # -1 indicates that no corresponding entry was found. If any -1s are
2914 # present, then we have special dates that doesn't correspond to any
2915 # trading day.
2916 if -1 in indexer:
2917 bad_dates = list(special_times[indexer == -1])
2918 raise ValueError(f"Special dates {bad_dates} are not sessions.")
2919
2920 srs = standard_times.to_series()
2921 srs.iloc[indexer] = special_times
2922 return pd.DatetimeIndex(srs)
2923
2924
2925 def _remove_breaks_for_special_dates(
2926 session_labels: pd.DatetimeIndex,
2927 standard_break_times: pd.DatetimeIndex | None,
2928 special_times: pd.Series,
2929 ) -> pd.DatetimeIndex | None:
2930 """Remove standard break times for sessions with special times."
2931
2932 Replaces standard break times with NaT for sessions with speical
2933 times. Anticipated that `special_times` will be special times for
2934 'opens' or 'closes'.
2935
2936 `session_labels` required for alignment.
2937 """
2938 # Short circuit when we have no breaks
2939 if standard_break_times is None:
2940 return None
2941
2942 # Short circuit when nothing to apply.
2943 if special_times.empty:
2944 return standard_break_times
2945
2946 len_m, len_oc = len(session_labels), len(standard_break_times)
2947 if len_m != len_oc:
2948 raise ValueError(
2949 "Found misaligned dates while building calendar.\n"
2950 "Expected session_labels to be the same length as break_starts,\n"
2951 f"but len(session_labels)={len_m}, len(break_start_or_end)={len_oc}"
2952 )
2953
2954 # Find the array indices corresponding to each special date.
2955 indexer = session_labels.get_indexer(special_times.index)
2956
2957 # -1 indicates that no corresponding entry was found. If any -1s are
2958 # present, then we have special dates that doesn't correspond to any
2959 # trading day.
2960 if -1 in indexer:
2961 bad_dates = list(special_times[indexer == -1])
2962 raise ValueError(f"Special dates {bad_dates} are not trading days.")
2963
2964 srs = standard_break_times.to_series()
2965 srs.iloc[indexer] = np.nan
2966 return pd.DatetimeIndex(srs)