def time_til_extended_close(a_date: datetime = to_est()) -> timedelta: """Time until close of extended-trading hours. Args: a_date: date/time Returns: time offset until extended-trading market close """ if not is_extended_hours_market_open(a_date): return timedelta.max close_time = tz_localize( datetime.combine(date=a_date.date(), time=POST_MARKET_CLOSE_TIME)) return close_time - a_date
def time_til_regular_close(a_date: datetime = to_est()) -> timedelta: """Time until close of regular market hours. Args: a_date: date/time Returns: time offset until regular market close """ if not is_market_open(a_date): return timedelta.max close_time = tz_localize( datetime.combine(date=a_date.date(), time=CLOSE_TIME)) return close_time - a_date
def time_til_extended_open(a_date: datetime = to_est()) -> timedelta: """Time until extended trading hours opens again. Args: a_date: date/time Returns: time offset until extended-hours open """ if in_extended_hours_market_time_window(a_date): return timedelta.min # Calculate days to skip for holidays and weekends based on that start of that day base_date = a_date.replace(hour=0, minute=0, second=0, microsecond=0) if is_weekend(base_date) or is_holiday(base_date): while is_weekend(base_date) or is_holiday(base_date): base_date += timedelta(days=1) else: # If after extended-hours close, add a day if in_post_market_time_window(a_date, extended_hours=True): base_date += timedelta(days=1) open_time = tz_localize( datetime.combine(base_date.date(), PRE_MARKET_OPEN_TIME)) return open_time - a_date
def test_time_til_extended_open_market_not_open_expected_time(): one_hour_before = tz_localize( datetime.combine(MARKET_OPEN_DATE, PRE_MARKET_OPEN_TIME) - timedelta(hours=1)) assert timedelta(hours=1) == time_til_extended_open(a_date=one_hour_before)
def test_time_til_regular_open_market_open_expected_time(): one_hour_after = tz_localize( datetime.combine(MARKET_OPEN_DATE, OPEN_TIME) + timedelta(hours=1)) assert timedelta.min == time_til_regular_open(a_date=one_hour_after)
def test_time_til_regular_close_market_open_expected_time(): one_hour_before = tz_localize( datetime.combine(MARKET_OPEN_DATE, CLOSE_TIME) - timedelta(hours=1)) assert timedelta(hours=1) == time_til_regular_close(a_date=one_hour_before)