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
97 changes: 81 additions & 16 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ env:
PYTHON_VERSION: "3.12.13"
PIP_DISABLE_PIP_VERSION_CHECK: "1"

# Every data-pipeline gate installs third-party packages from the hash-locked
# requirements/ files and then the project itself with `--no-deps`, so CI tests
# exactly the versions the image ships. docs/IDEA2STRATEGY_DEVELOPMENT.md
# describes how to regenerate them. The market loader keeps its own uv.lock.
jobs:
# ---------------------------------------------------------------- gate 1
gate1-lint:
Expand All @@ -48,10 +52,10 @@ jobs:
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: pip
- name: Install lint tooling
# Same pin as the dev extra, so this gate and a developer machine
# enforce the same rule set.
run: python -m pip install "ruff==0.16.1"
- name: Install lint tooling (hash-locked)
# ruff comes from the same lock a developer installs, so this gate and a
# developer machine enforce the same rule set.
run: python -m pip install --require-hashes -r requirements/dev.txt
- name: ruff check
# The rule set is in pyproject.toml. Legacy files carry an explicit
# per-file/per-code ignore ledger; nothing is disabled repo-wide, so a
Expand All @@ -69,9 +73,55 @@ jobs:
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: pip
- name: Install project and type tooling
- name: Install (hash-locked)
run: |
python -m pip install -e ".[dev]"
python -m pip install --require-hashes -r requirements/dev.txt
python -m pip install --no-deps -e .
# `pip install --no-deps` trusts the lock, so prove the lock still honours
# pyproject.toml. `pip check` covers the base dependencies only; the script
# also walks the `dev` and `test` extras, so a pin bumped in pyproject.toml
# without regenerating requirements/ fails here instead of testing old code.
# It also holds every runtime pin equal across both files, so the suites
# run against the versions the image ships.
- name: The lock satisfies every declared requirement
run: |
python -m pip check
python - <<'PY'
import re
import sys
from importlib.metadata import PackageNotFoundError, distribution, version
from pathlib import Path

from packaging.requirements import Requirement
from packaging.utils import canonicalize_name

def pins(path):
text = Path(path).read_text()
return dict(re.findall(r"^([A-Za-z0-9._-]+)==([^\s;\\]+)", text, re.M))

