73 Commits (888dc5be91285d1e1a63afded28dd39e91a2aade)

Author SHA1 Message Date
I Luk Kim 888dc5be91 feat: 생존편향-0 FINRA PIT 데이터셋 — 상폐 가격 백필 + PIT 뷰 + 2020 갭 메우기
숏볼륨 신호 검정을 위한 편향-0 데이터셋 완성:
- alpaca_client/price_service: adjustment 파라미터 추가 (get_bars, get_multi_bars,
  get_or_fetch_multi_bars) — adjustment='all'로 분할+배당 조정 일봉 수집 지원
- scripts/backfill_alpaca_daily_pit.py: FINRA 22,722 심볼(상폐 포함) 전체에
  Alpaca SIP 일봉 백필, row-weighted 잔존편향 리포트 출력
- scripts/backfill_finra_2020_gap.py: 2020-04~10 COVID 갭 (~138 거래일) 메우기
- scripts/export_pit_panel.py: FINRA×Alpaca 조인 패널 → parquet 핸드오프 export
- alembic q8h9i0j1k2l3: pit_universe_membership VIEW 생성 (날짜별 PIT 종목 집합)
- docker-compose: ./scripts live-mount 추가 (app/alembic과 동일 패턴)
- docs/DATA_COVERAGE.md: 실측 커버리지·API 파라미터·PIT 한계 업데이트

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
3 months ago
I Luk Kim 0c797ceb22 fix: attention zscore_20d null 3개 버그 수정 + 엔티티 오버라이드 API 추가
1. materialize_features identity-map 버그 수정
   - upsert commit 후 populate_existing=True로 재SELECT
   - resolve_entity와 동일 패턴 (SQLAlchemy async stale cache)

2. @with_cache 조건부 TTL — null 응답 캐시 단축
   - wiki.views=null → TTL 300s (5분)
   - 완전한 응답 → TTL 3600s (1시간)
   - 기존: null 응답이 1시간 캐시되어 재수집 영구 차단

3. 재실체화 조건 확장: wiki_zscore_20d is None도 재트리거
   - wiki_views는 있지만 lookback 부족으로 zscore만 null인 케이스 처리

4. POST /admin/entity/{ticker}/override 엔드포인트 추가
   - wiki_title 수동 지정 + is_manual_override=True 설정
   - CSCO→Cisco, DKNG→DraftKings 잘못된 매핑 수정용

5. entity_resolver: 소송 페이지 패턴 억제
   - "X v. Y" 형식 제목 score=0.05 (예: FSF v. Cisco Systems)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
3 months ago
I Luk Kim 517914f0ef fix: universe_service market_cap 상한 5e12→2e13 — NVDA $5.5T 스냅샷 필터 해제
NVDA 시총이 $5.5T를 초과하면서 build/screen 양쪽의 5e12($5T) 상한에
걸려 스냅샷 생성 및 조회에서 제외되던 문제 수정.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
3 months ago
I Luk Kim d513f64922 fix: screener total_available 필드 오독 수정 + feat: min_dollar_volume opt-in 추가
[사안 A] total_available 정확성 수정
- raw.get('count')(페이지당 행수=page_size)를 raw.get('total')(실제 매칭
  총수)보다 먼저 읽어 total_available=250/total_pages=1로 잘못 보고됨
- 'total' 우선으로 교정 (screen_stocks + screen_preset)
- 732행 집합에서 total_available 250→732, total_pages 1→3 검증

[사안 B] min_dollar_volume opt-in 파라미터 신규
- 가격(regularMarketPrice) × averageDailyVolume3Month 기준 달러거래량 필터
- 기본 OFF: 미지정 시 기존 경로 byte 동일 (회귀 0 검증)
- 지정 시 min_avg_volume을 Yahoo에 전달하지 않음 (고가·저주식수 우량주
  BLK/KLAC가 소스에서 잘리는 것 방지) → 달러거래량 게이트가 대체
- _collect_all_quotes로 전체 매칭 집합 페이지네이션(24p/6000행 상한,
  초과 시 truncated 플래그) 후 post-filter + 서버측 재정렬
