krx-quant-core 0.6.2__tar.gz → 0.7.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/PKG-INFO +58 -9
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/README.md +56 -7
- krx_quant_core-0.7.0/docs/superpowers/specs/2026-10-08-data-layer-acceleration-design.md +55 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/pyproject.toml +2 -2
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/__init__.py +1 -1
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/__init__.py +2 -1
- krx_quant_core-0.7.0/src/krx_quant_core/backtest/lob/_window.py +57 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/ceiling.py +7 -14
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/features.py +3 -17
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/ticks.py +15 -3
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/replay.py +40 -2
- krx_quant_core-0.7.0/src/krx_quant_core/backtest/ticktime.py +122 -0
- krx_quant_core-0.7.0/src/krx_quant_core/data/__init__.py +50 -0
- krx_quant_core-0.7.0/src/krx_quant_core/data/daily.py +315 -0
- krx_quant_core-0.7.0/src/krx_quant_core/data/db.py +183 -0
- krx_quant_core-0.7.0/src/krx_quant_core/data/intraday.py +408 -0
- krx_quant_core-0.7.0/src/krx_quant_core/data/store.py +181 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/market/ticks.py +53 -1
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/stats/__init__.py +8 -1
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/stats/matched_null.py +69 -1
- krx_quant_core-0.7.0/tests/backtest/lob/test_lob_window.py +45 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/test_replay.py +41 -0
- krx_quant_core-0.7.0/tests/backtest/test_ticktime.py +113 -0
- krx_quant_core-0.7.0/tests/data/test_data_layer.py +261 -0
- krx_quant_core-0.7.0/tests/data/test_data_review_fixes.py +194 -0
- krx_quant_core-0.7.0/tests/data/test_pg_integration.py +71 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/market/test_ticks.py +28 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/stats/test_stats_matched_null.py +36 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/uv.lock +1 -1
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/.claude/settings.json +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/.github/workflows/ci.yml +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/.github/workflows/commit-identity.yml +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/.github/workflows/publish.yml +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/.gitignore +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/LICENSE +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/docs/superpowers/plans/2026-09-15-simnode-run-infra.md +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/docs/superpowers/plans/2026-09-16-shared-engines.md +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/docs/superpowers/plans/2026-10-04-judgment-axis.md +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/docs/superpowers/specs/2026-09-15-simnode-run-infra-design.md +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/docs/superpowers/specs/2026-09-16-shared-engines-design.md +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/docs/superpowers/specs/2026-10-04-judgment-axis-design.md +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/__init__.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/crosssectional.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/drift.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/fills.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/ledger.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/_jit.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/book.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/control.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/features_v2.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/grid.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/queue.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/lob/sim.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/orderbook.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/backtest/panels.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/costs/__init__.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/costs/model.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/costs/tax.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/__init__.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/book.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/broker.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/engine.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/events.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/guards.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/kiwoom_broker.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/kiwoom_spec.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/oms.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/orders.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/execution/paper.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/market/__init__.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/market/calendar.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/market/codes.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/market/limits.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/market/session.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/py.typed +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/research/__init__.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/research/optuna.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/research/sweep.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/risk/__init__.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/risk/dart_db.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/risk/disclosure.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/risk/killswitch.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/runtime/__init__.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/runtime/cli.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/runtime/gitstate.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/runtime/host.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/runtime/nightly.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/runtime/oos.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/runtime/pins.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/runtime/runindex.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/runtime/runs.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/stats/cv.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/stats/fragility.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/stats/metrics.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/stats/selection.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/stats/sharpe.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/src/krx_quant_core/stats/trials.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/lob/_lob_golden.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/lob/_lob_golden_v2.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/lob/test_lob_ceiling_golden.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/lob/test_lob_features_v2.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/lob/test_lob_grid_golden.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/lob/test_lob_numba_parity.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/lob/test_lob_queue.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/test_backtest_crosssectional.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/test_backtest_fills.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/test_backtest_ledger.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/test_backtest_orderbook.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/test_backtest_panels.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/backtest/test_drift.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/costs/test_cost_model.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/costs/test_tax_schedule.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/execution/test_book.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/execution/test_engine.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/execution/test_kiwoom_broker.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/execution/test_kiwoom_spec.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/execution/test_oms.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/execution/test_order_guards.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/execution/test_paper.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/market/test_limits.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/market/test_trading_calendar.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/research/test_sweep.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/risk/test_dart_disclosure_db_core.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/risk/test_disclosure_gate.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/risk/test_killswitch.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/runtime/test_cli.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/runtime/test_host_guard.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/runtime/test_nightly.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/runtime/test_oos.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/runtime/test_pins.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/runtime/test_runs.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/stats/test_stats_cv.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/stats/test_stats_fragility.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/stats/test_stats_metrics.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/stats/test_stats_selection.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/stats/test_stats_sharpe.py +0 -0
- {krx_quant_core-0.6.2 → krx_quant_core-0.7.0}/tests/stats/test_stats_trials.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: krx-quant-core
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: 한국 주식(KOSPI·KOSDAQ) 퀀트 공통 코어 — 호가단위·가격제한폭·세션, 일자별 거래세 비용모델, 주문 가드, 공시 리스크 분류, 체결 시뮬레이션, Deflated Sharpe·purged CV 검증
|
|
3
|
+
Version: 0.7.0
|
|
4
|
+
Summary: 한국 주식(KOSPI·KOSDAQ) 퀀트 공통 코어 — 호가단위·가격제한폭·세션, 일자별 거래세 비용모델, 주문 가드, 공시 리스크 분류, 체결 시뮬레이션, Deflated Sharpe·purged CV 검증 통계, 공용 데이터 층(COPY·mmap 캐시)
|
|
5
5
|
Project-URL: Homepage, https://github.com/younghwan91/krx-quant-core
|
|
6
6
|
Project-URL: Repository, https://github.com/younghwan91/krx-quant-core
|
|
7
7
|
Author-email: Younghwan Chae <chyohw97@gmail.com>
|
|
@@ -59,12 +59,13 @@ Deflated Sharpe·purged CV 검증 통계를 한 패키지로 묶었다.
|
|
|
59
59
|
## 설치
|
|
60
60
|
|
|
61
61
|
```bash
|
|
62
|
-
pip install krx-quant-core==0.
|
|
63
|
-
# 초 격자 호가 리플레이(backtest.lob)를 numba 로 가속하려면 extra 로: "krx-quant-core[fast]==0.
|
|
64
|
-
# optuna 스윕(research.optuna_search)까지 쓰려면: "krx-quant-core[fast,opt]==0.
|
|
62
|
+
pip install krx-quant-core==0.7.0
|
|
63
|
+
# 초 격자 호가 리플레이(backtest.lob)를 numba 로 가속하려면 extra 로: "krx-quant-core[fast]==0.7.0"
|
|
64
|
+
# optuna 스윕(research.optuna_search)까지 쓰려면: "krx-quant-core[fast,opt]==0.7.0"
|
|
65
|
+
# 데이터 층(data.*)을 Postgres 에서 읽으려면: "krx-quant-core[db]==0.7.0" (psycopg2 가 깔려 있으면 그것도 된다)
|
|
65
66
|
|
|
66
67
|
# PyPI 릴리스 전(또는 태그 고정 개발 중)에는 git 태그로:
|
|
67
|
-
pip install "krx-quant-core @ git+https://github.com/younghwan91/krx-quant-core@v0.
|
|
68
|
+
pip install "krx-quant-core @ git+https://github.com/younghwan91/krx-quant-core@v0.7.0"
|
|
68
69
|
```
|
|
69
70
|
|
|
70
71
|
Python ≥ 3.11. 의존성은 `kiwoom-client`(호가단위 표의 정본), `numpy`, `pandas` 뿐이다.
|
|
@@ -74,7 +75,8 @@ Python ≥ 3.11. 의존성은 `kiwoom-client`(호가단위 표의 정본), `nump
|
|
|
74
75
|
|
|
75
76
|
```
|
|
76
77
|
krx_quant_core/
|
|
77
|
-
├──
|
|
78
|
+
├── data/ 공용 DB 읽기(COPY)·열 단위 mmap 캐시 — 하루치 틱·호가·분봉 CSR, 연도별 일봉·패널, 거래일 달력
|
|
79
|
+
├── market/ 종목코드·Market, 호가단위(스칼라·벡터·ETF), 상/하한가, KST 세션, 거래일 달력
|
|
78
80
|
├── costs/ 일자별 거래세 스케줄, KoreanCostModel(Decimal), round_trip_cost(float)
|
|
79
81
|
├── execution/ 주문 관리 계층 — OrderManager·InstanceLock(oms.py), PositionBook(book.py),
|
|
80
82
|
│ Broker 프로토콜·PaperBroker·KiwoomBroker, EngineCore(같은 전략, 실매매/리플레이),
|
|
@@ -82,7 +84,8 @@ krx_quant_core/
|
|
|
82
84
|
├── risk/ DART 중대공시 분류·RiskGate, DartDisclosureDB, KillSwitch
|
|
83
85
|
├── backtest/ 호가 스윕 VWAP·왕복비용, 지정가 체결 규칙, 트레이드 원장 지표, 횡단면 시뮬,
|
|
84
86
|
│ replay.py(run_replay — EngineCore+PaperBroker 로 과거 이벤트 리플레이),
|
|
85
|
-
│ drift.py(일중·야간 수익 분해 — 이 유니버스의 일중은 구조적으로 음수인가)
|
|
87
|
+
│ drift.py(일중·야간 수익 분해 — 이 유니버스의 일중은 구조적으로 음수인가),
|
|
88
|
+
│ ticktime.py(불규칙 틱시각 직전·미래 창 — numba)
|
|
86
89
|
│ └── lob/ 틱·호가 → 초 격자 특징·경로, 배치=실시간 공용 커널, 에피소드 시뮬, 무작위 대조군, 지정가 대기열 모델,
|
|
87
90
|
│ ceiling.py(오라클 천장 — 완벽한 예지력으로도 비용을 넘는가)
|
|
88
91
|
├── research/ run_sweep(격자·병렬·캐시), optuna_search(TPE, extra `opt`) — 둘 다 모든
|
|
@@ -402,6 +405,46 @@ a.alpha, a.ci_low, a.ci_high, a.by_stratum # 사전
|
|
|
402
405
|
95·98 은 원본 스크립트와 **비트 단위로 같다**(골든 테스트가 원본 복사본을 대조). `through_fill_second` 는
|
|
403
406
|
numba 커널이고 폴백도 같은 숫자다. `cost` 는 필수 인자 — 원본의 `COST = 0.0023` 상수를 박지 않았다.
|
|
404
407
|
|
|
408
|
+
## 데이터 층 (v0.7) — 한 번 읽고, 열 단위로 mmap
|
|
409
|
+
|
|
410
|
+
세 레포가 같은 DB(`KR_QUANT_DB`)를 각자 읽었다: scalp-it 은 하루치 틱·호가 로더 9벌과 날짜별 피클 캐시
|
|
411
|
+
17벌(`~/of80` 17GB), daytrade-it 은 분봉을 매 실행 다시 쿼리, swing-it 은 `daily_bars_adjusted` 580만 행을
|
|
412
|
+
매번 `SELECT *`. `data` 는 Postgres 를 `COPY … TO STDOUT (FORMAT csv)` 로 읽어 열마다 `.npy` 로 저장하고
|
|
413
|
+
다음부터 `mmap` 으로 연다 — 필요한 열만 디스크에서 올라오고, 16 워커가 같은 날을 읽어도 페이지 캐시 한 벌이다.
|
|
414
|
+
캐시 위치 `$KQC_DATA`(기본 `~/.kqc/data`). **옵트인**이라 기존 어댑터는 그대로 돈다.
|
|
415
|
+
|
|
416
|
+
```python
|
|
417
|
+
from datetime import date
|
|
418
|
+
from krx_quant_core import data as D
|
|
419
|
+
from krx_quant_core.backtest.lob import build_second_grid
|
|
420
|
+
|
|
421
|
+
tk = D.load_ticks(date(2026, 10, 7)) # 종목별 CSR: tk.codes, tk.ptr, tk.cols["price"] (int32)
|
|
422
|
+
qs = D.load_quotes(date(2026, 10, 7), levels=3) # 캐시는 10단계 전체, 읽는 건 3단계만
|
|
423
|
+
feat, path = build_second_grid(tk.frame("005930"), qs.frame("005930")) # read_sql 경로와 비트 동일
|
|
424
|
+
mb = D.load_minute_bars(date(2026, 10, 7)) # sec = 분 시작 초
|
|
425
|
+
bars = D.load_daily_bars("2016-01-01", "2026-10-08") # 연도별 캐시 + 지문 — 바뀐 해만 다시 받는다
|
|
426
|
+
panel = D.daily_panel(bars, ["close", "trade_value"], dtype="float32")
|
|
427
|
+
panel.array("close") # code × date (crosssectional 입력 방향)
|
|
428
|
+
panel.frame("close", orient="date_x_code") # orient 는 필수 — .T 빠뜨리는 버그 방지
|
|
429
|
+
cal = D.trading_calendar() # daily_bars 날짜, KST 하루 한 번 DB
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
simnode 실측(2026-10-07 하루, 콜드 → 웜): 틱 190만 행 5.4s → **1ms**, 호가 90만 행 9.0s → **2ms**,
|
|
433
|
+
분봉 56만 행 2.6s → 2ms, 일봉 10년 580만 행 16s → 1.1s(지문 쿼리 포함), 패널 0.35s, 달력 0.74s → 1ms.
|
|
434
|
+
틱 하루 메모리 `read_sql` 223MB → 84MB. 장중 데이터는 **닫힌 날**(KST 오늘 이전)만 캐시하고 오늘은 매번 DB.
|
|
435
|
+
`frame()` 은 정수열을 int64 로 올려 `read_sql` 과 같은 의미다 — 배열(`get()`)을 직접 곱할 땐 먼저
|
|
436
|
+
`astype(np.int64)`(int32 × int32 는 넘친다).
|
|
437
|
+
|
|
438
|
+
같은 판에 들어간 가속(전부 **값 동일** — 원본·정본 대조 테스트):
|
|
439
|
+
|
|
440
|
+
| 무엇 | 전 → 후 |
|
|
441
|
+
|---|---|
|
|
442
|
+
| `lob.ceiling_table`·`forward_labels` 미래 창 극값 (O(n·h) → 단조 덱 O(n)) | 3종목-일 2.23s → 0.058s, h=7200 0.19s → 0.0006s |
|
|
443
|
+
| `market.ticks.tick_size_int` (Decimal → float 밴드 이분탐색) · `tick_size_array`·ETF 표 신설 | 0.44 → 0.07µs/호출 |
|
|
444
|
+
| `backtest.ticktime.trailing_sums`·`forward_max_last` (scalp-it `tick_sanity` 루프 이식) | 13만 틱 21×·119× |
|
|
445
|
+
| `run_replay(cost_model=, liquidate_at_end=)` | daytrade-it 이중 장부 우회 제거 |
|
|
446
|
+
| `stats.cluster_bootstrap_diff_ci` | daytrade-it `diff_ci` 와 같은 숫자, 손 루프 대체 |
|
|
447
|
+
|
|
405
448
|
## 설계 원칙
|
|
406
449
|
|
|
407
450
|
1. **이식은 수치 동일.** 소비 레포가 실매매일에 갈아탈 수 있어야 한다. 포트마다 원본
|
|
@@ -448,7 +491,7 @@ numba 커널이고 폴백도 같은 숫자다. `cost` 는 필수 인자 — 원
|
|
|
448
491
|
```bash
|
|
449
492
|
uv sync --extra dev
|
|
450
493
|
uv sync --extra dev --extra fast # numba 경로까지
|
|
451
|
-
uv run pytest -q #
|
|
494
|
+
uv run pytest -q # 800+ tests (extra fast·opt 포함)
|
|
452
495
|
uv run ruff check src tests
|
|
453
496
|
```
|
|
454
497
|
|
|
@@ -456,6 +499,12 @@ uv run ruff check src tests
|
|
|
456
499
|
|
|
457
500
|
## 로드맵
|
|
458
501
|
|
|
502
|
+
- **v0.7** 로 데이터 층(`data`)과 가속이 들어갔다. 소비 레포 채택 순서 제안: scalp-it 하루치 로더 9벌·
|
|
503
|
+
피클 캐시 → `load_ticks`/`load_quotes`, `select distinct ts::date` → `trading_calendar`, `tick_sanity` 루프
|
|
504
|
+
→ `backtest.ticktime`; daytrade-it 분봉 쿼리 → `load_minute_bars`, `handlers/backtest.py` 이중 장부 →
|
|
505
|
+
`run_replay(cost_model=, liquidate_at_end=True)`, `diff_ci` → `cluster_bootstrap_diff_ci`; swing-it
|
|
506
|
+
`read_prices`·반복 피벗 → `load_daily_bars` + `daily_panel`. 다음: 수집기 COPY 쓰기 경로, 실시간
|
|
507
|
+
`TimeWindow`(pair_detector 창 합), `price_adjust` 의 코어 이전 — 셋 다 실매매·운영 경로라 패리티 근거와 함께.
|
|
459
508
|
- **v0.6** 로 판정 축(`backtest.lob.ceiling`·`stats.selection`·`backtest.drift`·`stats.matched_null`)과
|
|
460
509
|
`kqc nightly status`·`kqc pins` 가 들어갔다. 다음 순서: scalp-it 100번(분봉 275일 탐색)이 3·4 를 쓰게 →
|
|
461
510
|
엔진 A 마무리(두 데몬의 킬·장부를 `OrderManager` 로, 실주문이 멈춘 지금이 교체 비용이 가장 싸다) →
|
|
@@ -28,12 +28,13 @@ Deflated Sharpe·purged CV 검증 통계를 한 패키지로 묶었다.
|
|
|
28
28
|
## 설치
|
|
29
29
|
|
|
30
30
|
```bash
|
|
31
|
-
pip install krx-quant-core==0.
|
|
32
|
-
# 초 격자 호가 리플레이(backtest.lob)를 numba 로 가속하려면 extra 로: "krx-quant-core[fast]==0.
|
|
33
|
-
# optuna 스윕(research.optuna_search)까지 쓰려면: "krx-quant-core[fast,opt]==0.
|
|
31
|
+
pip install krx-quant-core==0.7.0
|
|
32
|
+
# 초 격자 호가 리플레이(backtest.lob)를 numba 로 가속하려면 extra 로: "krx-quant-core[fast]==0.7.0"
|
|
33
|
+
# optuna 스윕(research.optuna_search)까지 쓰려면: "krx-quant-core[fast,opt]==0.7.0"
|
|
34
|
+
# 데이터 층(data.*)을 Postgres 에서 읽으려면: "krx-quant-core[db]==0.7.0" (psycopg2 가 깔려 있으면 그것도 된다)
|
|
34
35
|
|
|
35
36
|
# PyPI 릴리스 전(또는 태그 고정 개발 중)에는 git 태그로:
|
|
36
|
-
pip install "krx-quant-core @ git+https://github.com/younghwan91/krx-quant-core@v0.
|
|
37
|
+
pip install "krx-quant-core @ git+https://github.com/younghwan91/krx-quant-core@v0.7.0"
|
|
37
38
|
```
|
|
38
39
|
|
|
39
40
|
Python ≥ 3.11. 의존성은 `kiwoom-client`(호가단위 표의 정본), `numpy`, `pandas` 뿐이다.
|
|
@@ -43,7 +44,8 @@ Python ≥ 3.11. 의존성은 `kiwoom-client`(호가단위 표의 정본), `nump
|
|
|
43
44
|
|
|
44
45
|
```
|
|
45
46
|
krx_quant_core/
|
|
46
|
-
├──
|
|
47
|
+
├── data/ 공용 DB 읽기(COPY)·열 단위 mmap 캐시 — 하루치 틱·호가·분봉 CSR, 연도별 일봉·패널, 거래일 달력
|
|
48
|
+
├── market/ 종목코드·Market, 호가단위(스칼라·벡터·ETF), 상/하한가, KST 세션, 거래일 달력
|
|
47
49
|
├── costs/ 일자별 거래세 스케줄, KoreanCostModel(Decimal), round_trip_cost(float)
|
|
48
50
|
├── execution/ 주문 관리 계층 — OrderManager·InstanceLock(oms.py), PositionBook(book.py),
|
|
49
51
|
│ Broker 프로토콜·PaperBroker·KiwoomBroker, EngineCore(같은 전략, 실매매/리플레이),
|
|
@@ -51,7 +53,8 @@ krx_quant_core/
|
|
|
51
53
|
├── risk/ DART 중대공시 분류·RiskGate, DartDisclosureDB, KillSwitch
|
|
52
54
|
├── backtest/ 호가 스윕 VWAP·왕복비용, 지정가 체결 규칙, 트레이드 원장 지표, 횡단면 시뮬,
|
|
53
55
|
│ replay.py(run_replay — EngineCore+PaperBroker 로 과거 이벤트 리플레이),
|
|
54
|
-
│ drift.py(일중·야간 수익 분해 — 이 유니버스의 일중은 구조적으로 음수인가)
|
|
56
|
+
│ drift.py(일중·야간 수익 분해 — 이 유니버스의 일중은 구조적으로 음수인가),
|
|
57
|
+
│ ticktime.py(불규칙 틱시각 직전·미래 창 — numba)
|
|
55
58
|
│ └── lob/ 틱·호가 → 초 격자 특징·경로, 배치=실시간 공용 커널, 에피소드 시뮬, 무작위 대조군, 지정가 대기열 모델,
|
|
56
59
|
│ ceiling.py(오라클 천장 — 완벽한 예지력으로도 비용을 넘는가)
|
|
57
60
|
├── research/ run_sweep(격자·병렬·캐시), optuna_search(TPE, extra `opt`) — 둘 다 모든
|
|
@@ -371,6 +374,46 @@ a.alpha, a.ci_low, a.ci_high, a.by_stratum # 사전
|
|
|
371
374
|
95·98 은 원본 스크립트와 **비트 단위로 같다**(골든 테스트가 원본 복사본을 대조). `through_fill_second` 는
|
|
372
375
|
numba 커널이고 폴백도 같은 숫자다. `cost` 는 필수 인자 — 원본의 `COST = 0.0023` 상수를 박지 않았다.
|
|
373
376
|
|
|
377
|
+
## 데이터 층 (v0.7) — 한 번 읽고, 열 단위로 mmap
|
|
378
|
+
|
|
379
|
+
세 레포가 같은 DB(`KR_QUANT_DB`)를 각자 읽었다: scalp-it 은 하루치 틱·호가 로더 9벌과 날짜별 피클 캐시
|
|
380
|
+
17벌(`~/of80` 17GB), daytrade-it 은 분봉을 매 실행 다시 쿼리, swing-it 은 `daily_bars_adjusted` 580만 행을
|
|
381
|
+
매번 `SELECT *`. `data` 는 Postgres 를 `COPY … TO STDOUT (FORMAT csv)` 로 읽어 열마다 `.npy` 로 저장하고
|
|
382
|
+
다음부터 `mmap` 으로 연다 — 필요한 열만 디스크에서 올라오고, 16 워커가 같은 날을 읽어도 페이지 캐시 한 벌이다.
|
|
383
|
+
캐시 위치 `$KQC_DATA`(기본 `~/.kqc/data`). **옵트인**이라 기존 어댑터는 그대로 돈다.
|
|
384
|
+
|
|
385
|
+
```python
|
|
386
|
+
from datetime import date
|
|
387
|
+
from krx_quant_core import data as D
|
|
388
|
+
from krx_quant_core.backtest.lob import build_second_grid
|
|
389
|
+
|
|
390
|
+
tk = D.load_ticks(date(2026, 10, 7)) # 종목별 CSR: tk.codes, tk.ptr, tk.cols["price"] (int32)
|
|
391
|
+
qs = D.load_quotes(date(2026, 10, 7), levels=3) # 캐시는 10단계 전체, 읽는 건 3단계만
|
|
392
|
+
feat, path = build_second_grid(tk.frame("005930"), qs.frame("005930")) # read_sql 경로와 비트 동일
|
|
393
|
+
mb = D.load_minute_bars(date(2026, 10, 7)) # sec = 분 시작 초
|
|
394
|
+
bars = D.load_daily_bars("2016-01-01", "2026-10-08") # 연도별 캐시 + 지문 — 바뀐 해만 다시 받는다
|
|
395
|
+
panel = D.daily_panel(bars, ["close", "trade_value"], dtype="float32")
|
|
396
|
+
panel.array("close") # code × date (crosssectional 입력 방향)
|
|
397
|
+
panel.frame("close", orient="date_x_code") # orient 는 필수 — .T 빠뜨리는 버그 방지
|
|
398
|
+
cal = D.trading_calendar() # daily_bars 날짜, KST 하루 한 번 DB
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
simnode 실측(2026-10-07 하루, 콜드 → 웜): 틱 190만 행 5.4s → **1ms**, 호가 90만 행 9.0s → **2ms**,
|
|
402
|
+
분봉 56만 행 2.6s → 2ms, 일봉 10년 580만 행 16s → 1.1s(지문 쿼리 포함), 패널 0.35s, 달력 0.74s → 1ms.
|
|
403
|
+
틱 하루 메모리 `read_sql` 223MB → 84MB. 장중 데이터는 **닫힌 날**(KST 오늘 이전)만 캐시하고 오늘은 매번 DB.
|
|
404
|
+
`frame()` 은 정수열을 int64 로 올려 `read_sql` 과 같은 의미다 — 배열(`get()`)을 직접 곱할 땐 먼저
|
|
405
|
+
`astype(np.int64)`(int32 × int32 는 넘친다).
|
|
406
|
+
|
|
407
|
+
같은 판에 들어간 가속(전부 **값 동일** — 원본·정본 대조 테스트):
|
|
408
|
+
|
|
409
|
+
| 무엇 | 전 → 후 |
|
|
410
|
+
|---|---|
|
|
411
|
+
| `lob.ceiling_table`·`forward_labels` 미래 창 극값 (O(n·h) → 단조 덱 O(n)) | 3종목-일 2.23s → 0.058s, h=7200 0.19s → 0.0006s |
|
|
412
|
+
| `market.ticks.tick_size_int` (Decimal → float 밴드 이분탐색) · `tick_size_array`·ETF 표 신설 | 0.44 → 0.07µs/호출 |
|
|
413
|
+
| `backtest.ticktime.trailing_sums`·`forward_max_last` (scalp-it `tick_sanity` 루프 이식) | 13만 틱 21×·119× |
|
|
414
|
+
| `run_replay(cost_model=, liquidate_at_end=)` | daytrade-it 이중 장부 우회 제거 |
|
|
415
|
+
| `stats.cluster_bootstrap_diff_ci` | daytrade-it `diff_ci` 와 같은 숫자, 손 루프 대체 |
|
|
416
|
+
|
|
374
417
|
## 설계 원칙
|
|
375
418
|
|
|
376
419
|
1. **이식은 수치 동일.** 소비 레포가 실매매일에 갈아탈 수 있어야 한다. 포트마다 원본
|
|
@@ -417,7 +460,7 @@ numba 커널이고 폴백도 같은 숫자다. `cost` 는 필수 인자 — 원
|
|
|
417
460
|
```bash
|
|
418
461
|
uv sync --extra dev
|
|
419
462
|
uv sync --extra dev --extra fast # numba 경로까지
|
|
420
|
-
uv run pytest -q #
|
|
463
|
+
uv run pytest -q # 800+ tests (extra fast·opt 포함)
|
|
421
464
|
uv run ruff check src tests
|
|
422
465
|
```
|
|
423
466
|
|
|
@@ -425,6 +468,12 @@ uv run ruff check src tests
|
|
|
425
468
|
|
|
426
469
|
## 로드맵
|
|
427
470
|
|
|
471
|
+
- **v0.7** 로 데이터 층(`data`)과 가속이 들어갔다. 소비 레포 채택 순서 제안: scalp-it 하루치 로더 9벌·
|
|
472
|
+
피클 캐시 → `load_ticks`/`load_quotes`, `select distinct ts::date` → `trading_calendar`, `tick_sanity` 루프
|
|
473
|
+
→ `backtest.ticktime`; daytrade-it 분봉 쿼리 → `load_minute_bars`, `handlers/backtest.py` 이중 장부 →
|
|
474
|
+
`run_replay(cost_model=, liquidate_at_end=True)`, `diff_ci` → `cluster_bootstrap_diff_ci`; swing-it
|
|
475
|
+
`read_prices`·반복 피벗 → `load_daily_bars` + `daily_panel`. 다음: 수집기 COPY 쓰기 경로, 실시간
|
|
476
|
+
`TimeWindow`(pair_detector 창 합), `price_adjust` 의 코어 이전 — 셋 다 실매매·운영 경로라 패리티 근거와 함께.
|
|
428
477
|
- **v0.6** 로 판정 축(`backtest.lob.ceiling`·`stats.selection`·`backtest.drift`·`stats.matched_null`)과
|
|
429
478
|
`kqc nightly status`·`kqc pins` 가 들어갔다. 다음 순서: scalp-it 100번(분봉 275일 탐색)이 3·4 를 쓰게 →
|
|
430
479
|
엔진 A 마무리(두 데몬의 킬·장부를 `OrderManager` 로, 실주문이 멈춘 지금이 교체 비용이 가장 싸다) →
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# v0.7.0 — 공용 데이터 레이어 + 가속 (2026-10-08)
|
|
2
|
+
|
|
3
|
+
사용자 지시(2026-10-08): "코어의 디펜던시가 트레이더 레포들을 잘 보필하는지 점검하고 최대한 많은 공통
|
|
4
|
+
비중을 챙겨오고, 캐싱과 가속화·메모리, numba". 세 소비 레포(scalp-it·daytrade-it·swing-it) 감사 결과
|
|
5
|
+
공통 1순위가 같았다 — **코어에 데이터 읽기 층이 없다**.
|
|
6
|
+
|
|
7
|
+
## 감사 요약(근거)
|
|
8
|
+
|
|
9
|
+
- scalp-it: 하루치 틱·호가를 `pd.read_sql` 로 통째 읽고 `dict(tuple(groupby))` 로 복사하는 로더가 9벌,
|
|
10
|
+
날짜별 피클 캐시 로더 17벌(`~/of80` 17GB, float64·object 열 혼재). `select distinct ts::date from ticks`
|
|
11
|
+
로 9.8GB 하이퍼테이블을 훑어 날짜 목록을 낸다(5곳).
|
|
12
|
+
- daytrade-it: 분봉을 매 실행 Postgres 에서 다시 읽는다(코드×일 단위 쿼리 포함), 전 거래일을 005930
|
|
13
|
+
일봉으로 찾는다, `Decimal(str(x))` 로 분봉 OHLC 를 만든다.
|
|
14
|
+
- swing-it: `SELECT *` 로 `daily_bars_adjusted` 전체를 매번 읽고 같은 표를 5~6번 피벗, `code×date`
|
|
15
|
+
vs `date×code` 방향 혼동으로 실제 버그 기록(`inst_flow_accel_gate.py:61`).
|
|
16
|
+
- 코어 자체 느린 곳: `lob.ceiling` 미래 창 O(n·h)(→ 커밋 2a34d66 에서 O(n)), `panels`
|
|
17
|
+
(`pivot_table`·`transform(lambda)`), `crosssectional._trailing_adv`(날짜 루프), `paired_bootstrap`
|
|
18
|
+
(n_boot 파이썬 루프), `matched_control`(트레이드마다 후보 배열 복사), `tick_size_int`(호출마다 Decimal).
|
|
19
|
+
|
|
20
|
+
이전 결정 "읽기 클라이언트는 레포별 독립 사본"(swing-it `storage.py`, 2026-09-12)은 **쓰기 통합**만 다룬
|
|
21
|
+
것이고 캐시·자료형 문제는 다루지 않았다. 이번 데이터 층은 **옵트인**이다 — 기존 어댑터를 깨지 않고,
|
|
22
|
+
소비 레포가 로더를 하나씩 갈아끼운다.
|
|
23
|
+
|
|
24
|
+
## `krx_quant_core.data`
|
|
25
|
+
|
|
26
|
+
| 모듈 | 내용 |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `db` | `resolve_dsn()`(인자 → `KR_QUANT_DB` → `KQC_ENV_FILE`/`.env` 탐색), `connect()`(psycopg3 우선, 없으면 psycopg2), `fetch_frame()` — Postgres 는 `COPY … TO STDOUT (FORMAT csv)` + pandas C 파서(`read_sql` 대비 1.7×, 실측 7.6s→4.5s/일), 그 밖의 DB-API(sqlite 테스트)는 커서. |
|
|
29
|
+
| `store` | `ColumnStore` — `{root}/{dataset}/v{N}/{key}/{col}.npy` + `meta.json`. 열 단위로 쓰고 `mmap_mode="r"` 로 읽는다(16 워커 스윕이 같은 페이지 캐시를 공유, 필요한 열만 디스크에서 올라옴). 원자적 쓰기(임시 파일 → `os.replace`), 열 추가는 `flock`. 의존성 없음(pyarrow 불필요 — 소비 레포 둘에 없다). |
|
|
30
|
+
| `intraday` | `CodeDay`(종목별 CSR: `codes`·`ptr`·열 배열) + `load_ticks(day)`·`load_quotes(day, levels)`·`load_minute_bars(day)`. 시각은 `sec`(자정 기준 int32 초), 가격 int32, 수량 int64, 방향 int8, 강도 float64(DB 비트 동일 — float32 는 피처 골든을 깬다). `CodeDay.frame(code)` 가 `lob.build_second_grid` 가 받는 DataFrame(`ts` 복원)을 낸다. **닫힌 날(KST 오늘 이전)만** 캐시 — 오늘은 매번 DB, 행 0 인 날은 캐시 안 함, 백필 뒤엔 `refresh=True`. 정수열은 int64 로 파싱 후 범위 검사(C 파서에 int32 를 주면 조용히 wrap). |
|
|
31
|
+
| `daily` | `load_daily_bars(start, end, adjusted=)` 긴 프레임(`code` 범주형) + `daily_panel()` → `DailyPanel(codes, dates, 값 배열)` 방향 명시(`frame(field, orient=)`). 캐시는 **연도별**, 지문 `(count, max(date), Σround(close×100), Σvolume)` 정수 합(float 합은 PG 병렬 집계에서 흔들린다). 지문이 바뀐 해만 새 세대로 통째 교체. |
|
|
32
|
+
| (daily 안) | `trading_calendar()` — `daily_bars` 의 distinct date(0.76s)를 하루 한 번 디스크 캐시 → `TradingCalendar`. 직전 평일이 없으면(수집 실패) 캐시 안 하고 10분 뒤 재질의. |
|
|
33
|
+
|
|
34
|
+
## 가속·메모리(기존 API, 값 동일) — 실제 반영분
|
|
35
|
+
|
|
36
|
+
- `backtest.lob.ceiling`·`features.forward_labels`: 미래 창 극값 O(n·h) → 단조 덱 O(n)(`lob._window`).
|
|
37
|
+
- `market.ticks.tick_size_int` float 밴드 이분탐색, `tick_size_array(prices, etf=)`, `ETF_TICK_BANDS`,
|
|
38
|
+
`lob.etf_tick_table()`.
|
|
39
|
+
- `backtest.ticktime.trailing_sums`·`forward_max_last` — scalp-it `tick_sanity` 루프의 numba 이식(비트 동일).
|
|
40
|
+
- `run_replay(cost_model=, liquidate_at_end=)`.
|
|
41
|
+
|
|
42
|
+
측정 후 **하지 않은 것**: `backtest.panels`(재작성 이득 ≤25%, 3,000×2,500 기준 각 ~1s — swing-it 의 해법은
|
|
43
|
+
반복 피벗을 `data.daily_panel` 한 번으로 바꾸는 것), `crosssectional._trailing_adv`(0.8s, nanmean 합 순서가
|
|
44
|
+
배열 메모리 배치에 따라 달라 비트 동일 재현 비용이 큼), `paired_bootstrap`(0.4s)·`matched_control`(0.12s)
|
|
45
|
+
— 이미 1초 미만.
|
|
46
|
+
|
|
47
|
+
## 추가 통계(소비 레포 수작업 대체)
|
|
48
|
+
|
|
49
|
+
- `stats.matched_null.cluster_bootstrap_diff_ci(a, ca, b, cb)` — 두 표본 평균차, 날짜 공동 재추출
|
|
50
|
+
(daytrade-it `diff_ci` 와 같은 숫자; scalp-it `tick_sanity.bootstrap_diff_ci` 는 관측 i.i.d. 라 숫자가 다르다).
|
|
51
|
+
|
|
52
|
+
## 하지 않는 것
|
|
53
|
+
|
|
54
|
+
- 소비 레포 코드 변경(각 레포 세션 몫 — 채택 안내만).
|
|
55
|
+
- 수집기 쓰기 경로(COPY writer)·`TimeWindow` 실시간 상태 — 실매매 경로라 다음 단계에서 패리티 근거와 함께.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "krx-quant-core"
|
|
3
|
-
version = "0.
|
|
4
|
-
description = "한국 주식(KOSPI·KOSDAQ) 퀀트 공통 코어 — 호가단위·가격제한폭·세션, 일자별 거래세 비용모델, 주문 가드, 공시 리스크 분류, 체결 시뮬레이션, Deflated Sharpe·purged CV 검증
|
|
3
|
+
version = "0.7.0"
|
|
4
|
+
description = "한국 주식(KOSPI·KOSDAQ) 퀀트 공통 코어 — 호가단위·가격제한폭·세션, 일자별 거래세 비용모델, 주문 가드, 공시 리스크 분류, 체결 시뮬레이션, Deflated Sharpe·purged CV 검증 통계, 공용 데이터 층(COPY·mmap 캐시)"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = { text = "Apache-2.0" }
|
|
7
7
|
requires-python = ">=3.11"
|
|
@@ -66,7 +66,7 @@ from .sim import (
|
|
|
66
66
|
SimResult,
|
|
67
67
|
simulate_exits,
|
|
68
68
|
)
|
|
69
|
-
from .ticks import TickTable, stock_tick_table
|
|
69
|
+
from .ticks import TickTable, etf_tick_table, stock_tick_table
|
|
70
70
|
|
|
71
71
|
__all__ = [
|
|
72
72
|
"DEFAULT_HORIZONS",
|
|
@@ -113,6 +113,7 @@ __all__ = [
|
|
|
113
113
|
"build_second_grid",
|
|
114
114
|
"compute_features",
|
|
115
115
|
"compute_features_v2",
|
|
116
|
+
"etf_tick_table",
|
|
116
117
|
"cross_section_ranks_v2",
|
|
117
118
|
"forward_labels",
|
|
118
119
|
"new_state_v2",
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""미래 창 최댓값·최솟값 — 단조 덱 O(n) 커널(창 길이와 무관).
|
|
2
|
+
|
|
3
|
+
``out[t] = nanmax(x[t+lo : t+lo+h])`` (뒤는 ``n`` 에서 자른다, 창 안이 전부 nan 이거나 비면
|
|
4
|
+
nan). 원본들은 지평 ``h`` 만큼 배열 전체를 ``fmax`` 로 겹쳐 O(n·h) 였다 — 7,200초 지평이면
|
|
5
|
+
하루 한 종목에 배열 패스 7,200번이다. 최댓값은 **고르는** 연산이라 더하는 순서가 없어서
|
|
6
|
+
덱으로 바꿔도 결과가 비트 단위로 같다(골든 테스트가 원본 식과 대조한다).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from numpy.typing import NDArray
|
|
13
|
+
|
|
14
|
+
from ._jit import njit
|
|
15
|
+
|
|
16
|
+
__all__ = ["forward_extreme"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@njit
|
|
20
|
+
def _forward_extreme(x: NDArray[np.float64], lo: int, h: int, largest: bool) -> NDArray[np.float64]:
|
|
21
|
+
n = x.shape[0]
|
|
22
|
+
out = np.full(n, np.nan)
|
|
23
|
+
if h <= 0:
|
|
24
|
+
return out
|
|
25
|
+
dq = np.empty(n, np.int64) # 창 안 후보 인덱스. head 가 가장 큰 인덱스(먼저 만료)
|
|
26
|
+
head = 0
|
|
27
|
+
tail = 0 # [head, tail) — tail 쪽이 가장 최근에 넣은(작은) 인덱스
|
|
28
|
+
# t 를 거꾸로 돌며 창 [t+lo, t+lo+h-1] 을 왼쪽으로 민다.
|
|
29
|
+
for t in range(n - 1, -1, -1):
|
|
30
|
+
i = t + lo
|
|
31
|
+
if i < n:
|
|
32
|
+
v = x[i]
|
|
33
|
+
if v == v:
|
|
34
|
+
if largest:
|
|
35
|
+
while tail > head and x[dq[tail - 1]] <= v:
|
|
36
|
+
tail -= 1
|
|
37
|
+
else:
|
|
38
|
+
while tail > head and x[dq[tail - 1]] >= v:
|
|
39
|
+
tail -= 1
|
|
40
|
+
dq[tail] = i
|
|
41
|
+
tail += 1
|
|
42
|
+
last = t + lo + h - 1
|
|
43
|
+
while tail > head and dq[head] > last:
|
|
44
|
+
head += 1
|
|
45
|
+
if tail > head:
|
|
46
|
+
out[t] = x[dq[head]]
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def forward_extreme(
|
|
51
|
+
x: NDArray[np.float64], lo: int, h: int, *, largest: bool
|
|
52
|
+
) -> NDArray[np.float64]:
|
|
53
|
+
"""``out[t]`` = ``x[t+lo : t+lo+h]`` 의 nan 무시 최댓값(``largest``)/최솟값. 없으면 nan."""
|
|
54
|
+
if lo < 0:
|
|
55
|
+
raise ValueError("lo must be >= 0")
|
|
56
|
+
arr = np.ascontiguousarray(x, dtype=np.float64)
|
|
57
|
+
return _forward_extreme(arr, int(lo), int(h), bool(largest)) # type: ignore[no-any-return]
|
|
@@ -24,9 +24,9 @@ from collections.abc import Sequence
|
|
|
24
24
|
|
|
25
25
|
import numpy as np
|
|
26
26
|
import pandas as pd
|
|
27
|
-
from numpy.lib.stride_tricks import sliding_window_view
|
|
28
27
|
|
|
29
28
|
from ._jit import njit
|
|
29
|
+
from ._window import forward_extreme
|
|
30
30
|
|
|
31
31
|
__all__ = [
|
|
32
32
|
"DEFAULT_HORIZONS",
|
|
@@ -43,15 +43,8 @@ DEFAULT_HORIZONS: tuple[int, ...] = (10, 30, 60, 300, 600, 1800, 3600, 7200)
|
|
|
43
43
|
|
|
44
44
|
|
|
45
45
|
def _future_extreme(x: np.ndarray, h: int, *, largest: bool) -> np.ndarray:
|
|
46
|
-
"""out[t] = max/min(x[t+2 : t+2+h])
|
|
47
|
-
|
|
48
|
-
best = np.full(n, np.nan, np.float64)
|
|
49
|
-
op = np.fmax if largest else np.fmin
|
|
50
|
-
for j in range(2, h + 2):
|
|
51
|
-
s = np.full(n, np.nan)
|
|
52
|
-
s[: n - j] = x[j:]
|
|
53
|
-
best = op(best, s)
|
|
54
|
-
return best
|
|
46
|
+
"""out[t] = max/min(x[t+2 : t+2+h]) (NaN 무시) — 원본 fmax/fmin h겹 누적과 같은 값, O(n)."""
|
|
47
|
+
return forward_extreme(x, 2, h, largest=largest)
|
|
55
48
|
|
|
56
49
|
|
|
57
50
|
def oracle_long(
|
|
@@ -125,10 +118,10 @@ def window_max(x: np.ndarray, h: int) -> np.ndarray:
|
|
|
125
118
|
"""``w[i] = nanmax(x[i : i+h])`` — 뒤가 모자라면 NaN."""
|
|
126
119
|
x = np.asarray(x, np.float64)
|
|
127
120
|
n = len(x)
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
121
|
+
if n <= h:
|
|
122
|
+
return np.full(n, np.nan)
|
|
123
|
+
out = forward_extreme(x, 0, h, largest=True)
|
|
124
|
+
out[n - h + 1 :] = np.nan
|
|
132
125
|
return out
|
|
133
126
|
|
|
134
127
|
|
|
@@ -23,6 +23,7 @@ import numpy as np
|
|
|
23
23
|
from numpy.typing import NDArray
|
|
24
24
|
|
|
25
25
|
from ._jit import div, njit
|
|
26
|
+
from ._window import forward_extreme
|
|
26
27
|
from .ticks import TickTable, stock_tick_table, tick_of
|
|
27
28
|
|
|
28
29
|
__all__ = [
|
|
@@ -290,22 +291,6 @@ class SecondFeatureStream:
|
|
|
290
291
|
return self._out
|
|
291
292
|
|
|
292
293
|
|
|
293
|
-
@njit
|
|
294
|
-
def _fwd_max_shifted(a: NDArray[np.float64], h: int) -> NDArray[np.float64]:
|
|
295
|
-
"""``out[t] = nanmax(a[t+2 .. t+1+h])`` — 원본 ``mfe`` 정렬(1초 지연 진입 뒤 h초)."""
|
|
296
|
-
n = a.shape[0]
|
|
297
|
-
out = np.full(n, np.nan)
|
|
298
|
-
for t in range(n - 1):
|
|
299
|
-
m = np.nan
|
|
300
|
-
hi = min(t + 1 + h, n - 1)
|
|
301
|
-
for s in range(t + 2, hi + 1):
|
|
302
|
-
v = a[s]
|
|
303
|
-
if v == v and (m != m or v > m):
|
|
304
|
-
m = v
|
|
305
|
-
out[t] = m
|
|
306
|
-
return out
|
|
307
|
-
|
|
308
|
-
|
|
309
294
|
def forward_labels(
|
|
310
295
|
bid: NDArray[np.float64],
|
|
311
296
|
ask: NDArray[np.float64],
|
|
@@ -329,5 +314,6 @@ def forward_labels(
|
|
|
329
314
|
if n - 1 - h > 0:
|
|
330
315
|
exit_b[: n - 1 - h] = bb[1 + h :]
|
|
331
316
|
out[f"net{h}"] = exit_b / ask_e - 1 - cost
|
|
332
|
-
|
|
317
|
+
# 1초 지연 진입 뒤 h초: nanmax(bb[t+2 .. t+1+h]) — 원본 mfe 정렬
|
|
318
|
+
out[f"mfe{h}"] = forward_extreme(bb, 2, int(h), largest=True) / ask_e - 1 - cost
|
|
333
319
|
return out
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
정본이 바뀌면 여기가 조용히 어긋나지 않고 import 가 실패한다.
|
|
6
6
|
|
|
7
7
|
ETF 호가단위(2,000원 미만 1원·이상 5원)는 kiwoom-client 0.4.0 에 **없다**. 정본에 추가를
|
|
8
|
-
요청해 두었고, 그
|
|
8
|
+
요청해 두었고, 그 전까지는 :func:`etf_tick_table` (``market.ticks.ETF_TICK_BANDS``)을 쓴다.
|
|
9
9
|
"""
|
|
10
10
|
|
|
11
11
|
from __future__ import annotations
|
|
@@ -16,11 +16,11 @@ from dataclasses import dataclass
|
|
|
16
16
|
import numpy as np
|
|
17
17
|
from numpy.typing import NDArray
|
|
18
18
|
|
|
19
|
-
from krx_quant_core.market.ticks import tick_size
|
|
19
|
+
from krx_quant_core.market.ticks import ETF_TICK_BANDS, tick_size
|
|
20
20
|
|
|
21
21
|
from ._jit import njit
|
|
22
22
|
|
|
23
|
-
__all__ = ["TickTable", "stock_tick_table", "tick_of"]
|
|
23
|
+
__all__ = ["TickTable", "etf_tick_table", "stock_tick_table", "tick_of"]
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
@dataclass(frozen=True)
|
|
@@ -81,3 +81,15 @@ _STOCK = _load_stock_table()
|
|
|
81
81
|
def stock_tick_table() -> TickTable:
|
|
82
82
|
"""KOSPI·KOSDAQ 주식 호가단위(kiwoom-client 정본)."""
|
|
83
83
|
return _STOCK
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_ETF = TickTable(
|
|
87
|
+
bounds=np.array(ETF_TICK_BANDS[0], np.float64),
|
|
88
|
+
ticks=np.array(ETF_TICK_BANDS[1][:-1], np.float64),
|
|
89
|
+
top=float(ETF_TICK_BANDS[1][-1]),
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def etf_tick_table() -> TickTable:
|
|
94
|
+
"""ETF·ETN 호가단위(2,000원 미만 1원, 이상 5원) — ``simulate_exits(tick_table=...)`` 등에."""
|
|
95
|
+
return _ETF
|
|
@@ -24,6 +24,7 @@ from pathlib import Path
|
|
|
24
24
|
|
|
25
25
|
import pandas as pd
|
|
26
26
|
|
|
27
|
+
from krx_quant_core.costs.model import KoreanCostModel
|
|
27
28
|
from krx_quant_core.execution.book import PositionBook
|
|
28
29
|
from krx_quant_core.execution.engine import Bar, EngineCore, Event, Quote, Strategy, Trade
|
|
29
30
|
from krx_quant_core.execution.events import Fill
|
|
@@ -118,6 +119,28 @@ def merge_events(
|
|
|
118
119
|
return sorted(evs, key=lambda e: (e.ts, _KIND_ORDER[type(e)]))
|
|
119
120
|
|
|
120
121
|
|
|
122
|
+
def _liquidate(book: PositionBook, events: list[Event]) -> list[Fill]:
|
|
123
|
+
last: dict[str, tuple[float, datetime]] = {}
|
|
124
|
+
for ev in events:
|
|
125
|
+
if isinstance(ev, Bar):
|
|
126
|
+
last[ev.code] = (ev.close, ev.ts)
|
|
127
|
+
elif isinstance(ev, Trade):
|
|
128
|
+
last[ev.code] = (ev.price, ev.ts)
|
|
129
|
+
elif isinstance(ev, Quote) and ev.bid > 0:
|
|
130
|
+
last[ev.code] = (ev.bid, ev.ts)
|
|
131
|
+
out: list[Fill] = []
|
|
132
|
+
for code, holding in book.positions().items():
|
|
133
|
+
if code not in last:
|
|
134
|
+
raise ValueError(f"liquidate_at_end: no price observed for held {code}")
|
|
135
|
+
price, ts = last[code]
|
|
136
|
+
fill = Fill(
|
|
137
|
+
ord_no="END", code=code, side="sell", qty=holding.qty, price=int(round(price)), ts=ts
|
|
138
|
+
)
|
|
139
|
+
book.apply(fill)
|
|
140
|
+
out.append(fill)
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
121
144
|
def run_replay(
|
|
122
145
|
strategy: Strategy,
|
|
123
146
|
events: Iterable[Event],
|
|
@@ -127,8 +150,21 @@ def run_replay(
|
|
|
127
150
|
fill_basis: FillBasis = "through",
|
|
128
151
|
latency_sec: float = 0.0,
|
|
129
152
|
market_of: Callable[[str], str] = lambda c: "KOSPI",
|
|
153
|
+
cost_model: KoreanCostModel | None = None,
|
|
154
|
+
liquidate_at_end: bool = False,
|
|
130
155
|
) -> ReplayResult:
|
|
131
|
-
"""``events`` 를 순서대로 ``PaperBroker`` 위 엔진에 먹이고 결과를 모은다.
|
|
156
|
+
"""``events`` 를 순서대로 ``PaperBroker`` 위 엔진에 먹이고 결과를 모은다.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
cost_model: 장부(:class:`PositionBook`)가 청산 때 뺄 비용 모델. 기본은 장부 기본값
|
|
160
|
+
(슬리피지 0 — 체결가에 이미 들어 있다). daytrade-it 처럼 자기 비용 모델이 있으면
|
|
161
|
+
넘긴다(전엔 체결을 두 번째 장부에 다시 적어야 했다).
|
|
162
|
+
liquidate_at_end: 끝에 남은 보유를 종목별 **마지막 관측가**(봉 종가·체결가·매수1호가)로
|
|
163
|
+
장부에서 청산한다(``ord_no="END"`` 체결로 ``fills``·``trades`` 에 남는다). 주문·가드·
|
|
164
|
+
``fill_basis`` 를 거치지 않는 회계상 청산이다 — 가격은 매수1호가가 아니라 마지막
|
|
165
|
+
체결가/종가일 수 있고(원 단위 반올림), 시각은 그 관측 시각이다(지연 체결보다
|
|
166
|
+
이를 수 있다).
|
|
167
|
+
"""
|
|
132
168
|
engine: EngineCore | None = None
|
|
133
169
|
|
|
134
170
|
def clock() -> datetime:
|
|
@@ -136,7 +172,7 @@ def run_replay(
|
|
|
136
172
|
|
|
137
173
|
broker = PaperBroker(fill_basis=fill_basis, latency_sec=latency_sec)
|
|
138
174
|
guard = OrderGuard(guard_config or _default_guard_config(), clock=clock)
|
|
139
|
-
book = PositionBook(market_of=market_of)
|
|
175
|
+
book = PositionBook(market_of=market_of, cost_model=cost_model)
|
|
140
176
|
kill = KillSwitch(kill_config) if kill_config is not None else None
|
|
141
177
|
|
|
142
178
|
# 이벤트를 먼저 목록으로 굳혀 첫 시각을 안다 — on_start 에서 낸 주문도 1970 시계가
|
|
@@ -158,6 +194,8 @@ def run_replay(
|
|
|
158
194
|
for ev in events:
|
|
159
195
|
fills.extend(engine.feed(ev))
|
|
160
196
|
engine.end()
|
|
197
|
+
if liquidate_at_end:
|
|
198
|
+
fills.extend(_liquidate(book, events))
|
|
161
199
|
rows: list[dict] = []
|
|
162
200
|
if log_path.exists():
|
|
163
201
|
with open(log_path, encoding="utf-8") as f:
|