10 Commits (ffaed4fc9d87ac2cfcdd4fa80b7156ee5bf059e6)

Author SHA1 Message Date
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 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 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 2c4b4d583d perf: API 성능 개선 Round 3 — 8개 항목 (P15-P22)
P15: FINRA ingest N+1 쿼리 → chunked batch upsert (on_conflict_do_nothing)
P16: Request log 통계 4개 COUNT 쿼리 → 단일 case() 집계 쿼리
P17: stocks/52-week-gainers (1h), stocks/trending (30m) 캐시 추가
P18: Alpaca bars/data 캐시 TTL None→86400 (과거 불변 데이터)
P19: Request log flush 배치 100→500, 간격 1s→2s
P20: Overlay feature_builder matched_symbols Python 필터 → DB JSONB @> 연산자
P21: with_cache Pydantic 모델 캐시 키에 model_dump_json() 사용
P22: Alpaca price 저장 SELECT+filter → batch upsert (on_conflict_do_nothing)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
5 months ago
I Luk Kim bf6932ca2f Add Alpaca-specific DB table and Redis caching for Alpaca/FINRA endpoints
Separate Alpaca price data into dedicated AlpacaPriceData table to avoid
UniqueConstraint('ticker', 'date') conflicts with Yahoo Finance PriceData.
Add Redis caching (build_cache_key/get_cached_response/set_cached_response)
to 3 Alpaca endpoints and 2 FINRA query endpoints with appropriate TTLs.

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