- @with_cache key_params에 min_dollar_volume 등록 (미지정/지정 캐시 분리)
- 검증: min_dollar_volume=1e8 시 BLK/KLAC(p1)·URI/GRMN(p2) 전부 포함,
  exclude_types·market_cap_min·price_min 동시 정상 적용

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
3 months ago
I Luk Kim e2ac9fa4d4 fix: 과거 가격 데이터 upsert → insert-only로 변경 (Yahoo adjusted price 덮어쓰기 방지)
과거 OHLC 행은 on_conflict_do_nothing, 오늘 행만 on_conflict_do_update.
Yahoo Finance의 배당·분할 소급 조정으로 인한 기존 PIT 데이터 훼손 방지.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
3 months ago
I Luk Kim 79164ecb66 fix: universe snapshot + gainer 수집 안정성 개선
- universe_service: yf.download() → Ticker.history() (최신 날짜 버그 수정)
- universe_service: 이미 완료된 ticker skip 로직 추가 (재실행 시 중복 HTTP 방지)
- universe_service: SEC 캐시 클리어 주기 20→5배치 (OOM 방지)
- yahoo_client: 성공 fetch 후 세션 즉시 교체 (Yahoo soft rate-limit 대응)
- scripts/build_snapshots_batched.py: 재작성 — 날짜 자동화, GC 명시, 배치 크기 30

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
3 months ago
I Luk Kim cc024ecbe1 refactor: day_gainers → Yahoo Finance API 직접 호출 (curl_cffi 우회)
- yfinance_plus/preset 제거, query1.finance.yahoo.com 직접 호출
- curl_cffi 세션 풀(4개) + 브라우저 지문 로테이션으로 429 우회
- count=200 반환 확인 (yfinance preset 25개 한계 해소)
- /stocks/gainers: page/page_size → count 파라미터로 변경
- collector: fetch_day_gainers_sync(200) 사용

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
3 months ago
I Luk Kim 1d087b54a4 feat: day_gainers 5분봉 수집 + News v2 ingest + overlay 정리
주요 변경사항:

gainer snapshot (신규)
- gainer_snapshots 테이블: 5분 단위 intraday top-100 day_gainers 스냅샷
- APScheduler CronTrigger (*/5 min, Mon-Fri ET) + 장중 guard (9:30~16:00)
- alembic migration p7g8h9i0j1k2

/stocks/gainers 엔드포인트 (신규)
- yfinance day_gainers preset, 실시간(캐시 없음)
- yfinance_plus screen() wrapper — 모든 screen() 호출에 세션 풀 + 브라우저 지문 우회 적용

News v2 ingest (신규)
- Alpaca News + StockTwits + Finnhub 수집 파이프라인
- news_headlines 테이블 + scheduler (5분 realtime poll, 일 1회 backfill)

Overlay 정리
- 미사용 서브시스템 제거: wikimedia, youtube, google_trends, feature_builder, overlay_scorer
- Yahoo RSS 어댑터 유지, 파이프라인 단순화

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
3 months ago
I Luk Kim 27990ea908 fix: _CHUNK 1500→1200 — asyncpg 32767 param limit 방지
26 cols × 1500 = 39000 > 32767로 MSTR/COIN/META/GOOGL 등 대형 filer에서 batch insert 실패.
26 cols × 1200 = 31200으로 안전하게 유지.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 93a81fd35a fix: Form 4 buy_only=P-only + 10분기 backfill 설정
- buy_only=true 필터를 P+A → P(open-market purchase) 단독으로 변경
  - get_form4_pit / get_form4_by_date / get_form4_aggregate 3곳 동일 수정
  - aggregate의 buy_dollar_total / cluster_size / csuite_count / avg_pct_of_holding
    모두 P-only 기준으로 정확해짐 (A코드 awards 제외)
- _parse_transaction_element: purchase_pct_of_holding 계산도 P-only로 정합
- SEC_FORM4_BOOTSTRAP_QUARTERS: 8 → 10 (2024Q1~)
- Form4AggregateResponse docstring에 P-only 명시

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim db9abd7786 feat: SEC Form 4 PIT + SC 13D/G activist ownership API
## 신규 엔드포인트
- GET /insider/form4/{ticker} — PIT-safe Form 4 거래 목록 (as_of 필수)
- GET /insider/form4/by-date/{date} — 특정 공시일 cross-ticker 거래
- GET /insider/form4/aggregate/{ticker} — 내부자 매수 집계 (window_days)
- GET /ownership/13dg/{ticker} — SC 13D/G activist 이벤트 (as_of 필수)
- GET /ownership/13dg/active — 현재 활성 activist 포지션 (window function PIT)

