diff --git a/src/quant_platform_kit/markets/__init__.py b/src/quant_platform_kit/markets/__init__.py index 89fe30e1..9579df8c 100644 --- a/src/quant_platform_kit/markets/__init__.py +++ b/src/quant_platform_kit/markets/__init__.py @@ -8,6 +8,8 @@ MarketProfileId, MarketSessionDecision, evaluate_market_session, + is_market_open_now, + is_market_open_today, ) __all__ = [ @@ -20,4 +22,6 @@ "MarketProfileId", "MarketSessionDecision", "evaluate_market_session", + "is_market_open_now", + "is_market_open_today", ] diff --git a/src/quant_platform_kit/markets/sessions.py b/src/quant_platform_kit/markets/sessions.py index 8f994124..d8ee7967 100644 --- a/src/quant_platform_kit/markets/sessions.py +++ b/src/quant_platform_kit/markets/sessions.py @@ -346,3 +346,59 @@ def evaluate_market_session( if profile == MarketProfileId.CME_FUTURES_23X5: return _evaluate_cme_futures_23x5(now, is_trading_day, early_close_by_date) raise ValueError(f"Unsupported market profile: {profile!r}") + + +def _resolve_calendar_factory(calendar_factory: Callable[[str], object] | None): + if calendar_factory is not None: + return calendar_factory + import pandas_market_calendars as mcal + + return mcal.get_calendar + + +def is_market_open_now( + *, + calendar_name: str = "NYSE", + timezone_name: str = US_EQUITY_TIMEZONE, + calendar_factory: Callable[[str], object] | None = None, + now: datetime | None = None, +) -> tuple[bool, Exception | None]: + """Return whether the target exchange regular session is open right now.""" + try: + factory = _resolve_calendar_factory(calendar_factory) + calendar = factory(calendar_name) + market_tz = ZoneInfo(timezone_name) + now_market = now.astimezone(market_tz) if now is not None else datetime.now(market_tz) + schedule = calendar.schedule( + start_date=now_market.date(), + end_date=now_market.date(), + ) + if schedule.empty: + return False, None + try: + return bool(calendar.open_at_time(schedule, now_market)), None + except ValueError as exc: + if "not covered by the schedule" not in str(exc): + raise + return False, None + except Exception as exc: + return False, exc + + +def is_market_open_today( + *, + calendar_name: str = "NASDAQ", + timezone_name: str = US_EQUITY_TIMEZONE, + calendar_factory: Callable[[str], object] | None = None, + now: datetime | None = None, +) -> bool: + """Return whether today is a trading session on the target exchange.""" + factory = _resolve_calendar_factory(calendar_factory) + calendar = factory(calendar_name) + market_tz = ZoneInfo(timezone_name) + now_market = now.astimezone(market_tz) if now is not None else datetime.now(market_tz) + schedule = calendar.schedule( + start_date=now_market.date(), + end_date=now_market.date(), + ) + return not schedule.empty diff --git a/tests/test_market_open_helpers.py b/tests/test_market_open_helpers.py new file mode 100644 index 00000000..435115eb --- /dev/null +++ b/tests/test_market_open_helpers.py @@ -0,0 +1,90 @@ +"""Unit tests for shared exchange market-open helpers.""" + +from __future__ import annotations + +from datetime import datetime, timezone + +from quant_platform_kit.markets import is_market_open_now, is_market_open_today + + +class _FakeSchedule: + def __init__(self, empty: bool) -> None: + self.empty = empty + + +class _FakeCalendar: + def __init__(self, *, empty: bool = False, open_result=True, error: Exception | None = None) -> None: + self._empty = empty + self._open_result = open_result + self._error = error + self.seen_dates = [] + + def schedule(self, *, start_date, end_date): + self.seen_dates.append((start_date, end_date)) + return _FakeSchedule(self._empty) + + def open_at_time(self, schedule, dt): + if self._error is not None: + raise self._error + return self._open_result + + +def test_is_market_open_now_returns_open_status(): + cal = _FakeCalendar(empty=False, open_result=True) + is_open, err = is_market_open_now( + calendar_name="NASDAQ", + calendar_factory=lambda _name: cal, + now=datetime(2026, 11, 20, 15, 0, tzinfo=timezone.utc), + ) + assert is_open is True + assert err is None + + +def test_is_market_open_now_handles_empty_schedule(): + cal = _FakeCalendar(empty=True) + is_open, err = is_market_open_now( + calendar_factory=lambda _name: cal, + now=datetime(2026, 11, 22, 15, 0, tzinfo=timezone.utc), + ) + assert is_open is False + assert err is None + + +def test_is_market_open_now_treats_not_covered_by_schedule_as_closed(): + cal = _FakeCalendar( + empty=False, + error=ValueError("timestamp is not covered by the schedule"), + ) + is_open, err = is_market_open_now( + calendar_factory=lambda _name: cal, + now=datetime(2026, 11, 20, 23, 0, tzinfo=timezone.utc), + ) + assert is_open is False + assert err is None + + +def test_is_market_open_now_returns_unexpected_errors(): + cal = _FakeCalendar(empty=False, error=RuntimeError("calendar failure")) + is_open, err = is_market_open_now( + calendar_factory=lambda _name: cal, + now=datetime(2026, 11, 20, 15, 0, tzinfo=timezone.utc), + ) + assert is_open is False + assert isinstance(err, RuntimeError) + + +def test_is_market_open_today(): + assert ( + is_market_open_today( + calendar_factory=lambda _name: _FakeCalendar(empty=False), + now=datetime(2026, 11, 20, 15, 0, tzinfo=timezone.utc), + ) + is True + ) + assert ( + is_market_open_today( + calendar_factory=lambda _name: _FakeCalendar(empty=True), + now=datetime(2026, 11, 22, 15, 0, tzinfo=timezone.utc), + ) + is False + )