diff --git a/README.md b/README.md index 8493328..76ca0ae 100644 --- a/README.md +++ b/README.md @@ -401,8 +401,12 @@ python market_pipeline.py register-reference-data ... --target postgres --execut ``` `calendar_version`은 경계를 생성한 라이브러리 릴리스를 이름에 담습니다 -(`XNYS/mcal-5.4.0`). 다른 릴리스가 설치되어 있으면 `CalendarSourceDrift`로 -거부합니다. 재계산된 캘린더는 새 버전이며 기존 행을 덮어쓰지 않습니다. +(`XNYS/mcal-5.4.0`). pandas-market-calendars 5.4.0의 XNYS는 exchange-calendars를 +미러링하므로(휴장일·조기 폐장·세션 시각) 두 라이브러리를 모두 고정합니다 +(`pandas-market-calendars==5.4.0`, `exchange-calendars==4.13.2`). 어느 쪽이든 다른 +릴리스가 설치되어 있으면 `CalendarSourceDrift`로 거부합니다. 재계산된 캘린더는 새 +버전이며 기존 행을 덮어쓰지 않습니다. 다음에 두 릴리스 중 하나를 올릴 때는 두 +릴리스를 모두 담은 새 버전 이름을 씁니다(예: `XNYS/mcal-5.5.0+xcals-4.14.0`). DBML 계약 검증 및 별도 export: diff --git a/market_pipeline_lib/legacy_bootstrap.py b/market_pipeline_lib/legacy_bootstrap.py index cf219b1..e9437d0 100644 --- a/market_pipeline_lib/legacy_bootstrap.py +++ b/market_pipeline_lib/legacy_bootstrap.py @@ -494,7 +494,7 @@ def _legacy_schema_metadata(connection: Connection) -> dict[str, Any]: ) """ ) - value = connection.execute(statement).scalar_one() + value: dict[str, Any] = connection.execute(statement).scalar_one() _require(isinstance(value, dict), "legacy schema metadata query did not return an object") return value @@ -962,7 +962,7 @@ def _verify_empty_v001(connection: Connection) -> None: ) for table in _EMPTY_V001_CHANGED_TABLES: schema, name = table.split(".", 1) - count = connection.execute( + count: int = connection.execute( text(f'SELECT count(*) FROM "{schema}"."{name}"') ).scalar_one() if count: diff --git a/market_pipeline_lib/reference/__init__.py b/market_pipeline_lib/reference/__init__.py index f1173f0..45e9c3b 100644 --- a/market_pipeline_lib/reference/__init__.py +++ b/market_pipeline_lib/reference/__init__.py @@ -50,6 +50,7 @@ SESSION_TYPES, XNYS_CALENDAR_LIBRARY_VERSION, XNYS_CALENDAR_VERSION, + XNYS_EXCHANGE_CALENDARS_VERSION, XNYS_MIC, TradingSession, TradingSessionRegistry, @@ -73,6 +74,7 @@ "TRADING_SESSIONS", "XNYS_CALENDAR_LIBRARY_VERSION", "XNYS_CALENDAR_VERSION", + "XNYS_EXCHANGE_CALENDARS_VERSION", "XNYS_MIC", "CalendarSourceDrift", "InstrumentIdentityConflict", diff --git a/market_pipeline_lib/reference/errors.py b/market_pipeline_lib/reference/errors.py index e80c089..ae5e4f7 100644 --- a/market_pipeline_lib/reference/errors.py +++ b/market_pipeline_lib/reference/errors.py @@ -73,7 +73,10 @@ class InvalidTradingSession(ReferenceDataError, ValueError): class CalendarSourceDrift(ReferenceDataError, RuntimeError): - """The installed calendar library is not the one `calendar_version` names. + """An installed calendar library is not the release `calendar_version` stands for. + + Either `pandas_market_calendars` itself or `exchange_calendars`, which its XNYS + mirror takes holidays and early closes from. `trading_sessions.calendar_version` is what a backtest, a realtime evaluation and a weekly object check pin their session boundaries to. Emitting rows diff --git a/market_pipeline_lib/reference/sessions.py b/market_pipeline_lib/reference/sessions.py index 46fcbb7..2ab4200 100644 --- a/market_pipeline_lib/reference/sessions.py +++ b/market_pipeline_lib/reference/sessions.py @@ -8,14 +8,26 @@ **The source has to be real.** Sessions come from `pandas_market_calendars`, the same library `engine.py`, `processing.py` and `quality.py` already use for XNYS, including its own `early_closes` classification. Nothing here re-derives a -holiday rule. +holiday rule. For "XNYS" that library is itself a mirror: its holidays, early +closes and session times come from `exchange_calendars`, so both releases decide +the boundaries. **The version has to be honest.** `calendar_version` is the label downstream replay pins to, so it names the library release that produced the boundaries and -`xnys_sessions` refuses to emit rows under that label from any other release. A -recalculated calendar is therefore a *new version* -- the unique index is -``(exchange_mic, session_date, calendar_version)``, so old rows survive and a -completed backtest's boundaries cannot be silently rewritten. +`xnys_sessions` refuses to emit rows under that label from any other release of +either library. A recalculated calendar is therefore a *new version* -- the +unique index is ``(exchange_mic, session_date, calendar_version)``, so old rows +survive and a completed backtest's boundaries cannot be silently rewritten. + +The label names only the `pandas_market_calendars` release. It was not widened to +name `exchange_calendars` as well when that pin was added: the refusal above +already ties ``XNYS/mcal-5.4.0`` to exactly one pair of releases, and renaming the +label would re-key every published row (the id hashes it), strand any reader +configured with the old label, and leave a database holding two XNYS versions, +which the superproject's replay oracle +(``scripts/integration/backtest_actual_run_oracle.py``) rejects. The next bump of +either release is a new version anyway, and that label should name both, e.g. +``XNYS/mcal-5.5.0+xcals-4.14.0`` (29 of the 40 characters). A row is emitted for every date in the requested range, not only for trading days. "Is 2024-11-28 a session?" is then one lookup with no weekend/holiday fallback @@ -33,6 +45,7 @@ from datetime import UTC, date, datetime, timedelta from typing import Any +import exchange_calendars as xcals import pandas as pd import pandas_market_calendars as mcal @@ -47,6 +60,7 @@ "SESSION_TYPE_REGULAR", "XNYS_CALENDAR_LIBRARY_VERSION", "XNYS_CALENDAR_VERSION", + "XNYS_EXCHANGE_CALENDARS_VERSION", "XNYS_MIC", "TradingSession", "TradingSessionRegistry", @@ -67,6 +81,11 @@ #: The `pandas_market_calendars` release these boundaries were verified against. XNYS_CALENDAR_LIBRARY_VERSION = "5.4.0" +#: The `exchange_calendars` release behind them. `pandas_market_calendars` 5.4.0 +#: serves "XNYS" from its `calendars/mirror.py`, which delegates holidays, early +#: closes and session times to this library. +XNYS_EXCHANGE_CALENDARS_VERSION = "4.13.2" + #: `varchar(40)`. Names the calendar and the library release that produced it. XNYS_CALENDAR_VERSION = f"XNYS/mcal-{XNYS_CALENDAR_LIBRARY_VERSION}" @@ -91,6 +110,12 @@ def _installed_calendar_library_version() -> str: return str(getattr(mcal, "__version__", "unknown")) +def _installed_exchange_calendars_version() -> str: + """Read at call time, like `_installed_calendar_library_version`.""" + + return str(getattr(xcals, "__version__", "unknown")) + + @dataclass(frozen=True) class TradingSession: """One `market_data.trading_sessions` row. @@ -189,9 +214,10 @@ def xnys_sessions(start: date, end: date) -> tuple[TradingSession, ...]: """Every date in ``[start, end]``, classified from the pinned XNYS calendar. Raises `CalendarSourceDrift` when the installed `pandas_market_calendars` is - not the release `XNYS_CALENDAR_VERSION` names: the label is what downstream - replay pins its boundaries to, so it may not be attached to rows a different - release produced. + not the release `XNYS_CALENDAR_VERSION` names, or the installed + `exchange_calendars` is not `XNYS_EXCHANGE_CALENDARS_VERSION`: the label is + what downstream replay pins its boundaries to, so it may not be attached to + rows a different release produced. """ installed = _installed_calendar_library_version() @@ -203,6 +229,17 @@ def xnys_sessions(start: date, end: date) -> tuple[TradingSession, ...]: "XNYS_CALENDAR_LIBRARY_VERSION and the pinned expectations in " "tests/test_reference_catalog.py." ) + installed_mirror = _installed_exchange_calendars_version() + if installed_mirror != XNYS_EXCHANGE_CALENDARS_VERSION: + raise CalendarSourceDrift( + f"exchange-calendars {installed_mirror} is installed but {XNYS_CALENDAR_VERSION} " + "labels boundaries produced with exchange-calendars " + f"{XNYS_EXCHANGE_CALENDARS_VERSION}, which supplies pandas-market-calendars' " + "XNYS holidays and early closes. Re-verify the XNYS facts against the new " + "release, then bump XNYS_EXCHANGE_CALENDARS_VERSION, mint a calendar_version " + "that names both releases, and update the pinned expectations in " + "tests/test_reference_catalog.py." + ) if end < start: raise ValueError(f"end {end.isoformat()} precedes start {start.isoformat()}") diff --git a/pyproject.toml b/pyproject.toml index 2a8f3f8..0d8de65 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,13 @@ dependencies = [ "lxml>=6,<7", "numpy>=2,<3", "pandas>=3,<4", - "pandas-market-calendars>=5.4,<6", + # `market_pipeline_lib.reference.sessions` refuses any release but the one its XNYS + # boundaries were verified against (XNYS_CALENDAR_LIBRARY_VERSION). Bump both together. + "pandas-market-calendars==5.4.0", + # pandas-market-calendars 5.4.0 serves "XNYS" from its exchange-calendars mirror, which + # supplies the holidays, early closes and session times, so the same refusal covers this + # release too (XNYS_EXCHANGE_CALENDARS_VERSION). Bump both together. + "exchange-calendars==4.13.2", "psycopg[binary]>=3.2,<4", # Parquet contract fixtures include the producer version in their metadata. # Keep the writer exact so byte-for-byte determinism is portable across CI and local runs. @@ -35,14 +41,18 @@ dependencies = [ # only transport that can actually receive them. A runtime dependency, not a # test one: the realtime consumer does not work without it. "redis>=5,<7", - "SQLAlchemy>=2.0,<3", + # Capped below the next minor, not the next major: SQLAlchemy 2.1 retyped `Result`, + # which is enough to fail a type gate, so moving past 2.1 is a deliberate bump. + "SQLAlchemy>=2.0,<2.2", ] [project.optional-dependencies] dev = [ "freezegun>=1.5,<2", "httpx>=0.28,<1", - "mypy>=1.17", + # Pinned for the same reason as ruff, and to the release backtest-engine pins: a + # new mypy can report new errors, so a floating one moves the type gate by itself. + "mypy==2.3.0", "pytest>=8.4", "pytest-cov>=6.2", # Pinned, not floating. An unpinned linter means CI and a developer machine @@ -219,6 +229,8 @@ module = [ "boto3.*", "botocore", "botocore.*", + "exchange_calendars", + "exchange_calendars.*", "pandas_market_calendars", "pandas_market_calendars.*", "pyarrow", diff --git a/tests/test_reference_catalog.py b/tests/test_reference_catalog.py index d89da95..3c40fdc 100644 --- a/tests/test_reference_catalog.py +++ b/tests/test_reference_catalog.py @@ -21,9 +21,12 @@ import uuid from datetime import UTC, date, datetime +from importlib.metadata import requires from typing import Any import pytest +from packaging.requirements import Requirement +from packaging.utils import canonicalize_name from market_pipeline_lib.catalog import LocalCatalog, PostgresCatalog, StorageObjectsPolicy from market_pipeline_lib.cli import build_parser, execute @@ -38,7 +41,9 @@ INSTRUMENT_SYMBOLS, INSTRUMENTS, TRADING_SESSIONS, + XNYS_CALENDAR_LIBRARY_VERSION, XNYS_CALENDAR_VERSION, + XNYS_EXCHANGE_CALENDARS_VERSION, XNYS_MIC, CalendarSourceDrift, InstrumentIdentityConflict, @@ -752,6 +757,44 @@ def test_a_different_calendar_library_version_refuses_to_produce_sessions( assert "5.4.0" in str(failure.value) +def test_a_different_exchange_calendars_version_refuses_to_produce_sessions( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """pandas-market-calendars 5.4.0 serves XNYS from an exchange-calendars mirror. + + The holidays and early closes come from there, so pinning pandas-market-calendars + alone would not pin the boundaries the label vouches for. + """ + + import exchange_calendars + + monkeypatch.setattr(exchange_calendars, "__version__", "4.14.0", raising=False) + + with pytest.raises(CalendarSourceDrift) as failure: + xnys_sessions(date(2024, 11, 27), date(2024, 11, 27)) + + assert "4.14.0" in str(failure.value) + assert XNYS_EXCHANGE_CALENDARS_VERSION in str(failure.value) + + +def test_the_distribution_pins_exactly_the_calendar_releases_the_label_was_verified_against() -> None: + """`xnys_sessions` refuses any other release, so the dependency has to as well. + + A range would let a fresh install resolve a newer release and turn the calendar + into a runtime refusal -- how pandas-market-calendars 5.5.0 reached CI. Read from + the installed metadata, which is what pip actually resolved against. + """ + + pins = { + canonicalize_name(requirement.name): str(requirement.specifier) + for requirement in map(Requirement, requires("idea2strategy-data-pipeline") or []) + if requirement.marker is None + } + + assert pins["pandas-market-calendars"] == f"=={XNYS_CALENDAR_LIBRARY_VERSION}" + assert pins["exchange-calendars"] == f"=={XNYS_EXCHANGE_CALENDARS_VERSION}" + + def test_a_backwards_range_is_refused() -> None: with pytest.raises(ValueError): xnys_sessions(date(2024, 11, 29), date(2024, 11, 27))