1- """
2- Cryptocurrency market calendar (24/7 trading).
3- """
1+ """UTC daily crypto sessions with explicit recurring maintenance breaks."""
42
5- from datetime import datetime , timedelta
3+ from datetime import UTC , date , datetime , time , timedelta
4+
5+ import polars as pl
6+ from ml4t .specs import UNSET_CALENDAR , CalendarUnset , FeedSpec
67
78from .base import ExchangeCalendar
89
910
1011class CryptoCalendar (ExchangeCalendar ):
11- """24/7 crypto market calendar with optional maintenance windows."""
12-
13- def __init__ (self , maintenance_window : tuple [int , int ] | None = None ):
14- """
15- Initialize crypto calendar.
16-
17- Parameters
18- ----------
19- maintenance_window : tuple of (start_hour, end_hour) in UTC
20- Optional maintenance window when trading is paused (e.g., (4, 5) for 4-5 AM UTC)
21- """
12+ """Authoritative 24/7 daily sessions, optionally shortened by UTC maintenance.
13+
14+ Maintenance is a half-open daily interval, including across midnight. A
15+ maintenance reopen is not another exchange session. Naive instants mean UTC.
16+ """
17+
18+ def __init__ (
19+ self ,
20+ maintenance_window : tuple [int , int ] | None = None ,
21+ * ,
22+ calendar : str | None | CalendarUnset = UNSET_CALENDAR ,
23+ ) -> None :
24+ from ml4t .engineer .labeling .calendar import PandasMarketCalendar
25+
26+ selected = FeedSpec (time_contract_version = 2 , calendar = "24/7" ).resolve_calendar (
27+ calendar = calendar
28+ )
29+ if selected not in {"24/7" , "CRYPTO_24_7" }:
30+ raise ValueError ("CryptoCalendar requires calendar='24/7'; None is consumer row mode" )
31+ if maintenance_window is not None :
32+ if (
33+ not isinstance (maintenance_window , tuple )
34+ or len (maintenance_window ) != 2
35+ or any (
36+ isinstance (hour , bool ) or not isinstance (hour , int )
37+ for hour in maintenance_window
38+ )
39+ ):
40+ raise ValueError ("maintenance_window must be a pair of integer UTC hours" )
41+ start , end = maintenance_window
42+ if not 0 <= start < 24 or not 0 <= end <= 24 or start == end or (start , end ) == (0 , 24 ):
43+ raise ValueError ("maintenance_window must leave trading time within each UTC day" )
44+ self ._adapter = PandasMarketCalendar ("24/7" )
2245 self .maintenance_window = maintenance_window
2346
2447 @property
@@ -29,79 +52,102 @@ def name(self) -> str:
2952 def timezone (self ) -> str :
3053 return "UTC"
3154
55+ def _normalize (self , dt : datetime ) -> datetime :
56+ return self ._adapter ._normalize_timestamp (dt )
57+
58+ def _session_intervals (self , day : date ) -> list [tuple [datetime , datetime ]]:
59+ intervals = [
60+ (opened , closed )
61+ for opened , closed , _ , _ in self ._adapter ._trading_intervals_around (day )
62+ if opened .date () == day
63+ ]
64+ if self .maintenance_window is None :
65+ return intervals
66+ start , end = self .maintenance_window
67+ midnight = datetime .combine (day , time (), tzinfo = UTC )
68+ for offset in (- 1 , 0 ):
69+ opened = midnight + timedelta (days = offset , hours = start )
70+ closed = midnight + timedelta (days = offset + (end < start ), hours = end )
71+ remaining = []
72+ for first , last in intervals :
73+ if last <= opened or first >= closed :
74+ remaining .append ((first , last ))
75+ else :
76+ if first < opened :
77+ remaining .append ((first , opened ))
78+ if closed < last :
79+ remaining .append ((closed , last ))
80+ intervals = remaining
81+ return intervals
82+
3283 def is_session (self , dt : datetime ) -> bool :
33- """Always true except during maintenance window."""
34- if self .maintenance_window :
35- start_hour , end_hour = self .maintenance_window
36- hour = dt .hour
37- return not (start_hour <= hour < end_hour )
38- return True
84+ """Check UTC membership with left-closed, right-open instant boundaries."""
85+ instant = self ._normalize (dt )
86+ return any (
87+ opened <= instant < closed for opened , closed in self ._session_intervals (instant .date ())
88+ )
89+
90+ def _adjacent_boundary (self , dt : datetime , * , forward : bool ) -> datetime :
91+ instant = self ._normalize (dt )
92+ candidates = []
93+ for offset in (- 2 , - 1 , 0 , 1 ):
94+ intervals = self ._session_intervals (instant .date () + timedelta (days = offset ))
95+ if intervals :
96+ boundary = intervals [0 ][0 ] if forward else intervals [- 1 ][1 ]
97+ eligible = boundary > instant if forward else boundary < instant
98+ if eligible :
99+ candidates .append (boundary )
100+ if not candidates :
101+ raise ValueError (f"No scheduled crypto session boundary near { instant .isoformat ()} " )
102+ return min (candidates ) if forward else max (candidates )
39103
40104 def next_open (self , dt : datetime ) -> datetime :
41- """Next market open (either immediate or after maintenance)."""
42- if self .is_session (dt ):
43- return dt
44-
45- if self .maintenance_window :
46- # Next opening is at the end of maintenance window
47- start_hour , end_hour = self .maintenance_window
48- next_open = dt .replace (hour = end_hour , minute = 0 , second = 0 , microsecond = 0 )
49-
50- # If we're already past end hour today, it's immediate
51- if dt .hour >= end_hour :
52- return dt
53-
54- return next_open
55-
56- return dt
105+ """Return the strictly next daily session open, not a maintenance reopen."""
106+ return self ._adjacent_boundary (dt , forward = True )
57107
58108 def previous_close (self , dt : datetime ) -> datetime :
59- """Previous market close (start of maintenance window)."""
60- if self .maintenance_window :
61- start_hour , end_hour = self .maintenance_window
62-
63- if dt .hour < start_hour :
64- # Maintenance was yesterday
65- prev_close = (dt - timedelta (days = 1 )).replace (
66- hour = start_hour ,
67- minute = 0 ,
68- second = 0 ,
69- microsecond = 0 ,
70- )
71- else :
72- # Maintenance was today or we're in it
73- prev_close = dt .replace (
74- hour = start_hour ,
75- minute = 0 ,
76- second = 0 ,
77- microsecond = 0 ,
78- )
79-
80- return prev_close
81-
82- # No maintenance, so no real "close"
83- return dt - timedelta (seconds = 1 )
109+ """Return the strictly previous daily session close, not an intraday break."""
110+ return self ._adjacent_boundary (dt , forward = False )
84111
85112 def sessions_between (self , start : datetime , end : datetime ) -> list [datetime ]:
86- """
87- List trading sessions. For 24/7 markets, this is every hour
88- outside maintenance windows.
89- """
113+ """Return one daily session open inside the inclusive instant interval."""
114+ start , end = self ._normalize (start ), self ._normalize (end )
115+ if start > end :
116+ raise ValueError ("session interval start must not follow end" )
117+ day = start .date ()
90118 sessions = []
91- current = start .replace (minute = 0 , second = 0 , microsecond = 0 )
92-
93- while current <= end :
94- if self .is_session (current ):
95- sessions .append (current )
96- current += timedelta (hours = 1 )
97-
119+ while day <= end .date ():
120+ intervals = self ._session_intervals (day )
121+ if intervals and start <= intervals [0 ][0 ] <= end :
122+ sessions .append (intervals [0 ][0 ])
123+ day += timedelta (days = 1 )
98124 return sessions
99125
100- def session_duration (self , date : datetime ) -> timedelta : # noqa: ARG002 - interface requirement
101- """Duration of trading session."""
102- if self .maintenance_window :
103- start_hour , end_hour = self .maintenance_window
104- maintenance_duration = end_hour - start_hour
105- return timedelta (hours = 24 - maintenance_duration )
106-
107- return timedelta (hours = 24 )
126+ def session_duration (self , date : datetime ) -> timedelta :
127+ """Return tradable duration of the supplied UTC session-label date."""
128+ return sum (
129+ (closed - opened for opened , closed in self ._session_intervals (date .date ())),
130+ timedelta (0 ),
131+ )
132+
133+ def _session_label (self , dt : datetime ) -> date | None :
134+ instant = self ._normalize (dt )
135+ return instant .date () if self .is_session (instant ) else None
136+
137+ def add_session_info (self , df : pl .DataFrame , timestamp_col : str = "timestamp" ) -> pl .DataFrame :
138+ """Add UTC membership, session labels and clock time without changing input rows."""
139+ dtype = df .schema [timestamp_col ]
140+ if not isinstance (dtype , pl .Datetime ):
141+ raise TypeError ("session annotations require datetime instants, not session labels" )
142+ timestamps = pl .col (timestamp_col )
143+ if dtype .time_zone is None :
144+ timestamps = timestamps .dt .replace_time_zone ("UTC" )
145+ return df .with_columns (
146+ pl .col (timestamp_col )
147+ .map_elements (self .is_session , return_dtype = pl .Boolean )
148+ .alias ("is_session" ),
149+ pl .col (timestamp_col )
150+ .map_elements (self ._session_label , return_dtype = pl .Date )
151+ .alias ("session_date" ),
152+ timestamps .dt .convert_time_zone ("UTC" ).dt .time ().alias ("session_time" ),
153+ )
0 commit comments