Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ name: CI
# with a `::warning` annotation in the run, never silenced.
#
# gate1 lint ruff
# gate1b market-loader static ruff + mypy from idea2strategy-market-loader/uv.lock
# gate2 types mypy
# gate3 unit tests + coverage pytest (data-pipeline)
# gate4 market-loader suite pytest (idea2strategy-market-loader) - was never run in CI
Expand Down Expand Up @@ -58,6 +59,36 @@ jobs:
# new violation anywhere fails here.
run: python -m ruff check . --output-format=github

# --------------------------------------------------------------- gate 1b
gate1b-market-loader-static:
name: gate1b-market-loader-static (ruff + mypy)
runs-on: ubuntu-latest
timeout-minutes: 10
# gate1 excludes `idea2strategy-market-loader/`, an independent uv project
# with its own ruff and strict mypy settings, so nothing checked them. The
# tools come from its uv.lock: `--locked` fails when the lock no longer
# matches its pyproject.toml, and the gate enforces the recorded releases.
defaults:
run:
working-directory: idea2strategy-market-loader
env:
UV_PYTHON_DOWNLOADS: never
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: ${{ env.PYTHON_VERSION }}
- name: Install uv
run: python -m pip install "uv==0.13.1"
- name: Install the locked environment
run: uv sync --locked --python "$(command -v python)"
- name: ruff check
run: uv run --no-sync ruff check . --output-format=github
- name: ruff format
run: uv run --no-sync ruff format --check .
- name: mypy
run: uv run --no-sync mypy

# ---------------------------------------------------------------- gate 2
gate2-types:
name: gate2-types (mypy)
Expand Down Expand Up @@ -402,8 +433,14 @@ jobs:
--health-interval 10s --health-timeout 5s --health-retries 12
env:
# The vendored bundle under db/migration-contributions/fixtures is the
# only source available to a bare checkout; leaving this unset would make
# conftest search for a superproject that CI does not check out.
# only source available to a bare checkout. With I2S_SUPERPROJECT_ROOT
# unset, conftest walks the ancestors and siblings of this checkout
# looking for a superproject CI never checks out, which is how
# /home/packer once errored every DB test. Pointing it at this checkout,
# which is not a superproject, turns that search off, so the run always
# applies the vendored bundle.
I2S_SUPERPROJECT_ROOT: ${{ github.workspace }}
# The image Testcontainers starts; conftest defaults to the same tag.
PIPELINE_TEST_POSTGRES_IMAGE: postgres:16-alpine
LOCALSTACK_ENDPOINT_URL: http://localhost:4566
AWS_ACCESS_KEY_ID: test
Expand Down
28 changes: 23 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,29 @@ source_minutes int16 # DERIVED에만 존재

## 설치

`pyproject.toml`의 `requires-python`은 `>=3.12,<3.13`이고 CI와 런타임
이미지는 CPython 3.12.13(COM02)을 씁니다.

```powershell
py -3.11 -m venv .venv
uv venv --python 3.12.13 .venv
.\.venv\Scripts\Activate.ps1
uv pip install -e ".[dev]"
```

uv가 없으면 표준 venv로 같은 환경을 만듭니다.

```powershell
py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip install -e ".[dev]"
```

실행만 필요하면 `.[dev]` 대신 `.`을 설치합니다.

`.env.example`을 참고하여 Alpaca 키를 환경변수로 제공합니다. S3와
PostgreSQL 실행은 각각 선택 의존성 `boto3`, `psycopg[binary]`가 필요합니다.
PostgreSQL 경로가 쓰는 `boto3`, `psycopg[binary]`, `SQLAlchemy`는 선택
의존성이 아니라 런타임 의존성이므로 위 설치에 함께 포함됩니다.
인증정보는 객체, Catalog, 상태, 보고서에 저장하지 않습니다.

`instrument_map.csv`에는 최소 다음 열이 필요합니다.
Expand Down Expand Up @@ -401,8 +415,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:

Expand Down
2 changes: 1 addition & 1 deletion docker-compose.localstack.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
services:
localstack:
image: localstack/localstack:4.14.0
image: localstack/localstack:4.7.0
ports:
- "4566:4566"
environment:
Expand Down
4 changes: 1 addition & 3 deletions idea2strategy-market-loader/src/market_loader/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,9 +464,7 @@ def resume(
database.close()


def _validation_rows(
settings: EnvironmentSettings, manifest_id: UUID
) -> list[dict[str, Any]]:
def _validation_rows(settings: EnvironmentSettings, manifest_id: UUID) -> list[dict[str, Any]]:
database = _database(settings)
try:
with database.transaction() as connection:
Expand Down
4 changes: 2 additions & 2 deletions market_pipeline_lib/legacy_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions market_pipeline_lib/reference/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
SESSION_TYPES,
XNYS_CALENDAR_LIBRARY_VERSION,
XNYS_CALENDAR_VERSION,
XNYS_EXCHANGE_CALENDARS_VERSION,
XNYS_MIC,
TradingSession,
TradingSessionRegistry,
Expand All @@ -73,6 +74,7 @@
"TRADING_SESSIONS",
"XNYS_CALENDAR_LIBRARY_VERSION",
"XNYS_CALENDAR_VERSION",
"XNYS_EXCHANGE_CALENDARS_VERSION",
"XNYS_MIC",
"CalendarSourceDrift",
"InstrumentIdentityConflict",
Expand Down
5 changes: 4 additions & 1 deletion market_pipeline_lib/reference/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
53 changes: 45 additions & 8 deletions market_pipeline_lib/reference/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand All @@ -47,6 +60,7 @@
"SESSION_TYPE_REGULAR",
"XNYS_CALENDAR_LIBRARY_VERSION",
"XNYS_CALENDAR_VERSION",
"XNYS_EXCHANGE_CALENDARS_VERSION",
"XNYS_MIC",
"TradingSession",
"TradingSessionRegistry",
Expand All @@ -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}"

Expand All @@ -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.
Expand Down Expand Up @@ -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()
Expand All @@ -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()}")

Expand Down
21 changes: 17 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -51,7 +61,8 @@ dev = [
"testcontainers[postgres]>=4.8,<5",
# Stubs, not a runtime dependency: without this mypy reports the pandas import
# itself as an error and the module's real type errors stay hidden behind it.
"pandas-stubs>=2.2,<3",
# The same major as the pandas runtime, so mypy checks the API that ships.
"pandas-stubs>=3,<4",
]
# Alias so `pip install -e .[test]` and `-e .[dev]` never drift apart.
test = [
Expand Down Expand Up @@ -219,6 +230,8 @@ module = [
"boto3.*",
"botocore",
"botocore.*",
"exchange_calendars",
"exchange_calendars.*",
"pandas_market_calendars",
"pandas_market_calendars.*",
"pyarrow",
Expand Down
Loading
Loading