## 데이터 인프라
- activist_ownership_events 테이블 (42,329행, 최근 2년 bootstrap 완료)
- insider_transactions: is_ceo/is_cfo/is_c_suite/purchase_pct_of_holding/owner_relationship 컬럼 추가
- SECFullIndexService: company.idx fixed-width 파서, form345.zip 파서
- ActivistOwnershipService: SGML header issuer 해석 + cover-page XML/HTML enrich
- SEC ingest scheduler: 매 영업일 09:00 ET daily ingest + 30분 enrich job
- scripts: bootstrap_form4_by_ticker.py, bootstrap_form4_2y.py, bootstrap_13dg.py

## 버그 수정 (enrich 품질)
- filing_url double edgar/ prefix 제거
- XML: classPercent + amountBeneficiallyOwned + reportingPerson... 태그 추가
- HTML: 태그 제거 후 regex 적용 (CSS 10pt → shares 오인식 방지)
- HTML: ownership_pct > 100 방어 로직

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 1f0017a4ea fix: company metadata placeholder 제거 — sector/industry 실제 값 보장
- financial.py: 캐시 히트 시 company 블록을 CMS에서 항상 refresh
  (financial:data:* 캐시에 stale company 블록이 임베드된 문제 해결)
- financial_service.py: _is_placeholder() 확장 — exchange=null인
  Technology/Software 종목도 placeholder로 감지 (AVGO-류 미검출 해결)
- company_metadata_service.py: _sync_fetch() 개선 — yfinance 첫 번째
  호출은 auth 토큰 없이 partial 응답을 반환할 수 있으므로 sector가
  없는 EQUITY 종목에 대해 한 번 retry (auth 캐시 후 full data 획득)
- docker-compose.yml: 컨테이너 시작 시 yfinance_plus 로컬 버전을
  site-packages에 자동 복사 (docker restart 후 override 소실 방지)

검증: USAS/CPRX/HE/ACHR/AVGO 모두 실제 sector/industry/exchange 반환

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim b322d28bd9 feat: yfinance_plus .info 필드 지원 + company metadata 통합
- yfinance_plus submodule 업데이트 (EnhancedTicker.info property 추가)
- company_metadata_service: yfinance_plus 우선 import (fallback: vanilla yfinance)
- Dockerfile: COPY 후 site-packages에 로컬 yfinance_plus 덮어쓰기
- docs/DATA_COVERAGE.md: /company 엔드포인트 섹션 추가, /financial 변경사항 기록

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 7f28266bd6 feat: company metadata 안정화 — 실제 sector/industry/exchange 보강
- CompanyMetadataService 신규: Redis → registry → yfinance 순서 조회,
  semaphore(5) 보호, 24h cache, companies + registry UPSERT
- GET /company/{ticker} + POST /company/bulk (최대 100개, 세션 격리)
- companies 테이블에 exchange/country/market_cap 컬럼 추가 (alembic)
- CompanyInfo 스키마 exchange/country/market_cap 필드 추가
- _is_placeholder() 체크: 기존 "Technology/Software/XYZ Corporation" 행 재보강
- financial endpoint: financials/price 실패 시 company block은 유지 (500 방지)
- bulk endpoint: 각 ticker마다 독립 AsyncSession으로 동시 세션 충돌 방지
- scripts/backfill_registry_sector.py: 9376개 NULL-sector 일괄 보강 스크립트

검증: AU→Basic Materials, USAS→Basic Materials, CPRX→Healthcare,
      HE→Utilities, ACHR→Industrials, ZZZZZZ→404, AAPL 기존 데이터 유지

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 59f78cd3ee fix: OOM → zombie worker 근본 수정 + 대량 스캔 방어 벡터 추가
- docker-compose: uvicorn --reload 제거 (PID 1 직접 실행) + mem_limit 2g→3g
  → OOM 시 컨테이너 종료 → restart:unless-stopped가 자동 복구
