forked from gerrymanoim/exchange_calendars
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exchange_calendar.py
3037 lines (2533 loc) · 105 KB
/
exchange_calendar.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from abc import ABC, abstractmethod
from calendar import day_name
import collections
from collections.abc import Sequence, Callable
import datetime
import functools
import operator
from typing import TYPE_CHECKING, Literal, Any
import warnings
import numpy as np
import pandas as pd
import toolz
from pandas.tseries.holiday import AbstractHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
import pytz
from pytz import UTC
from exchange_calendars import errors
from .calendar_helpers import (
NANOSECONDS_PER_MINUTE,
NP_NAT,
Date,
Minute,
Session,
TradingMinute,
_TradingIndex,
compute_minutes,
next_divider_idx,
one_minute_earlier,
one_minute_later,
parse_date,
parse_session,
parse_timestamp,
parse_trading_minute,
previous_divider_idx,
)
from .utils.pandas_utils import days_at_time
if TYPE_CHECKING:
from pandas._libs.tslibs.nattype import NaTType
GLOBAL_DEFAULT_START = pd.Timestamp.now().floor("D") - pd.DateOffset(years=20)
# Give an aggressive buffer for logic that needs to use the next trading
# day or minute.
GLOBAL_DEFAULT_END = pd.Timestamp.now().floor("D") + pd.DateOffset(years=1)
NANOS_IN_MINUTE = 60000000000
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = range(7)
WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY)
WEEKENDS = (SATURDAY, SUNDAY)
def selection(
arr: pd.DatetimeIndex, start: pd.Timestamp, end: pd.Timestamp
) -> pd.DatetimeIndex:
predicates = []
if start is not None:
predicates.append(start <= arr)
if end is not None:
predicates.append(arr < end)
if not predicates:
return arr
return arr[np.all(predicates, axis=0)]
def _group_times(
sessions: pd.DatetimeIndex,
times: None | Sequence[tuple[pd.Timestamp | None, datetime.time]],
tz: pytz.tzinfo.BaseTzInfo,
offset: int = 0,
) -> pd.DatetimeIndex | None:
"""Evaluate standard times for a specific session bound.
For example, if `times` passed as standard times for session opens then
will return a DatetimeIndex describing standard open times for each
session.
"""
if times is None:
return None
elements = [
days_at_time(selection(sessions, start, end), time, tz, offset)
for (start, time), (end, _) in toolz.sliding_window(
2, toolz.concatv(times, [(None, None)])
)
]
return elements[0].append(elements[1:])
class deprecate:
"""Decorator for deprecated ExchangeCalendar methods."""
def __init__(
self,
deprecated_release: str = "4.0",
message: str | None = None,
):
self.deprecated_release = "release " + deprecated_release
self.message = message
def __call__(self, f: Callable) -> Callable:
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
warnings.warn(self._message(f), FutureWarning)
return f(*args, **kwargs)
return wrapped_f
def _message(self, f: Callable) -> str:
msg = (
f"`{f.__name__}` was deprecated in {self.deprecated_release}"
f" and will be removed in a future release."
)
if self.message is not None:
msg += " " + self.message
return msg
class HolidayCalendar(AbstractHolidayCalendar):
def __init__(self, rules):
super().__init__(rules=rules)
class ExchangeCalendar(ABC):
"""Representation of timing information of a single market exchange.
The timing information comprises sessions, open/close times and, for
exchanges that observe an intraday break, break_start/break_end times.
For exchanges that do not observe an intraday break a session
represents a contiguous set of minutes. Where an exchange observes
an intraday break a session represents two contiguous sets of minutes
separated by the intraday break.
Each session is labeled as the date that the session represents.
For each session, we store the open and close time together with, for
those exchanges with breaks, the break start and break end. All times
are defined as UTC.
Note that a session may start on the day prior to the session label or
end on the day following the session label. Such behaviour is common
for calendars that represent futures exchanges.
Parameters
----------
start : default: later of 20 years ago or first supported start date.
First calendar session will be `start`, if `start` is a session, or
first session after `start`. Cannot be earlier than any date
returned by class method `bound_min`.
end : default: earliest of 1 year from 'today' or last supported end
date. Last calendar session will be `end`, if `end` is a session,
or last session before `end`. Cannot be later than any date
returned by class method `bound_max`.
side : default: "left"
Define which of session open/close and break start/end should
be treated as a trading minute:
"left" - treat session open and break_start as trading minutes,
do not treat session close or break_end as trading minutes.
"right" - treat session close and break_end as trading minutes,
do not treat session open or break_start as tradng minutes.
"both" - treat all of session open, session close, break_start
and break_end as trading minutes.
"neither" - treat none of session open, session close,
break_start or break_end as trading minutes.
Raises
------
ValueError
If `start` is earlier than the earliest supported start date.
If `end` is later than the latest supported end date.
If `start` parses to a later date than `end`.
Notes
-----
Exchange calendars were originally defined for the Zipline package from
Quantopian under the package 'trading_calendars'. Since 2021 they have
been maintained under the 'exchange_calendars' package (a fork of
'trading_calendars') by an active community of contributing users.
Some calendars have defined start and end bounds within which
contributors have endeavoured to ensure the calendar's accuracy and
outside of which the calendar would not be accurate. These bounds
are enforced such that passing `start` or `end` as dates that are
out-of-bounds will raise a ValueError. The bounds of each calendar are
exposed via the `bound_min` and `bound_max` class methods.
Many calendars do not have bounds defined (in these cases `bound_min`
and/or `bound_max` return None). These calendars can be created through
any date range although it should be noted that the earlier the start
date, the greater the potential for inaccuracies.
In all cases, no guarantees are offered as to the accuracy of any
calendar.
-- Internal method parameters --
_parse: bool
Determines if a `minute` or `session` parameter should be
parsed (default True). Passed as False:
- internally to prevent double parsing.
- by tests for efficiency.
"""
_LEFT_SIDES = ["left", "both"]
_RIGHT_SIDES = ["right", "both"]
@classmethod
def bound_min(cls) -> pd.Timestamp | None:
"""Earliest date from which calendar can be constructed.
Returns
-------
pd.Timestamp or None
Earliest date from which calendar can be constructed. Must be
timezone naive. None if no limit.
Notes
-----
To impose a constraint on the earliest date from which a calendar
can be constructed subclass should override this method and
optionally override `_bound_min_error_msg`.
"""
return None
@classmethod
def bound_max(cls) -> pd.Timestamp | None:
"""Latest date to which calendar can be constructed.
Returns
-------
pd.Timestamp or None
Latest date to which calendar can be constructed. Must be
timezone naive. None if no limit.
Notes
-----
To impose a constraint on the latest date to which a calendar can
be constructed subclass should override this method and optionally
override `_bound_max_error_msg`.
"""
return None
@classmethod
def default_start(cls) -> pd.Timestamp:
"""Return default calendar start date.
Calendar will start from this date if 'start' is not otherwise
passed to the constructor.
"""
bound_min = cls.bound_min()
if bound_min is None:
return GLOBAL_DEFAULT_START
else:
return max(GLOBAL_DEFAULT_START, bound_min)
@classmethod
def default_end(cls) -> pd.Timestamp:
"""Return default calendar end date.
Calendar will end at this date if 'end' is not otherwise passed to
the constructor.
"""
bound_max = cls.bound_max()
if bound_max is None:
return GLOBAL_DEFAULT_END
else:
return min(GLOBAL_DEFAULT_END, bound_max)
def __init__(
self,
start: Date | None = None,
end: Date | None = None,
side: Literal["left", "right", "both", "neither"] = "left",
):
if side not in self.valid_sides():
raise ValueError(
f"`side` must be in {self.valid_sides()} although received as {side}."
)
self._side = side
if start is None:
start = self.default_start()
else:
start = parse_date(start, "start", raise_oob=False)
bound_min = self.bound_min()
if bound_min is not None and start < bound_min:
raise ValueError(self._bound_min_error_msg(start))
if end is None:
end = self.default_end()
else:
end = parse_date(end, "end", raise_oob=False)
bound_max = self.bound_max()
if bound_max is not None and end > bound_max:
raise ValueError(self._bound_max_error_msg(end))
if start >= end:
raise ValueError(
"`start` must be earlier than `end` although `start` parsed as"
f" '{start}' and `end` as '{end}'."
)
_all_days = pd.date_range(start, end, freq=self.day) # session labels
if _all_days.empty:
raise errors.NoSessionsError(calendar_name=self.name, start=start, end=end)
# DatetimeIndex of standard times for each day.
self._opens = _group_times(
_all_days,
self.open_times,
self.tz,
self.open_offset,
)
self._break_starts = _group_times(
_all_days,
self.break_start_times,
self.tz,
)
self._break_ends = _group_times(
_all_days,
self.break_end_times,
self.tz,
)
self._closes = _group_times(
_all_days,
self.close_times,
self.tz,
self.close_offset,
)
# Apply any special offsets first
self.apply_special_offsets(_all_days, start, end)
# Series mapping sessions with non-standard opens/closes.
_special_opens = self._calculate_special_opens(start, end)
_special_closes = self._calculate_special_closes(start, end)
# Overwrite the special opens and closes on top of the standard ones.
_overwrite_special_dates(_all_days, self._opens, _special_opens)
_overwrite_special_dates(_all_days, self._closes, _special_closes)
_remove_breaks_for_special_dates(_all_days, self._break_starts, _special_closes)
_remove_breaks_for_special_dates(_all_days, self._break_ends, _special_closes)
break_starts = None if self._break_starts is None else self._break_starts
break_ends = None if self._break_ends is None else self._break_ends
self.schedule = pd.DataFrame(
index=_all_days,
data=collections.OrderedDict(
[
("open", self._opens),
("break_start", break_starts),
("break_end", break_ends),
("close", self._closes),
]
),
dtype="datetime64[ns, UTC]",
)
self.opens_nanos = self.schedule.open.values.astype(np.int64)
self.break_starts_nanos = self.schedule.break_start.values.astype(np.int64)
self.break_ends_nanos = self.schedule.break_end.values.astype(np.int64)
self.closes_nanos = self.schedule.close.values.astype(np.int64)
_check_breaks_match(self.break_starts_nanos, self.break_ends_nanos)
self._late_opens = _special_opens.index
self._early_closes = _special_closes.index
# --------------- Calendar definition methods/properties --------------
# Methods and properties in this section should be overriden or
# extended by subclass if and as required.
@property
@abstractmethod
def name(self) -> str:
"""Calendar name."""
raise NotImplementedError()
def _bound_min_error_msg(self, start: pd.Timestamp) -> str:
"""Return error message to handle `start` being out-of-bounds.
See Also
--------
bound_min
"""
return (
f"The earliest date from which calendar {self.name} can be"
f" evaluated is {self.bound_min()}, although received `start` as"
f" {start}."
)
def _bound_max_error_msg(self, end: pd.Timestamp) -> str:
"""Return error message to handle `end` being out-of-bounds.
See Also
--------
bound_max
"""
return (
f"The latest date to which calendar {self.name} can be evaluated"
f" is {self.bound_max()}, although received `end` as {end}."
)
@property
@abstractmethod
def tz(self) -> pytz.tzinfo.BaseTzInfo:
"""Calendar timezone."""
raise NotImplementedError()
@property
@abstractmethod
def open_times(self) -> Sequence[tuple[pd.Timestamp | None, datetime.time]]:
"""Local open time(s).
Returns
-------
Sequence[tuple[pd.Timestamp | None, datetime.time]]:
Sequence of tuples representing (start_date, open_time) where:
start_date: date from which `open_time` applies. Must be
timezone-naive. None for first item.
open_time: exchange's local open time.
Notes
-----
Examples for concreting `open_times` on a subclass.
Example where open time is constant throughout period covered by
calendar:
open_times = ((None, datetime.time(9)),)
Example where open times have varied over period covered by
calendar:
open_times = (
(None, time(9, 30)),
(pd.Timestamp("1978-04-01"), datetime.time(10, 0)),
(pd.Timestamp("1986-04-01"), datetime.time(9, 40)),
(pd.Timestamp("1995-01-01"), datetime.time(9, 30)),
(pd.Timestamp("1998-12-07"), datetime.time(9, 0)),
)
"""
raise NotImplementedError()
@property
def break_start_times(
self,
) -> None | Sequence[tuple[pd.Timestamp | None, datetime.time]]:
"""Local break start time(s).
As `close_times` although times represent the close of the morning
subsession. None if exchange does not observe a break.
"""
return None
@property
def break_end_times(
self,
) -> None | Sequence[tuple[pd.Timestamp | None, datetime.time]]:
"""Local break end time(s).
As `open_times` although times represent the open of the afternoon
subsession. None if exchange does not observe a break.
"""
return None
@property
@abstractmethod
def close_times(self) -> Sequence[tuple[pd.Timestamp | None, datetime.time]]:
"""Local close time(s).
Returns
-------
Sequence[tuple[pd.Timestamp | None, datetime.time]]:
Sequence of tuples representing (start_date, close_time) where:
start_date: date from which `close_time` applies. Must be
timezone naive. None for first item.
close_time: exchange's local close time.
Notes
-----
Examples for concreting `close_times` on a subclass.
Example where close time is constant throughout period covered by
calendar:
close_times = ((None, time(17, 30)),)
Example where close times have varied over period covered by
calendar:
close_times = (
(None, datetime.time(17, 30)),
(pd.Timestamp("1986-04-01"), datetime.time(17, 20)),
(pd.Timestamp("1995-01-01"), datetime.time(17, 0)),
(pd.Timestamp("2016-08-01"), datetime.time(17, 30)),
)
"""
raise NotImplementedError()
@property
def weekmask(self) -> str:
"""Indicator of weekdays on which the exchange is open.
Default is '1111100' (i.e. Monday-Friday).
See Also
--------
numpy.busdaycalendar
"""
return "1111100"
@property
def open_offset(self) -> int:
"""Day offset of open time(s) relative to session.
Returns
-------
int
0 if the date components of local open times are as the
corresponding session labels.
-1 if the date components of local open times are the day
before the corresponding session labels.
"""
return 0
@property
def close_offset(self) -> int:
"""Day offset of close time(s) relative to session.
Returns
-------
int
0 if the date components of local close times are as the
corresponding session labels.
1 if the date components of local close times are the day
after the corresponding session labels.
"""
return 0
@property
def regular_holidays(self) -> HolidayCalendar | None:
"""Holiday calendar representing calendar's regular holidays."""
return None
@property
def adhoc_holidays(self) -> list[pd.Timestamp]:
"""List of non-regular holidays.
Returns
-------
list[pd.Timestamp]
List of tz-naive timestamps representing non-regular holidays.
"""
return []
@property
def special_opens(self) -> list[tuple[datetime.time, HolidayCalendar] | int]:
"""Regular non-standard open times.
Example of what would be defined as a special open:
"EVERY YEAR on national lie-in day the exchange opens
at 13:00 rather than the standard 09:00".
"Every Monday the exchange opens late, at 10:30 rather than
the standard 09:00".
Returns
-------
list[tuple[datetime.time, HolidayCalendar | int]]:
list of tuples each describing a regular non-standard open:
[0] datetime.time: regular non-standard open time.
[1] Describes dates with regular non-standard open time
as [0]. As either:
HolidayCalendar: defines annual dates by rules.
int : integer defines a weekday with a regular
non-standard open (0 - Monday, ..., 6 - Sunday).
The same date may be described by more than one tuple, for
example, if a late open on an annual holiday coincides with
a weekday late open. In this case the time assigned to the
date will be that defined by the tuple with the lowest index
in the returned list.
"""
return []
@property
def special_opens_adhoc(
self,
) -> list[tuple[datetime.time, pd.DatetimeIndex]]:
"""Adhoc non-standard open times.
Defines non-standard open times that cannot be otherwise codified
within within `special_opens`.
Example of an event to define as an adhoc special open:
"On 2022-02-14 due to a typhoon the exchange opened at 13:00,
rather than the standard 09:00".
Returns
-------
list[tuple[datetime.time, pd.DatetimeIndex]]:
List of tuples each describing an adhoc non-standard open time:
[0] datetime.time: non-standard open time.
[1] pd.DatetimeIndex: date or dates corresponding with the
non-standard open time. (Must be timezone-naive.)
"""
return []
@property
def special_closes(self) -> list[tuple[datetime.time, HolidayCalendar | int]]:
"""Regular non-standard close times.
Examples of what would be defined as a special close:
"On christmas eve the exchange closes at 14:00 rather than
the standard 17:00".
"Every Friday the exchange closes early, at 14:00 rather than
the standard 17:00".
Returns
-------
list[tuple[datetime.time, HolidayCalendar | int]]:
list of tuples each describing a regular non-standard close:
[0] datetime.time: regular non-standard close time.
[1] Describes dates with regular non-standard close time
as [0]. As either:
HolidayCalendar: defines annual dates by rules.
int : integer defines a weekday with a regular
non-standard close (0 - Monday, ..., 6 - Sunday).
The same date may be described by more than one tuple, for
example, if an early close on an annual holiday coincides with
a weekday early close. In this case the time assigned to the
date will be that defined by the tuple with the lowest index
in the returned list.
"""
return []
@property
def special_closes_adhoc(
self,
) -> list[tuple[datetime.time, pd.DatetimeIndex]]:
"""Adhoc non-standard close times.
Defines non-standard close times that cannot be otherwise codified
within within `special_closes`.
Example of an event to define as an adhoc special close:
"On 2022-02-19 due to a typhoon the exchange closed at 12:00,
rather than the standard 16:00".
Returns
-------
list[tuple[datetime.time, pd.DatetimeIndex]]:
List of tuples each describing an adhoc non-standard close
time:
[0] datetime.time: non-standard close time.
[1] pd.DatetimeIndex: date or dates corresponding with the
non-standard close time. (Must be timezone-naive.)
"""
return []
def apply_special_offsets(
self, sessions: pd.DatetimeIndex, start: pd.Timestamp, end: pd.Timestamp
) -> None:
"""Hook for subclass to apply changes.
Method executed by constructor prior to overwritting special dates.
Parameters
----------
sessions
All calendar sessions.
start
Date from which special offsets to be applied.
end
Date through which special offsets to be applied.
Notes
-----
Incorporated to provide hook to `exchange_calendar_xkrx`.
"""
return None
# ------------------------------------------------------------------
# -- NO method below this line should be overriden on a subclass! --
# ------------------------------------------------------------------
# Methods and properties that define calendar (continued...).
@functools.cached_property
def day(self) -> CustomBusinessDay:
"""CustomBusinessDay instance representing calendar sessions."""
return CustomBusinessDay(
holidays=self.adhoc_holidays,
calendar=self.regular_holidays,
weekmask=self.weekmask,
)
@classmethod
def valid_sides(cls) -> list[str]:
"""List of valid `side` options."""
if cls.close_times == cls.open_times:
return ["left", "right"]
else:
return ["both", "left", "right", "neither"]
@property
def side(self) -> Literal["left", "right", "both", "neither"]:
"""Side on which sessions are closed.
Returns
-------
str
"left" - Session open and break_start are trading minutes.
Session close and break_end are not trading minutes.
"right" - Session close and break_end are trading minutes,
Session open and break_start are not tradng minutes.
"both" - Session open, session close, break_start and
break_end are all trading minutes.
"neither" - Session open, session close, break_start and
break_end are all not trading minutes.
Notes
-----
Subclasses should NOT override this method.
"""
return self._side
# Properties covering all sessions.
@property
def sessions(self) -> pd.DatetimeIndex:
"""All calendar sessions."""
return self.schedule.index
@functools.cached_property
def sessions_nanos(self) -> np.ndarray:
"""All calendar sessions as nano seconds."""
return self.sessions.values.astype("int64")
@property
def opens(self) -> pd.Series:
"""Open time of each session.
Returns
-------
pd.Series
index : pd.DatetimeIndex
All sessions.
dtype : datetime64[ns, UTC]
UTC open time of corresponding session.
"""
return self.schedule.open
@property
def closes(self) -> pd.Series:
"""Close time of each session.
Returns
-------
pd.Series
index : pd.DatetimeIndex
All sessions.
dtype : datetime64[ns, UTC]
UTC close time of corresponding session.
"""
return self.schedule.close
@property
def break_starts(self) -> pd.Series:
"""Break start time of each session.
Returns
-------
pd.Series
index : pd.DatetimeIndex
All sessions.
dtype : datetime64[ns, UTC]
UTC break-start time of corresponding session. Value is
missing (pd.NaT) for any session that does not have a
break.
"""
return self.schedule.break_start
@property
def break_ends(self) -> pd.Series:
"""Break end time of each session.
Returns
-------
pd.Series
index : pd.DatetimeIndex
All sessions.
dtype : datetime64[ns, UTC]
UTC break-end time of corresponding session.Value is
missing (pd.NaT) for any session that does not have a
break.
"""
return self.schedule.break_end
@functools.cached_property
def first_minutes_nanos(self) -> np.ndarray:
"""Each session's first minute as an integer."""
if self.side in self._LEFT_SIDES:
return self.opens_nanos
else:
return one_minute_later(self.opens_nanos)
@functools.cached_property
def last_minutes_nanos(self) -> np.ndarray:
"""Each session's last minute as an integer."""
if self.side in self._RIGHT_SIDES:
return self.closes_nanos
else:
return one_minute_earlier(self.closes_nanos)
@functools.cached_property
def last_am_minutes_nanos(self) -> np.ndarray:
"""Each morning subsessions's last minute as an integer."""
if self.side in self._RIGHT_SIDES:
return self.break_starts_nanos
else:
return one_minute_earlier(self.break_starts_nanos)
@functools.cached_property
def first_pm_minutes_nanos(self) -> np.ndarray:
"""Each afternoon subsessions's first minute as an integer."""
if self.side in self._LEFT_SIDES:
return self.break_ends_nanos
else:
return one_minute_later(self.break_ends_nanos)
def _minutes_as_series(self, nanos: np.ndarray, name: str) -> pd.Series:
"""Convert trading minute nanos to pd.Series."""
ser = pd.Series(pd.DatetimeIndex(nanos, tz=UTC), index=self.sessions)
ser.name = name
return ser
@property
def first_minutes(self) -> pd.Series:
"""First trading minute of each session."""
return self._minutes_as_series(self.first_minutes_nanos, "first_minutes")
@property
def last_minutes(self) -> pd.Series:
"""Last trading minute of each session."""
return self._minutes_as_series(self.last_minutes_nanos, "last_minutes")
@property
def last_am_minutes(self) -> pd.Series:
"""Last am trading minute of each session."""
return self._minutes_as_series(self.last_am_minutes_nanos, "last_am_minutes")
@property
def first_pm_minutes(self) -> pd.Series:
"""First pm trading minute of each session."""
return self._minutes_as_series(self.first_pm_minutes_nanos, "first_pm_minutes")
# Properties covering all minutes.
def _minutes(
self, side: Literal["left", "right", "both", "neither"]
) -> pd.DatetimeIndex:
return pd.DatetimeIndex(
compute_minutes(
self.opens_nanos,
self.break_starts_nanos,
self.break_ends_nanos,
self.closes_nanos,
side,
),
tz=UTC,
)
@functools.cached_property
def minutes(self) -> pd.DatetimeIndex:
"""All trading minutes."""
return self._minutes(self.side)
@functools.cached_property
def minutes_nanos(self) -> np.ndarray:
"""All trading minutes as nanoseconds."""
return self.minutes.values.astype(np.int64)
# Calendar properties.
@property
def first_session(self) -> pd.Timestamp:
"""First calendar session."""
return self.sessions[0]
@property
def last_session(self) -> pd.Timestamp:
"""Last calendar session."""
return self.sessions[-1]
@property
def first_session_open(self) -> pd.Timestamp:
"""Open time of calendar's first session."""
return self.opens[0]
@property
def last_session_close(self) -> pd.Timestamp:
"""Close time of calendar's last session."""
return self.closes[-1]
@property
def first_minute(self) -> pd.Timestamp:
"""Calendar's first trading minute."""
return pd.Timestamp(self.minutes_nanos[0], tz=UTC)
@property
def last_minute(self) -> pd.Timestamp:
"""Calendar's last trading minute."""
return pd.Timestamp(self.minutes_nanos[-1], tz=UTC)
@property
def has_break(self) -> bool:
"""Query if any calendar session has a break."""
return self.sessions_has_break(
self.first_session, self.last_session, _parse=False
)
@property
def late_opens(self) -> pd.DatetimeIndex:
"""Sessions that open later than the prevailing normal open.
NB. Prevailing normal open as defined by `open_times`.
"""
return self._late_opens
@property
def early_closes(self) -> pd.DatetimeIndex:
"""Sessions that close earlier than the prevailing normal close.
NB. Prevailing normal close as defined by `close_times`.
"""
return self._early_closes
# Methods that interrogate a given session.
def _get_session_idx(self, session: Date, _parse=True) -> int:
"""Index position of a session."""
session_ = parse_session(self, session) if _parse else session
if TYPE_CHECKING:
assert isinstance(session_, pd.Timestamp)
return self.sessions_nanos.searchsorted(session_.value, side="left")
def session_open(self, session: Session, _parse: bool = True) -> pd.Timestamp:
"""Return open time for a given session."""
if _parse:
session = parse_session(self, session, "session")
return self.schedule.at[session, "open"]
def session_close(self, session: Session, _parse: bool = True) -> pd.Timestamp:
"""Return close time for a given session."""
if _parse:
session = parse_session(self, session, "session")
return self.schedule.at[session, "close"]
def session_break_start(
self, session: Session, _parse: bool = True
) -> pd.Timestamp | NaTType:
"""Return break-start time for a given session.
Returns pd.NaT if no break.
"""
if _parse:
session = parse_session(self, session, "session")
break_start = self.schedule.at[session, "break_start"]
return break_start