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>
Same get_or_fetch_multi_bars() approach as daily bars:
- stores intraday rows in AlpacaPriceData (full timestamp as PK component)
- subsequent requests for historical periods served from DB
- same-day requests during market hours always hit Alpaca (max_date < end_dt)
- force_refresh=true bypasses DB check
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- 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>
- 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>
- 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>
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>
- 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>
429/rate limit 및 401/unauthorized 발생 시 최대 3회 재시도 (delay 3s, 6s).
모든 retry 소진 후 RuntimeError로 변환하여 503 응답.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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>
asyncpg 커넥션은 event loop에 바인딩됨. API의 AsyncSessionLocal을
다른 loop에서 사용하면 'Future attached to a different loop' 오류 발생.
→ build thread 내에서 전용 engine + session factory 생성.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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>
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>
## 새 기능
- 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>
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 적용됨
F1: SEC Form 4 내부자 거래 (insider transactions)
- GET /insider/transactions/{symbol} — Form 4 거래 내역 조회
- GET /insider/summary/{symbol} — 3/6/12개월 매수/매도 집계
- SEC EDGAR submissions JSON → Form 4 XML 파싱 → DB 저장
- 자동 인덱싱 (첫 조회 시 SEC에서 페치)
- joint filing, derivative/non-derivative 거래 모두 지원
F2: Earnings Surprise (Alpha Vantage)
- GET /earnings/surprise/{symbol} — 분기별 EPS surprise
- reported EPS vs estimated EPS, beat/miss streak 계산
- ALPHA_VANTAGE_API_KEY 환경변수 필요 (무료 tier: 25 req/day)
- DB 캐싱으로 반복 호출 시 API 절약
F3: FINRA Short Volume 확장
- days 파라미터: max 365 → 3650 (10년)
- limit 파라미터: max 1000 → 10000
- 5년치 백필 완료 반영
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- docs/DATA_COVERAGE.md 신규 생성: 엔드포인트별 실제 DB 보유 범위,
이론적 최대 범위, 백필 방법, SQL 확인 쿼리 포함
- FINRA/Alpaca/stocks/filings 엔드포인트 description에 데이터 범위 및
백필 방법 안내 추가 (Swagger UI에 표시됨)
현재 백필 필요 항목:
- FINRA: 2026-02-10~ 28거래일만 존재 → 2025년치 백필 권장
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- CHANGELOG: v3.0.2 (Attention 서브시스템), v3.0.3 (ETF as_of_date 버그 수정) 항목 추가
- README: ETF Holdings 섹션에 정확한 날짜 매칭 / stale 방지 설명 추가
- README: Attention 서브시스템 Features 및 Available Endpoints 섹션 추가
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- _load_snapshot_holdings(): DB 캐시 스냅샷이 as_of_date와 120일 초과
차이나면 stale로 판단하고 None 반환 → SEC 신규 fetch 트리거
- _find_best_filing_and_xml(): eligible 필터에 365일 하한 추가,
target_date 기준 1년 이내 파일링만 우선 후보로 사용
(하한 내 후보 없으면 기존 전체 검색 fallback 유지)
수정 전: SPY?as_of_date=2021-06-30 → 2019-11-18 (19개월 stale)
수정 후: SPY?as_of_date=2021-06-30 → 2021-05-28 (정상)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
period=None으로 history() 호출 시 발생하던
AttributeError: 'NoneType' object has no attribute 'lower' 수정.
upstream 변경사항:
- HistoricalDataCache.get/store/normalize에 period=None 가드 추가
- start/end 날짜 범위 요청 시 불필요한 pickle 캐시 시도 제거
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
## Overlay 버그 수정
- **collect_all 동시성 오류**: asyncio.gather로 공유 DB 세션에 동시 접근 → SQLAlchemy 오류
발생. 어댑터를 순차 실행으로 변경
- **feedparser/apscheduler/pytrends 미설치**: Docker 이미지 재빌드로 패키지 영구 포함
- **중복 job log 항목**: _log_job이 매번 새 행 삽입 → running+completed 중복 생성.
기존 running 행을 업데이트하도록 수정
- **admin/health 잘못된 job_type**: yahoo_rss/wikimedia 등 존재하지 않는 타입 조회.
실제 로깅되는 collect_all/feature_build만 조회하도록 수정
- **source_presence 항상 false**: z-score가 계산 불가능하면(2일 미만 데이터) source가
false로 표시됨. 실제 데이터 존재 여부(headline_count_24h > 0 등)로 판단하도록 수정
- **top-movers 심볼 중복**: 파이프라인 실행 횟수만큼 같은 심볼 반복 출력.
심볼별 최신 레코드만 조회하는 서브쿼리로 수정
- **YouTube None 곱셈 오류**: view_count * channel_weight에서 None이면 TypeError.
(or 0) / (or 0.5) 가드 추가
## Trends 기능 수정
- **ThemeTopicMap 자동 시딩**: 파이프라인 최초 실행 시 TOP_50_SYMBOLS에 대한
기본 topic 매핑 자동 생성
- **GOOGLE_TRENDS_ENABLED=true**: docker-compose.yml에 환경변수 추가
- **theme_heat_z 항상 null**: feature_builder에 build_trends_features() 메서드
누락 → OverlayTrendObservation 데이터가 점수에 반영 안 됨. 메서드 추가 및 연결
- **POST /admin/seed-topics**: ThemeTopicMap 수동 시딩용 admin 엔드포인트 추가
## OpenAPI 문서 개선
- 모든 엔드포인트에 summary/description 추가 (filings, news, database, etf, stocks,
screener, fred, attention, overlay)
- Pydantic 스키마에 json_schema_extra example 추가 (attention, filing)
- 누락된 태그 6개 추가 (attention, attention-admin, database, fred, error-logs,
request-logs)
- 루트(/) 랜딩 페이지를 Swagger UI로 리다이렉트로 교체
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
하드코딩된 330줄 HTML을 제거하고 request.app.openapi()에서
동적으로 엔드포인트 목록을 렌더링하도록 변경.
새 라우터 추가 시 / 페이지를 별도로 수정할 필요 없음.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
## 주요 기능
- Entity resolver: ticker → canonical name → Wikipedia 매칭
- SEC company_tickers.json fallback으로 placeholder name 자동 수정
- all-caps SEC 이름 title-case 변환, "Com" suffix 처리
- Wikipedia 페이지뷰 수집 + spike_10d / zscore_20d 피처 계산
- GDELT V2 DOC API 뉴스 기사 수집 (2017-01-01 이후)
## GDELT rate limit 제약 강제
- /event/{ticker} 온디맨드 GDELT 수집 제거 (IP ban 방지)
- 프로세스 전역 asyncio.Lock + 10초 최소 간격 강제
- 429 시 exponential backoff (30→60→120s)
- news.gdelt_status 필드로 클라이언트에 수집 상태 명시
('collected' | 'not_collected' | 'not_available')
## API
- GET /api/v1/attention/event/{ticker}?event_date=YYYY-MM-DD
- GET /api/v1/attention/entity/{ticker}
- POST /api/v1/attention/admin/resolve/{ticker}
- POST /api/v1/attention/admin/collect/wiki/{ticker}
- POST /api/v1/attention/admin/collect/gdelt/{ticker} ← scheduler 전용
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
content.read()로 body를 읽은 후 resp.get_encoding() 호출 시
aiohttp 내부 self._body(None) 접근으로 예외 발생.
이 예외가 except Exception에 잡혀 6번 retry + 지수 backoff(최대 ~22초)
→ asyncio.wait_for 캔슬 → TimeoutError → 504.
Content-Type 헤더에서 charset 직접 파싱으로 교체.
기본값 utf-8, SEC는 대부분 charset 미지정이므로 실질적으로 항상 utf-8 사용.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
index 페이지 + exhibit 두 단계를 15초에 커버하기엔 너무 빡빡함.
미캐시 시 index fetch 최대 8초 + exhibit fetch 최대 12초 = 최악 20초.
max_bytes 수정으로 메모리 고갈은 이미 해결되었으므로
deadline은 25초로 조정 (원래 30초보다 5초 단축).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- fetch_text에 max_bytes 파라미터 추가: Content-Length 헤더로 다운로드 전 사전 reject,
헤더 없으면 content.read(max_bytes+1)로 제한적 읽기
- ValueError는 즉시 raise (retry 없음 — 크기는 재시도해도 안 줄어듦)
- in-memory 캐시(_text_cache) 1MB 가드: 대형 응답은 디스크 캐시에만 저장
- MAX_EXHIBIT_SIZE 1MB → 5MB, fetch_text(max_bytes=...) 호출로 다운로드 전 체크
- exhibit deadline 30초 → 15초 (서비스 + 엔드포인트 + bulk)
- 신규 테스트 5개: Content-Length 사전 거부, body 제한 읽기, 메모리 캐시 가드,
소형 캐시 유지, ValueError no-retry
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- SECHttpClient._deadline(인스턴스 변수) → contextvars.ContextVar로 교체
asyncio task별 독립 데드라인으로 싱글턴 공유로 인한 레이스 컨디션 해결
- bulk exhibit에 Semaphore(4) + 전체 300s 타임아웃 추가
동시 50개 코루틴이 Semaphore(2)를 무제한 점유하던 문제 해결
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- sec_filings_service: 루프 전 accession_number 일괄 pre-fetch로 N+1 제거
- sec_filings_service: 500건 단위 청크 커밋으로 all-or-nothing 트랜잭션 방지
- sec_filings_service: bulk 인덱싱 시 코루틴별 독립 세션 생성으로 동시 세션 충돌 해결
- sec_filings_service: index_filings 데드라인 60s → 120s, bulk timeout 동일 적용
- sec_http_client: _TokenBucket(10 req/sec) 추가로 SEC EDGAR 과부하 방지
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- README/API_DOCUMENTATION에 `just run dev` 개발 서버 실행 방법 추가
- `GET /stocks/index/{index_name}` 엔드포인트 문서화 (sp500/nasdaq100)
- justfile을 프로젝트 파일로 문서에 포함
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
GET /stocks/index/{index_name} 엔드포인트 추가.
sp500/nasdaq100 구성 종목을 Wikipedia에서 실시간 파싱하여 반환.
24시간 Redis 캐시 및 30초 타임아웃 적용.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>