project = "idea2strategy-data-pipeline"
stale = []
runtime, dev = pins("requirements/runtime.txt"), pins("requirements/dev.txt")
for name, pinned in sorted(runtime.items()):
if dev.get(name) != pinned:
stale.append(f"{name}: runtime.txt pins {pinned}, dev.txt pins {dev.get(name)}")
for raw in distribution(project).requires or []:
req = Requirement(raw)
if canonicalize_name(req.name) == project:
continue # `test` names `dev` through the project itself
if req.marker and not any(req.marker.evaluate({"extra": e}) for e in ("dev", "test")):
continue
try:
found = version(req.name)
except PackageNotFoundError:
stale.append(f"{req}: missing from requirements/dev.txt")
continue
if not req.specifier.contains(found, prereleases=True):
stale.append(f"{req}: the lock pins {found}")
if stale:
sys.exit("requirements/ is stale, regenerate it (docs/IDEA2STRATEGY_DEVELOPMENT.md):\n " + "\n ".join(stale))
print("requirements/dev.txt satisfies pyproject.toml, extras included")
PY
- name: mypy
# `files` in pyproject.toml scopes this to apps/, lambdas/ and the
# migration-contribution validator in strict mode. The legacy packages
Expand All @@ -89,8 +139,10 @@ jobs:
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: pip
- name: Install project and test tooling
run: python -m pip install -e ".[dev]"
- name: Install (hash-locked)
run: |
python -m pip install --require-hashes -r requirements/dev.txt
python -m pip install --no-deps -e .
- name: pytest
run: |
python -m pytest tests \
Expand Down Expand Up @@ -145,8 +197,14 @@ jobs:
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: pip
# The runtime lock alone, as in the image: a module that imports something
# only the dev lock provides fails here, and `pip check` fails if
# pyproject.toml declares a runtime dependency the lock does not satisfy.
- name: Install project (validates packaging and console entry points)
run: python -m pip install -e .
run: |
python -m pip install --require-hashes -r requirements/runtime.txt
python -m pip install --no-deps -e .
python -m pip check
- name: Console entry points are installed
run: |
command -v pipeline-worker
Expand Down Expand Up @@ -290,8 +348,10 @@ jobs:
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: pip
- name: Install project and test tooling
run: python -m pip install -e ".[dev]"
- name: Install (hash-locked)
run: |
python -m pip install --require-hashes -r requirements/dev.txt
python -m pip install --no-deps -e .
- name: Validate the contribution root
run: python db/migration-contributions/validate_contribution.py
- name: Contribution contract tests
Expand Down Expand Up @@ -329,7 +389,8 @@ jobs:
cache: pip
- name: Install project and audit tooling
run: |
python -m pip install -e .
python -m pip install --require-hashes -r requirements/runtime.txt
python -m pip install --no-deps -e .
python -m pip install pip-audit
- name: pip-audit (data-pipeline)
# Fails when any installed dependency has a known advisory. `--strict`
Expand Down Expand Up @@ -415,8 +476,10 @@ jobs:
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: pip
- name: Install project and test tooling
run: python -m pip install -e ".[dev]"
- name: Install (hash-locked)
run: |
python -m pip install --require-hashes -r requirements/dev.txt
python -m pip install --no-deps -e .
- name: Docker is available
run: docker version
- name: Vendored central bundle matches its recorded digests
Expand Down Expand Up @@ -480,8 +543,10 @@ jobs:
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: pip
- name: Install project and test tooling
run: python -m pip install -e ".[dev]"
- name: Install (hash-locked)
run: |
python -m pip install --require-hashes -r requirements/dev.txt
python -m pip install --no-deps -e .
- name: Start LocalStack (s3 + sqs)
run: docker compose -f docker-compose.localstack.yml up -d --wait
- name: Both services are actually enabled
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ report/history/
*.txt
!requirements.txt
!requirements-s3-test.txt
!requirements/*.txt
!ticker_info/etf_universe.csv
!examples/*.csv
backfill-output/
Expand Down
12 changes: 11 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ RUN groupadd --gid 10001 pipeline \

WORKDIR /app

# Third-party packages come only from the hash-locked runtime set, as wheels, so
# a rebuild installs the same bytes and a tampered or substituted file fails.
# See docs/IDEA2STRATEGY_DEVELOPMENT.md for how the lock is regenerated.
COPY requirements/runtime.txt ./requirements/runtime.txt
RUN python -m pip install --no-cache-dir --require-hashes --only-binary=:all: \
-r requirements/runtime.txt

COPY pyproject.toml README.md ./
COPY apps ./apps
COPY lambdas ./lambdas
Expand All @@ -22,7 +29,10 @@ COPY daily_pipeline.py market_pipeline.py pipeline_reporting.py pipeline_state.p
# default. The worker does not invoke Perl or package-management tools at
# runtime; remove it only after Python dependencies are installed to keep the
# vulnerable interpreter out of the shipped image.
RUN python -m pip install --no-cache-dir . \
# `--no-deps`: the project adds nothing that is not already locked, and
# `pip check` fails the build if pyproject.toml declares something the lock lacks.
RUN python -m pip install --no-cache-dir --no-deps . \
&& python -m pip check \
&& dpkg --purge --force-remove-essential perl-base \
&& mkdir -p /var/lib/idea2strategy/catalog /var/lib/idea2strategy/objects \
&& chown -R 10001:10001 /var/lib/idea2strategy
Expand Down
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
38 changes: 38 additions & 0 deletions docs/IDEA2STRATEGY_DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,44 @@ corporate action 등록, adjusted dataset 재생성, 전략 판단 입력은 이
- Parquet 연산은 Polars·PyArrow가 담당합니다.
- Alembic은 사용하지 않으며 DBML·Flyway는 루트 저장소가 통합 관리합니다.

## 의존성 잠금

`pyproject.toml` 은 허용 범위를, `requirements/` 는 그 범위 안에서 실제로 설치하는 정확한
버전과 해시를 기록합니다. backtest-engine 과 같은 방식입니다.

| 파일 | 내용 | 사용하는 곳 |
|---|---|---|
| `requirements/runtime.txt` | 런타임 의존성 | `Dockerfile`, CI gate5·gate7 |
| `requirements/dev.txt` | 런타임 + `dev` extra | 나머지 CI gate, 로컬 개발 |

설치는 항상 두 단계입니다. 잠금 파일을 해시 검증으로 설치한 뒤 프로젝트 자체는 의존성 없이
설치합니다.

```text
python -m pip install --require-hashes -r requirements/dev.txt
python -m pip install --no-deps -e .
```

재생성은 저장소 루트에서 uv(0.13.1에서 확인)로 합니다.

```text
uv pip compile pyproject.toml --python-version 3.12 --universal --generate-hashes -o requirements/runtime.txt
uv pip compile pyproject.toml --python-version 3.12 --universal --generate-hashes --extra dev -o requirements/dev.txt
```

- `pyproject.toml` 의 의존성을 바꾸면 같은 커밋에서 두 파일을 다시 생성합니다. 출력 파일이
이미 있으면 uv는 기존 버전을 유지하고 바뀐 요구만 다시 풉니다.
- 버전을 올릴 때만 `--upgrade-package <이름>` (전체는 `--upgrade`) 을 붙이고, 두 명령에 같은
옵션을 줍니다. 두 파일에 함께 있는 패키지는 버전이 같아야 합니다.
- `--universal` 이므로 Linux amd64·arm64 이미지와 macOS·Windows 개발 환경이 같은 파일을
씁니다. 플랫폼 전용 패키지는 환경 마커로 남습니다.
- 잠금이 어긋나면 CI가 실패합니다. gate5와 이미지 빌드는 `pip check` 로 런타임 의존성을,
gate2는 `dev` extra와 두 파일 사이의 버전 일치까지 검사합니다.
- 빌드 백엔드 `setuptools`·`wheel` 은 해시 검증 대상이 아닙니다. pip가 격리된 빌드 환경에
따로 설치하며 이미지에는 남지 않습니다.
- `idea2strategy-market-loader/` 는 자체 `uv.lock` 을 쓰는 별도 프로젝트이며 이 잠금에
포함되지 않습니다.

## Git Flow

- `develop`: 기본 개발·통합 브랜치
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
Loading
Loading