From 24ceaae5db24b7cd38a28dc27f657337a685ce01 Mon Sep 17 00:00:00 2001 From: Ryan Min Date: Mon, 26 Oct 2026 21:47:29 +0900 Subject: [PATCH 1/3] fix: pin pandas-market-calendars to the verified 5.4.0 release market_pipeline_lib.reference.sessions raises CalendarSourceDrift for any installed pandas-market-calendars other than XNYS_CALENDAR_LIBRARY_VERSION (5.4.0), but pyproject allowed >=5.4,<6. Since 5.5.0 was published on 2026-10-05, a fresh install (CI and the production image) resolves 5.5.0: 11 reference-catalog unit tests and 6 integration tests fail, and xnys_sessions() raises inside the built image. Pin the exact release the XNYS boundaries were verified against, with a note that the pin and the constant must move together. Verified on CPython 3.12.13: ruff, mypy, gate3 (1090 passed, coverage 89.10%), gate8 with Testcontainers PostgreSQL 16 + LocalStack (160 passed, 0 skipped), and the production image reports 5.4.0 and classifies 2024-11-27..30 correctly. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 2a8f3f8..e3ae4ea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,9 @@ 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", "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. From 1dfb815ed831b716fea44d485a7ec7eb3578915c Mon Sep 17 00:00:00 2001 From: Ryan Min Date: Mon, 26 Oct 2026 21:55:37 +0900 Subject: [PATCH 2/3] chore: pin exchange-calendars and narrow SQLAlchemy and mypy ranges Follow-up hardening to the pandas-market-calendars 5.4.0 pin. exchange-calendars: pandas-market-calendars 5.4.0 resolves "XNYS" through calendars/mirror.py, which takes holidays, special closes and session times from exchange-calendars. That dependency was unconstrained (pmc only requires >=3.3), so the pmc pin did not freeze the XNYS boundaries. Pin exchange-calendars==4.13.2 (what CI resolves; the pinned 2024 XNYS facts pass on it) and extend the CalendarSourceDrift refusal in xnys_sessions to XNYS_EXCHANGE_CALENDARS_VERSION. The calendar_version label stays XNYS/mcal-5.4.0. The drift refusal already ties it to one (pmc, xcals) pair, while renaming it would re-key every trading_sessions row id and leave a database holding two XNYS versions, which the superproject replay oracle rejects. The next bump of either release mints a label that names both. A new test asserts the installed distribution's runtime requirements pin exactly XNYS_CALENDAR_LIBRARY_VERSION and XNYS_EXCHANGE_CALENDARS_VERSION, so a range can no longer reach a fresh install unnoticed. SQLAlchemy: narrow <3 to <2.2. 2.1 retyped Result, enough to fail a type gate, so the next minor is a deliberate bump. The suites pass on 2.1.6. mypy: pin ==2.3.0, the release backtest-engine pins (it floated to 2.4.0). Annotate the two latent scalar_one() sites in legacy_bootstrap.py that mypy 2.3.0 reports as var-annotated under SQLAlchemy 2.1. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +++- market_pipeline_lib/legacy_bootstrap.py | 4 +- market_pipeline_lib/reference/__init__.py | 2 + market_pipeline_lib/reference/errors.py | 5 ++- market_pipeline_lib/reference/sessions.py | 53 +++++++++++++++++++---- pyproject.toml | 15 ++++++- tests/test_reference_catalog.py | 43 ++++++++++++++++++ 7 files changed, 115 insertions(+), 15 deletions(-) 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 e3ae4ea..5d9b309 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,11 @@ authors = [{ name = "Idea2Strategy D bundle" }] dependencies = [ "alpaca-py>=0.43,<1", "boto3>=1.40,<2", + # pandas-market-calendars 5.4.0 resolves "XNYS" through its exchange-calendars mirror, + # which supplies the holidays, early closes and session times, so pinning only the + # former leaves the boundaries free to move. `xnys_sessions` refuses any other release + # (XNYS_EXCHANGE_CALENDARS_VERSION). Bump both together. + "exchange-calendars==4.13.2", "jsonschema>=4.23,<5", "lxml>=6,<7", "numpy>=2,<3", @@ -37,14 +42,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 @@ -221,6 +230,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)) From e2f8631616fe0914244d5daa12bdd403a8fad45e Mon Sep 17 00:00:00 2001 From: Ryan Min Date: Mon, 26 Oct 2026 22:02:27 +0900 Subject: [PATCH 3/3] chore: list the exchange-calendars pin beside pandas-market-calendars Move the pin directly below `pandas-market-calendars==5.4.0` and its comment, so the two releases the XNYS drift check covers sit together. No dependency change. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5d9b309..0d8de65 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,11 +20,6 @@ authors = [{ name = "Idea2Strategy D bundle" }] dependencies = [ "alpaca-py>=0.43,<1", "boto3>=1.40,<2", - # pandas-market-calendars 5.4.0 resolves "XNYS" through its exchange-calendars mirror, - # which supplies the holidays, early closes and session times, so pinning only the - # former leaves the boundaries free to move. `xnys_sessions` refuses any other release - # (XNYS_EXCHANGE_CALENDARS_VERSION). Bump both together. - "exchange-calendars==4.13.2", "jsonschema>=4.23,<5", "lxml>=6,<7", "numpy>=2,<3", @@ -32,6 +27,10 @@ dependencies = [ # `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.