66from abc import ABC , abstractmethod
77from dataclasses import dataclass
88from datetime import date , timedelta
9+ from typing import Any
910
1011import polars as pl
1112
1213from ml4t .data .futures .schema import ContractSpec
14+ from ml4t .data .sessions .assigner import SessionAssigner
15+ from ml4t .specs import UNSET_CALENDAR , CalendarUnset , FeedSpec
1316
1417
1518@dataclass (frozen = True )
@@ -99,17 +102,34 @@ def select_contracts(
99102
100103
101104class TimeBasedRoll (RollStrategy ):
102- """Select the nearest contract until its configured pre-expiry roll date."""
105+ """Select the nearest contract until its configured pre-expiry roll date.
106+
107+ ``use_business_days=True`` counts authoritative sessions strictly before expiration.
108+ Explicit ``calendar`` overrides ``feed_spec``, then NYSE; an exchange identity does not
109+ select a calendar. A missing target session never moves the trigger to an earlier observation.
110+ ``use_business_days=False`` selects elapsed civil days, not an observation count.
111+ Calendar-free row-based expiry offsets are unsupported in session-count mode.
112+ """
103113
104114 def __init__ (
105115 self ,
106116 days_before_expiration : int = 5 ,
107117 use_business_days : bool = True ,
108- ):
118+ * ,
119+ calendar : str | None | CalendarUnset = UNSET_CALENDAR ,
120+ feed_spec : Any | None = None ,
121+ ) -> None :
109122 if days_before_expiration < 0 :
110123 raise ValueError ("days_before_expiration cannot be negative" )
111124 self .days_before_expiration = days_before_expiration
112125 self .use_business_days = use_business_days
126+ self .feed_spec = FeedSpec .from_any (feed_spec )
127+ self .calendar = self .feed_spec .resolve_calendar (calendar = calendar )
128+ if self .calendar is None and use_business_days :
129+ raise ValueError ("calendar-free row-based expiry rolls are not supported" )
130+ self ._schedule_calendar = (
131+ SessionAssigner (self .calendar ).calendar if self .calendar is not None else None
132+ )
113133
114134 def select_contracts (
115135 self ,
@@ -122,7 +142,7 @@ def select_contracts(
122142 return _empty_selections ()
123143 contracts = dict (_contract_expirations (data ))
124144 roll_dates = {
125- symbol : self ._calculate_roll_date (expiration , dates )
145+ symbol : self ._calculate_roll_date (expiration )
126146 for symbol , expiration in contracts .items ()
127147 }
128148 available_by_date = _available_symbols_by_date (data )
@@ -139,38 +159,54 @@ def select_contracts(
139159 )
140160 return _selection_frame (records )
141161
142- def _calculate_roll_date (self , expiration : date , trading_dates : list [date ]) -> date :
143- """Calculate the last configured roll date on the observed calendar."""
144- target = expiration
145- if self .use_business_days :
146- days_counted = 0
147- while days_counted < self .days_before_expiration :
148- target -= timedelta (days = 1 )
149- if target .weekday () < 5 :
150- days_counted += 1
151- else :
152- target -= timedelta (days = self .days_before_expiration )
153- if target >= trading_dates [- 1 ] or target < trading_dates [0 ]:
154- return target
155- observed = [trading_date for trading_date in trading_dates if trading_date <= target ]
156- return max (observed ) if observed else target
162+ def _calculate_roll_date (self , expiration : date ) -> date :
163+ """Calculate a schedule or explicit elapsed-day trigger independently of observations."""
164+ if not self .use_business_days :
165+ return expiration - timedelta (days = self .days_before_expiration )
166+ if self .days_before_expiration == 0 :
167+ return expiration
168+ span = max (14 , self .days_before_expiration * 2 )
169+ while True :
170+ try :
171+ start = expiration - timedelta (days = span )
172+ except OverflowError as error :
173+ raise ValueError (
174+ "not enough calendar history for the requested expiry offset"
175+ ) from error
176+ schedule = self ._schedule_calendar .schedule (
177+ start_date = start , end_date = expiration - timedelta (days = 1 )
178+ )
179+ if len (schedule ) >= self .days_before_expiration :
180+ return schedule .index [- self .days_before_expiration ].date ()
181+ span *= 2
157182
158183
159184class FirstNoticeDateRoll (RollStrategy ):
160185 """Select physical contracts before the configured first-notice interval."""
161186
162- def __init__ (self , days_before_first_notice : int = 1 ):
187+ def __init__ (
188+ self ,
189+ days_before_first_notice : int = 1 ,
190+ * ,
191+ calendar : str | None | CalendarUnset = UNSET_CALENDAR ,
192+ feed_spec : Any | None = None ,
193+ ) -> None :
163194 if days_before_first_notice < 0 :
164195 raise ValueError ("days_before_first_notice cannot be negative" )
165196 self .days_before_first_notice = days_before_first_notice
197+ self ._time_roll = TimeBasedRoll (calendar = calendar , feed_spec = feed_spec )
166198
167199 def select_contracts (
168200 self , data : pl .DataFrame , contract_spec : ContractSpec | None = None
169201 ) -> pl .DataFrame :
170202 if contract_spec is None or contract_spec .is_cash_settled :
171- return TimeBasedRoll ( days_before_expiration = 5 ) .select_contracts (data , contract_spec )
203+ return self . _time_roll .select_contracts (data , contract_spec )
172204 days = (contract_spec .first_notice_days or 25 ) + self .days_before_first_notice
173- return TimeBasedRoll (days_before_expiration = days ).select_contracts (data , contract_spec )
205+ return TimeBasedRoll (
206+ days_before_expiration = days ,
207+ calendar = self ._time_roll .calendar ,
208+ feed_spec = self ._time_roll .feed_spec ,
209+ ).select_contracts (data , contract_spec )
174210
175211
176212class CalendarRoll (RollStrategy ):
0 commit comments