- /attention/event: Semaphore(8) + 10s fast-fail + wiki collector rate limit
- wiki_collector: Semaphore(2) + 0.25s min-interval + 429 log-burst 억제
- /filings/events: Semaphore(4) + 10s fast-fail (SEC HTML 다운로드 벡터 차단)
- sec_http_client: CIK 조회 실패 negative cache (1h) — 10MB dict 반복 스캔 제거

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 4e77043671 fix: 백그라운드 reindex 전역 세마포어(3) 추가 — 이벤트 루프 포화 방지
500+ 티커 bulk 스캔 시 ensure_future로 수백 개의 SEC EDGAR 태스크가
동시 생성되어 이벤트 루프 포화 → 서버 응답 불가.
_BACKGROUND_REINDEX_SEMAPHORE(3)으로 동시 실행을 최대 3개로 제한.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim be8dce201d fix: SEC filings 동시 insert 경쟁 조건 수정 (ON CONFLICT + 백그라운드 재인덱스)
동시 요청 시 둘 다 빈 existing_accs 읽고 중복 INSERT → UniqueViolationError 발생.
pg_insert().on_conflict_do_nothing()으로 원자적 upsert 교체,
staleness 재인덱스를 background task로 이동해 요청 차단 제거.
auto-parse는 최근 20개로 제한.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim b4d8c97ba2 fix: Alpaca end 파라미터를 날짜 → datetime(UTC)으로 수정
날짜만 보내면(2026-04-15) Alpaca가 ET 자정(23:59 ET = 03:59 UTC)으로 해석해
당일 장 마감 후에도 "미래 end" 로 판정 → SIP 403 에러 발생.
RFC-3339 datetime 형식(2026-04-15T23:59:59Z)으로 변경하면
Alpaca가 UTC 기준으로 정확히 해석해 15분 규칙을 통과함.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim abfab0fa57 fix: OOM kill 방지 — Phase 4 경량화 + Semaphore 3으로 제한
Worker가 OOM kill로 죽는 것을 확인 (docker inspect: OOMKilled=true).
호스트 메모리: 물리 RAM ~68MB 여유, 스왑 97% 사용 상태.

원인: Phase 4에서 SELECT AlpacaPriceData (전체 ORM 객체) 로드.
- 75 ticker × 78 5분봉 = 5,850개 ORM 객체/요청
- SQLAlchemy ORM instrumentation으로 dict 대비 ~10x 메모리 소비
- Semaphore(10) → 최대 10개 요청 동시 처리 = 피크 수백 MB ~ 1GB

수정:
- Phase 4: SELECT * → SELECT 7 columns only (ticker, date, OHLCV)
  → result.all()로 경량 Row namedtuple 반환, ORM 객체 생성 없음
  → SQLAlchemy Row는 속성 접근(row.date, row.open 등) 지원 — 엔드포인트 호환
- Semaphore(10) → Semaphore(3): 동시 처리 3개로 제한
  → 피크 메모리 ~70% 감소

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim ffaed4fc9d fix: 서버 응답불능 — limit-concurrency 20 + asyncio yield points
BaseHTTPMiddleware는 요청당 2개 asyncio task를 생성한다.
--limit-concurrency 100은 여전히 200개 task가 event loop를 포화시켜
health check 포함 모든 요청이 block됐다.

변경 사항:
- docker-compose.yml: --limit-concurrency 100 → 20
  (세마포어 10개 처리 + 10개 대기, 나머지 20초과 시 503으로 즉시 반환)
- alpaca_price_service.py: upsert 루프 청크 사이 + Phase 4 ORM 일괄 생성 후
  await asyncio.sleep(0) 추가 — 동기 CPU 블로킹 중 event loop yield 보장

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim dd3e38fbf5 fix: GET /price/data — Alpaca → yfinance 교체 + bulk end_date 버그 2건 수정
- GET /price/data를 AlpacaPriceService 대신 PriceDataService(yfinance)로 교체
- ?ticker= alias 추가 (기존 ?tickers= 유지, 인터페이스 호환)
- _bulk_fetch_price_data: yfinance end 파라미터 exclusive 미반영 (+1일 누락) 수정
- get_multi_ticker_daily_bars: end_dt를 min.time(00:00) → max.time(23:59:59)으로 수정
  (DB 쿼리 date <= end_dt 에서 당일 레코드가 필터링되던 버그)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim c203f3920b refactor: session-per-phase — DB 커넥션을 외부 API 호출 중 해제
서비스 메서드가 db: AsyncSession을 인자로 받아 외부 API 호출(yfinance 30-60s,
Alpaca HTTP) 중에도 DB 커넥션을 잡고 있던 구조를 제거.

