8 Commits (2f4d9f61f7dcd5f01ebabd74d59d7d2729dc862f)
 

Author SHA1 Message Date
I Luk Kim 2f4d9f61f7 feat: implement Phase 4 -- event-driven backtester
Full backtesting engine that reads Parquet snapshots and simulates a
swing-trading strategy with no look-ahead bias.

## New modules (libs/backtest/)
- domain.py: All Pydantic v2 models (Candidate, PlannedOrder, FilledTrade,
  OpenPosition, DailyPortfolioState, MetricsBundle, BacktestConfig, etc.)
- calendar.py: Thin wrappers over time_utils + reaction_date
- manifests.py: Config load/deep-merge/validate, run-ID generation
- metrics.py: 21 pure-function metrics (no pandas, stdlib statistics only)
- selector.py: build_candidate(), rank_candidates() (score↓ ADV↓ symbol↑)
- allocator.py: 7-gate run_entry_gates(), ATR stop, floor() shares
- execution.py: simulate_entry/exit(), update_trailing_stop() (ratchet-up only)
- splits.py: Walk-forward windows, year/regime split utilities
- snapshot_store.py: Sync load() → asyncio.run(_async_load()), no look-ahead
- artifacts.py: Full run-dir writer (Parquet, CSV, JSON)

## App modules (apps/backtester/)
- run.py: BacktestRunner (exit-first→entry simulation, 25% kill switch) + CLI
- replay.py: Double-run determinism checker

## Config files
- configs/backtest/defaults.json: Base strategy defaults
- configs/experiments/baseline_v1.json: First experiment manifest