변경 패턴 (Session-per-phase):
  Before: Endpoint(db) → Service(db) → DB check → API call(30s 세션 유지) → DB store
  After:  Endpoint()   → Service()   → DB check(세션1) → API call(세션 없음) → DB store(세션2)

변경 파일:
- alpaca_price_service.py: fetch_and_store_bars, get_or_fetch_multi_bars에서 db 제거
- price_data_service.py: get_or_update_price_data, get_multiple_tickers_data_optimized에서
  db 제거; _fetch_price_data(새), _bulk_fetch_price_data(새, lambda 클로저 버그 수정);
  _fetch_and_store_price_data, _bulk_fetch_and_store_price_data, get_multiple_tickers_data 제거
- alpaca.py, price.py: Depends(get_db) 제거 (GET /latest 제외)
- financial_service.py, real_sec_financial_service.py: 호출 인자 정리

결과: "idle in transaction" 커넥션 0개, 풀 고갈 원인 근본 해결

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 5bcba8632c fix: fetch_and_store_bars() interval 컬럼 추가 + CHUNK 분할
- interval 누락으로 uq_alpaca_price_data constraint 위반 방지
- 단일 INSERT → CHUNK=2300 분할 (14 params/row, asyncpg 한도 대비)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim e6ea1abb0e fix: asyncpg param 한도 초과 — INSERT CHUNK 2900→2300
interval 컬럼 추가로 row당 파라미터 14개로 증가.
2900 × 14 = 40,600 > 32,767 → InterfaceError 발생.
2300 × 14 = 32,200으로 안전 범위 내 수정.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim af26df8895 feat: AlpacaPriceData에 interval 컬럼 추가 — 일봉/분봉 DB 충돌 해결
- alpaca_price_data 테이블에 interval 컬럼 추가 (VARCHAR, default '1d')
- unique constraint: (ticker, date) → (ticker, date, interval)
- get_or_fetch_multi_bars(): interval 필터로 coverage 체크 및 DB 조회
- insert rows에 interval 포함
- asyncpg param limit 대비 CHUNK 3000→2900 (파라미터 11개/행)
- alembic 마이그레이션: h9b0c1d2e3f4

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 800bb9b4a6 fix: /alpaca/intraday/{ticker} SIP 피드로 변경 + 어제까지 날짜 제한
- fetch_bars_raw()에 feed 파라미터 추가
- /intraday/{ticker}: IEX → SIP, end_date >= 오늘이면 400 에러
- 캐시 TTL: 5분 → 24시간 (과거 데이터는 변하지 않음)
- openapi.json 업데이트

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 8e58fdffa5 feat: Alpaca intraday 엔드포인트 분리 — /intraday (SIP, 과거) + /intraday/today (IEX, 당일)
- GET /alpaca/intraday: SIP 피드로 변경, end_date >= 오늘이면 400 에러, 백테스트용
- GET /alpaca/intraday/today: 신규, IEX 피드, 오늘 당일 실시간 전용, force_refresh=True
- AlpacaPriceService.get_or_fetch_multi_bars()에 feed 파라미터 추가

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 73bf6115fa fix: _batch_check_missing_periods — today 포함 시 항상 re-fetch
_check_missing_periods는 수정됐지만 bulk 경로에서 사용하는
_batch_check_missing_periods에는 동일한 today 체크가 빠져 있었음.

POST /price/data/bulk로 당일 데이터 요청 시 DB에 mid-session으로
캐시된 partial-volume 데이터를 그대로 반환하는 버그.

end_date.date() >= today이면 모든 티커를 missing으로 처리하여
_check_missing_periods와 동일한 동작 보장.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim bb2a06ce6e fix: reduce Alpaca multi-bar batch_size 200 → 100
Community reports 502 above ~100 symbols per request. Official docs have
no stated limit but 200 appears to be a ceiling. 100 is a safe conservative
default that avoids the 502 edge case with minimal performance impact
(500 tickers = 5 batches instead of 3).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 38207d342c fix: Alpaca intraday 503 — auto-select feed=iex for free plan
Free plan blocks SIP intraday data (403). IEX feed is free and real-time.
- _default_feed(): returns 'iex' for intraday timeframes, None for daily+
- get_bars() / get_multi_bars(): apply default feed automatically
- Callers can override with feed='sip' if on paid plan

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 5ef4d1790d feat: GET /price/intraday — multi-ticker intraday via Yahoo Finance
Alpaca free plan blocks recent SIP data (403 on same-day requests).
Replace with Yahoo Finance which has no subscription requirement.

- PriceDataService.get_multi_intraday(): yf.download() in chunks of 50,
  handles both single (flat DataFrame) and multi-ticker (MultiIndex) cases
- GET /price/intraday?tickers=...&interval=5m&start_date=...&end_date=...
  → same AlpacaMultiBarsResponse format (bars: {sym → [{timestamp,ohlcv}]})
  → source="YAHOO_FINANCE", Redis 5-min TTL cache
- /alpaca/intraday still exists for historical data (works on free plan)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 2081611884 fix: multi-ticker daily bars — DB storage + DB-first fetch logic
- AlpacaPriceService.get_or_fetch_multi_bars(): checks DB max_date per
  ticker, only fetches missing ranges from Alpaca, upserts with chunking
  (3000 rows/chunk, asyncpg 32767-param limit) then reads back from DB
- GET /price/data endpoint: now uses service + Depends(get_db); subsequent
  calls for same date range skip Alpaca entirely
- force_refresh=true bypasses DB check and re-fetches all from Alpaca

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim fbb42edfc2 feat: multi-ticker bulk bars endpoints + BF-B ticker normalization
- GET /api/v1/price/data?tickers=AAPL,MSFT,BF-B&start_date=...&end_date=...
  → multi-ticker daily OHLCV via Alpaca (ORB engine daily bars interface)
- GET /api/v1/alpaca/intraday?tickers=...&interval=5min&start_date=...&end_date=...
  → multi-ticker intraday OHLCV via Alpaca (ORB engine ORB-window interface)
- AlpacaMultiBarsResponse schema: {source, interval, count, bars: {sym → [bar]}}
- normalize_ticker(): BF-B→BF.B, BRK-B→BRK.B applied in get_bars/get_multi_bars/get_snapshot(s)
- get_multi_bars: transparent batching (200 symbols/request) + INTERVAL_MAP aliases (5min, 15min, 60min, …)
- Response re-keys Alpaca normalized symbols back to original input names

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim a9a158d804 feat: Alpaca 실시간 snapshot 엔드포인트 추가
- GET /alpaca/snapshot/{ticker} — 단일 티커 실시간 가격/bid-ask/OHLCV/등락률
- GET /alpaca/snapshot?tickers=A,B — 최대 100개 멀티 티커 일괄 조회
- AlpacaClient.get_snapshot / get_snapshots 메서드 추가
- AlpacaSnapshotResponse / AlpacaMultiSnapshotResponse 스키마 추가
- docs/PYTHON_CLIENT.md 사용 예시 업데이트
- 캐시 없음 — 매 요청마다 Alpaca API 직접 호출

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim a496789fbe feat: 8-K 재파싱 지원 — force_reparse + 단일 accession 재처리 endpoint
- POST /filings/events/parse/{accession_number}: 특정 filing 강제 재파싱
  (parsed_status 무관하게 pending으로 리셋 후 즉시 파싱)
- POST /filings/events/parse/bulk에 force_reparse: bool 추가
  (true이면 succeeded/failed도 pending으로 리셋 후 재처리)
- BulkParseRequest에 force_reparse 필드 추가

사용법:
  curl -X POST /api/v1/filings/events/parse/0001193125-26-144028
  curl -X POST /api/v1/filings/events/parse/bulk -d '{"tickers":["AVGO"],"force_reparse":true}'

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 25603c390c feat: 8-K filing parser — Item 추출 + event 생성
AVGO 8-K (accession 0001193125-26-144028, Item 8.01, Google TPU 공급계약)이
DB에 수집은 되었으나 파싱/event 생성이 불가했던 문제 해결.

구현:
- sec_8k_parser.py: 8-K primary document HTML 파싱
  - extract_items(): regex 기반 Item 헤더 추출, 목차 중복 제거 (last-wins)
  - _strip_ixbrl_viewer(): documents_json의 /ix?doc=... URL → 직접 URL 변환
  - _find_primary_doc_url(): primary_document_url 우선 사용 (iXBRL viewer 회피)
  - Item 8.01 단독 filing: exhibit(9.01) 없이 본문에서 직접 content 추출
  - Item 9.01 skip, 나머지는 ITEM_EVENT_MAP으로 event_type 분류
  - Exhibit enrichment: 2.02/7.01/8.01 + EX-99.1 있을 때 exhibit content 우선
- sec_filing_events 테이블 신설 (UniqueConstraint: accession_number + item_number)
- sec_filings 테이블에 parsed_status / items_json 컬럼 추가
- index_filings() 완료 후 신규 8-K auto-parse 트리거
- GET /filings/events/{ticker}: lazy parse + 조회
- POST /filings/events/parse/bulk: backfill용 일괄 파싱
- FilingSummary에 parsed_status / items 필드 포함
- alembic migration: g8a9b0c1d2e3
- 테스트 22개 추가 (extract_items, strip_ixbrl, find_primary_doc, parse_filing)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 3eb736445b feat: PIT dividend calendar + earnings surprise calendar endpoint
dividend calendar:
- DividendCalendar 모델 (PIT revisioned: as_of_date 컬럼으로 lookahead bias 방지)
- FINRA 5yr 데이터 backfill + yfinance 갱신 지원
- GET /dividends/calendar/{ticker}, POST /dividends/calendar/bulk
- alembic migration: f7a8b9c0d1e2

earnings:
- GET /earnings/calendar/{ticker}: ex-dividend 방식 earnings calendar 제공
- EarningsSurprise 모델에 fiscal_date 인덱스 추가

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 2438c511c7 fix: SEC EDGAR stale 8-K index auto-refresh + HTTP cache bypass
- fetch_json()에 skip_cache 파라미터 추가 (in-memory/disk 캐시 bypass)
- index_filings()에 force_refresh → skip_cache 자동 연동
- search_filings()에 staleness check (MAX indexed_at vs SEC_DATA_REFRESH_HOURS)
  → 24h 이상 stale한 ticker 자동 re-index (per-ticker asyncio.Lock으로 thundering herd 방지)
- search_filings_bulk()도 동일 staleness 처리
- 테스트 7개 추가 (skip_cache 동작, force_refresh 연동)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim 7a003a5360 fix: screener yf.screen() rate limit/401 retry 처리 추가
429/rate limit 및 401/unauthorized 발생 시 최대 3회 재시도 (delay 3s, 6s).
모든 retry 소진 후 RuntimeError로 변환하여 503 응답.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
4 months ago
I Luk Kim c4565159b1 fix: universe service - NASDAQ case bug + OOM prevention
Two fixes to universe snapshot build:

1. SEC EDGAR exchange case mismatch: company_tickers_exchange.json uses
   "Nasdaq" (mixed case) but filter expected "NASDAQ". All NASDAQ-listed
   stocks (AAPL, MSFT, GOOGL, etc.) were silently excluded from registry.
   Fixed with case-insensitive _US_EXCHANGE_MAP lookup + canonical normalization.

2. OOM during large builds: SEC EDGAR companyfacts JSONs accumulate in
   _json_cache without eviction, causing OOM after ~1500-1800 tickers.
   Fixed by clearing _json_cache + _text_cache + gc.collect() every 20
   batches. Memory remains stable throughout full 9,376-ticker build.

Result: 529,328 snapshot rows, 5,570 tickers (NASDAQ:2515, NYSE:2084, OTC:971)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim 24736954bb fix: yfinance threads=False + 배치 30개로 OS 스레드 폭발 방지
threads=True일 때 배치당 50개 OS 스레드 생성 → 시스템 자원 고갈 → API 먹통.
threads=False로 순차 다운로드, 배치 30개로 축소.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim 1b037c9256 fix: full force_rebuild 시 universe_snapshot 전체 삭제
tickers=None (전체 빌드)일 때 registry에서 제거된 stale 티커 데이터도
정리되도록 DELETE FROM universe_snapshot 실행.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim e51e045169 fix: universe build을 isolated thread로 분리하여 API 먹통 방지
BackgroundTask가 FastAPI event loop을 공유해서 deadlock 발생 →
별도 thread에서 새 asyncio event loop으로 실행하도록 변경.
- API event loop 완전 분리
- DB 커넥션 풀 독립적 사용 (per-batch factory session)
- 빌드 중 API 정상 응답 유지

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim 0e048f82ef fix: universe build event loop 차단 방지
- _PRICE_BATCH 100 → 50 (배치당 부하 감소)
- 배치 완료 후 asyncio.sleep(1) 추가 (event loop yield)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim b54ac6d5b7 fix: universe 데이터 품질 개선 — sanity check + preferred stock 필터링
- SEC EDGAR fallback에서 "-" 포함 티커 제외 (preferred stock, BAC-PL 등)
- W/R/Z suffix 티커 제외 (warrant, right, special)
- build_snapshots: close > $1M 또는 shares < 100,000 또는 market_cap > $5T 제외
- screen_historical: market_cap > $5T 쿼리 레벨 필터 추가

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim 5ab1663977 feat: universe discover에 SEC EDGAR fallback 추가
yf.screen() 401 에러 시 SEC EDGAR company_tickers_exchange.json으로 자동 전환.
- 5,848개 NYSE/NASDAQ/AMEX/ARCA 종목 등록 가능
- response에 source 필드 추가 (yfinance / sec_edgar)
- market_cap_min 필터는 yfinance 사용 시에만 적용 (SEC Edgar fallback 시 미적용, 스크리닝 시점에 필터링)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim b3092a0d5e feat: 백테스팅 유니버스 과거 시점 주식 스크리닝 (Historical Stock Universe)
## 새 기능
- GET  /universe/screen — 과거 날짜 기준 시총/섹터/거래소 필터링
- GET  /universe/registry — 추적 종목 목록 조회
- POST /universe/admin/discover — yfinance screener로 US 주식 자동 등록
- POST /universe/admin/build-snapshots — SEC EDGAR × yfinance 월별 시총 스냅샷 생성

## 데이터 모델
- universe_ticker_registry: 종목 마스터 (ticker, name, cik, sector, industry, exchange)
- universe_snapshot: 월별 스냅샷 (ticker, snapshot_date, market_cap, close_price, shares_outstanding)
  - 인덱스: (snapshot_date, market_cap) — 핵심 스크리닝 쿼리 최적화
  - ~4000종목 × 120개월 ≈ 480K 행 예상

## 데이터 흐름
1. SEC EDGAR companyfacts → shares_outstanding (최신, 주가분할 반영)
2. yfinance bulk download 1mo interval → 월별 종가
3. market_cap = latest_shares × close_price (yfinance 분할조정 가격과 일관성)

## 제한사항
- Survivorship bias: 현재 상장 종목만 (상폐 종목 미포함)
- 자사주 매입으로 과거 시총 ~20% 오차 가능 (분할 오차 방지가 주목적)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5 months ago
I Luk Kim e121c7ab40 feat: Earnings Surprise를 yfinance-plus로 전환 (Alpha Vantage 제거)
- yfinance Ticker.earnings_dates에서 EPS Estimate + Reported EPS + Surprise(%) 직접 제공
- Alpha Vantage 의존성 완전 제거 (API 키 불필요, rate limit 없음)
- ~25분기(6년+) 커버리지, 진짜 애널리스트 컨센서스 기반
- AAPL: 12분기 연속 beat, avg +4.36%
- MSFT: 8분기 연속 beat, avg +4.50%
5 months ago
I Luk Kim 99a998b2f1 feat: Earnings Surprise에 Alpha Vantage 애널리스트 추정치 통합
- XBRL reported EPS + Alpha Vantage estimated EPS 합산
- surprise = reported - estimated (진짜 컨센서스 대비)
- fiscal 날짜 ±15일 fuzzy match (Apple 등 비표준 fiscal calendar 대응)
- AV 키 미설정 시 reported EPS만 반환 (graceful degradation)
- AV rate limiter: 5 req/min token bucket
- force_refresh 시 기존 데이터 삭제 후 재인덱싱
5 months ago
I Luk Kim 971c0f053f feat: Earnings Surprise를 SEC XBRL로 전환 + Insider/FINRA 과거 데이터 확장
1. Earnings Surprise: Alpha Vantage → SEC EDGAR XBRL 전환
   - companyfacts API에서 EarningsPerShareDiluted/Basic 추출
   - QoQ surprise 계산 (현재 EPS - 이전 분기 EPS)
   - 15일 이내 중복 분기 제거 (10-Q 우선)
   - force_refresh 시 기존 데이터 삭제 후 재인덱싱
   - API 키 불필요, 2009년~ 커버리지

2. Insider transactions: days max 1095→3650, older pages 3→10

3. FINRA: 이전 커밋에서 이미 days=3650, limit=10000 적용됨
5 months ago