## Tests: 142 new tests, all passing
- 132 unit tests (no DB/HTTP required)
- 8 integration tests (synthetic SnapshotStore)
- 3 backtest determinism/replay tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim f69a8b4731 fix: use TEST-prefixed IDs in integration tests to avoid real-data conflicts
Integration tests used ISSUER::0000320193 (Apple's real CIK) and
SYM::AAPL::XNYS as hardcoded IDs. After the real pipeline inserts
actual AAPL data, subsequent test runs fail with UniqueViolationError
since the db_session rollback only undoes intra-test writes.

Changed to ISSUER::TEST::0000320193 and SYM::AAPL::XNYS (distinct
from the real SYM::AAPL::US) while keeping ticker="AAPL" so the
Oracle price service returns real price data for label/feature tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim 9d3427e24e fix: disable Qwen3.5 thinking mode and switch OllamaClient to sync httpx
- Add `think: False` and `num_ctx: 8192` to Ollama payload:
  Qwen3.5 extended thinking mode generated 1300+ internal reasoning
  tokens before each response, adding 30-60s latency per LLM call.
  Disabling it reduces parse time from 600s timeout to ~13s.

- Rewrite OllamaClient to use sync httpx.Client inside asyncio.to_thread():
  Async httpx inside an active asyncpg SQLAlchemy session context on
  Python 3.13 hung indefinitely. Synchronous httpx in a thread pool
  completely isolates Ollama I/O from the asyncio event loop.

- Fix filing_poller to set issuer_id/symbol_id on Document records:
  Missing FK caused feature_builder to reject all events with
  event_no_symbol warning. Now looks up IssuerMaster/SymbolMaster
  by ticker before creating Document rows.

- Update test_llm_client to mock _sync_call instead of _client attr.
- Raise ollama_timeout default to 600s for large document processing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim bbe0e31150 feat: implement Phase 3 -- LLM enrichment, labeler, review queue, dataset export
- libs/llm/: OllamaClient (httpx async, retry), LLMCacheStore (SHA-256 DB cache),
  prompt registry (event_classifier_v1), LLMParser (cache→prompt→validate→repair)
- libs/parser/merger.py: rule+LLM canonical merge with provenance tracking,
  conflict detection (both confident + disagree), should_queue_for_review()
- libs/db/models.py: LLMCallCache, ReviewItem, EventLabel 3개 ORM 모델 추가
- libs/db/migrations/versions/0002_phase3_tables.py: Phase 3 Alembic migration
- libs/labeler/: filing_time_bucket→reaction_date, 1D/3D/5D fwd return, MFE/MAE
- libs/review/queue.py: create(dedup)/resolve/list ReviewItem
- libs/export/snapshot_export.py: temporal split + Parquet + manifest.json
- apps/: label_generator, dataset_export, review CLI, gold set evaluator
- 42개 신규 테스트 추가 (unit 32 + integration 4 + replay 1) — 152/152 통과
- libs/common/config.py: OLLAMA_URL/MODEL/TIMEOUT 설정 추가
- libs/common/logging.py: bugfix — add_logger_name incompatible with PrintLoggerFactory

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim 7fed850fbf test: Phase 1/2 체크리스트 재작성 및 Oracle 실연동 통합 테스트
- Oracle 서비스 어댑터 5개를 실제 API 포맷에 맞게 수정
  - 모든 경로에 /api/v1/ prefix 추가
  - price: data[] → bars 매핑, volume float→int
  - filings: accession_number→accession_no, total_count→total
  - financial: financial_data[] → periods, period_date 파싱
  - finra: entries[] → data 매핑
  - fred: data.observations 언패킹, value string→float (버그 수정 포함)
- fixtures 6개를 실제 Oracle 응답 포맷으로 전면 교체
- 통합 테스트에서 httpx_mock 완전 제거 → 실제 Oracle 직접 호출
- 신규 단위 테스트 3개 파일 추가 (logging, fred_service, llm_parser_stub)
- test_retries.py에 exhaustion 테스트 추가
- test_oracle_client.py에 connection/timeout/no-ctx 테스트 추가
- Phase 1/2 testing_checklist.md 실제 구현 기준으로 전면 재작성
- 전체 114 tests pass (unit 100 + replay 5 + integration 9)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim 38ac53b597 implement Phase 2 gap items: backfill CLI, retry, financial features
- filing_poller: add --start-date/--end-date CLI args for historical backfill
  (defaults to 7 days ago when omitted)
- OracleClient.get/post: apply with_retry(max_attempts=3) so transient
  connection errors, timeouts, and 5xx responses are automatically retried
  with exponential backoff (0.1s→0.2s→fail)
- financial_features: new compute_financial_features() extracting latest_eps,
  latest_gross_margin, latest_operating_margin, eps_growth_qoq,
  revenue_growth_qoq from FinancialDataResponse
- feature_builder: wire FinancialService into build_features_for_event(),
  persisting financial_v1 FeatureSnapshot (non-fatal if unavailable)
- tests: 94 pass (81→89 unit + 5 replay); +8 new tests covering financial
  features and retry success path

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim 32a845044c fix: integration test isolation and migration server_default escaping
- Fix all JSONB/text server_default values to use sa.text() wrapper to
  prevent double-escaping in Alembic-generated SQL
- Replace testcontainers with direct docker-compose postgres connection in
  integration conftest, removing asyncio.run() from async fixture context
- Change db_engine/db_session to function-scoped with explicit transaction
  rollback for proper per-test isolation
- Flush IssuerMaster before Document insert to respect FK ordering

All 94 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim 0471018dd8 feat: implement ACE-F v1 Phase 1 -- Stock Oracle 기반 이벤트 파이프라인
Stock Oracle (localhost:18001)을 단일 데이터 소스로 사용하는 미국 주식
이벤트 스윙 트레이딩 시스템의 Phase 1 구현체.

주요 구성:
- libs/oracle_client/: Stock Oracle REST 클라이언트 (filings, price, financial, fred, finra)
- libs/common/: config, logging, time_utils, ids, retries, file_store
- libs/db/: SQLAlchemy 2.0 모델 12개 + Alembic 마이그레이션 0001
- libs/parser/: 규칙 기반 파서 (텍스트 정규화, JSON Schema 검증, LLM 스텁)
- libs/features/: 시장/이벤트 피처 계산기
- apps/pipeline/: filing_poller → filing_fetcher → event_parser → feature_builder
- apps/sync/: macro_sync (FRED), short_volume_sync (FINRA), issuer_sync
- tests/: 단위 81개 + 리플레이 5개 전체 통과, lint clean

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago