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>main
parent
e121c7ab40
commit
b3092a0d5e
@ -0,0 +1,65 @@
|
|||||||
|
"""add universe_snapshot tables
|
||||||
|
|
||||||
|
Revision ID: e6f7a8b9c0d1
|
||||||
|
Revises: d5e6f7a8b9c0
|
||||||
|
Create Date: 2026-03-29
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "e6f7a8b9c0d1"
|
||||||
|
down_revision: Union[str, Sequence[str], None] = "d5e6f7a8b9c0"
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
conn = op.get_bind()
|
||||||
|
|
||||||
|
if not conn.dialect.has_table(conn, "universe_ticker_registry"):
|
||||||
|
op.create_table(
|
||||||
|
"universe_ticker_registry",
|
||||||
|
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||||
|
sa.Column("ticker", sa.String(10), nullable=False),
|
||||||
|
sa.Column("name", sa.String(255), nullable=True),
|
||||||
|
sa.Column("cik", sa.String(20), nullable=True),
|
||||||
|
sa.Column("sector", sa.String(100), nullable=True),
|
||||||
|
sa.Column("industry", sa.String(200), nullable=True),
|
||||||
|
sa.Column("exchange", sa.String(20), nullable=True),
|
||||||
|
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
|
||||||
|
sa.Column("created_at", postgresql.TIMESTAMP(timezone=True)),
|
||||||
|
sa.Column("updated_at", postgresql.TIMESTAMP(timezone=True)),
|
||||||
|
sa.UniqueConstraint("ticker", name="uq_universe_ticker_registry"),
|
||||||
|
)
|
||||||
|
op.create_index("idx_registry_ticker", "universe_ticker_registry", ["ticker"])
|
||||||
|
op.create_index("idx_registry_sector", "universe_ticker_registry", ["sector"])
|
||||||
|
op.create_index("idx_registry_exchange", "universe_ticker_registry", ["exchange"])
|
||||||
|
op.create_index("idx_registry_active", "universe_ticker_registry", ["is_active"])
|
||||||
|
|
||||||
|
if not conn.dialect.has_table(conn, "universe_snapshot"):
|
||||||
|
op.create_table(
|
||||||
|
"universe_snapshot",
|
||||||
|
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||||
|
sa.Column("ticker", sa.String(10), nullable=False),
|
||||||
|
sa.Column("snapshot_date", postgresql.TIMESTAMP(timezone=True), nullable=False),
|
||||||
|
sa.Column("close_price", sa.Float(), nullable=True),
|
||||||
|
sa.Column("shares_outstanding", sa.Float(), nullable=True),
|
||||||
|
sa.Column("market_cap", sa.Float(), nullable=True),
|
||||||
|
sa.Column("sector", sa.String(100), nullable=True),
|
||||||
|
sa.Column("industry", sa.String(200), nullable=True),
|
||||||
|
sa.Column("exchange", sa.String(20), nullable=True),
|
||||||
|
sa.Column("created_at", postgresql.TIMESTAMP(timezone=True)),
|
||||||
|
sa.UniqueConstraint("ticker", "snapshot_date", name="uq_universe_snapshot"),
|
||||||
|
)
|
||||||
|
op.create_index("idx_snapshot_ticker_date", "universe_snapshot", ["ticker", "snapshot_date"])
|
||||||
|
op.create_index("idx_snapshot_date_mcap", "universe_snapshot", ["snapshot_date", "market_cap"])
|
||||||
|
op.create_index("idx_snapshot_sector", "universe_snapshot", ["sector"])
|
||||||
|
op.create_index("idx_snapshot_date", "universe_snapshot", ["snapshot_date"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("universe_snapshot")
|
||||||
|
op.drop_table("universe_ticker_registry")
|
||||||
@ -0,0 +1,64 @@
|
|||||||
|
"""
|
||||||
|
Universe Snapshot models for historical stock screening (backtesting universe)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from sqlalchemy import Column, String, Float, Index, UniqueConstraint, Boolean
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID, TIMESTAMP
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from app.core.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class UniverseTickerRegistry(Base):
|
||||||
|
__tablename__ = "universe_ticker_registry"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
ticker = Column(String(10), nullable=False)
|
||||||
|
name = Column(String(255), nullable=True)
|
||||||
|
cik = Column(String(20), nullable=True)
|
||||||
|
sector = Column(String(100), nullable=True)
|
||||||
|
industry = Column(String(200), nullable=True)
|
||||||
|
exchange = Column(String(20), nullable=True)
|
||||||
|
is_active = Column(Boolean, default=True, nullable=False)
|
||||||
|
created_at = Column(
|
||||||
|
TIMESTAMP(timezone=True), default=lambda: datetime.now(timezone.utc)
|
||||||
|
)
|
||||||
|
updated_at = Column(
|
||||||
|
TIMESTAMP(timezone=True),
|
||||||
|
default=lambda: datetime.now(timezone.utc),
|
||||||
|
onupdate=lambda: datetime.now(timezone.utc),
|
||||||
|
)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("ticker", name="uq_universe_ticker_registry"),
|
||||||
|
Index("idx_registry_ticker", "ticker"),
|
||||||
|
Index("idx_registry_sector", "sector"),
|
||||||
|
Index("idx_registry_exchange", "exchange"),
|
||||||
|
Index("idx_registry_active", "is_active"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class UniverseSnapshot(Base):
|
||||||
|
__tablename__ = "universe_snapshot"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
ticker = Column(String(10), nullable=False, index=True)
|
||||||
|
snapshot_date = Column(TIMESTAMP(timezone=True), nullable=False)
|
||||||
|
close_price = Column(Float, nullable=True)
|
||||||
|
shares_outstanding = Column(Float, nullable=True)
|
||||||
|
market_cap = Column(Float, nullable=True)
|
||||||
|
sector = Column(String(100), nullable=True)
|
||||||
|
industry = Column(String(200), nullable=True)
|
||||||
|
exchange = Column(String(20), nullable=True)
|
||||||
|
created_at = Column(
|
||||||
|
TIMESTAMP(timezone=True), default=lambda: datetime.now(timezone.utc)
|
||||||
|
)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("ticker", "snapshot_date", name="uq_universe_snapshot"),
|
||||||
|
Index("idx_snapshot_ticker_date", "ticker", "snapshot_date"),
|
||||||
|
Index("idx_snapshot_date_mcap", "snapshot_date", "market_cap"),
|
||||||
|
Index("idx_snapshot_sector", "sector"),
|
||||||
|
Index("idx_snapshot_date", "snapshot_date"),
|
||||||
|
)
|
||||||
@ -0,0 +1,66 @@
|
|||||||
|
"""
|
||||||
|
Universe screening schemas for backtesting universe construction
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class UniverseSnapshotItem(BaseModel):
|
||||||
|
ticker: str
|
||||||
|
name: Optional[str] = None
|
||||||
|
market_cap: Optional[float] = None
|
||||||
|
close_price: Optional[float] = None
|
||||||
|
shares_outstanding: Optional[float] = None
|
||||||
|
sector: Optional[str] = None
|
||||||
|
industry: Optional[str] = None
|
||||||
|
exchange: Optional[str] = None
|
||||||
|
snapshot_date: Optional[datetime] = None
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
|
||||||
|
class UniverseScreenResponse(BaseModel):
|
||||||
|
stocks: List[UniverseSnapshotItem]
|
||||||
|
total_count: int
|
||||||
|
page: int
|
||||||
|
page_size: int
|
||||||
|
total_pages: int
|
||||||
|
snapshot_date: Optional[str] = None
|
||||||
|
filters_applied: Dict[str, Any] = {}
|
||||||
|
metadata: Dict[str, Any] = {}
|
||||||
|
|
||||||
|
|
||||||
|
class TickerRegistryItem(BaseModel):
|
||||||
|
ticker: str
|
||||||
|
name: Optional[str] = None
|
||||||
|
sector: Optional[str] = None
|
||||||
|
industry: Optional[str] = None
|
||||||
|
exchange: Optional[str] = None
|
||||||
|
cik: Optional[str] = None
|
||||||
|
is_active: bool = True
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
|
||||||
|
class RegistryResponse(BaseModel):
|
||||||
|
tickers: List[TickerRegistryItem]
|
||||||
|
total_count: int
|
||||||
|
page: int
|
||||||
|
page_size: int
|
||||||
|
total_pages: int
|
||||||
|
|
||||||
|
|
||||||
|
class SnapshotBuildRequest(BaseModel):
|
||||||
|
tickers: Optional[List[str]] = Field(
|
||||||
|
None,
|
||||||
|
description="Specific tickers to build. Omit for all registry tickers.",
|
||||||
|
)
|
||||||
|
start_date: str = Field(..., description="Start date YYYY-MM-DD (e.g. 2015-01-01)")
|
||||||
|
end_date: str = Field(..., description="End date YYYY-MM-DD (e.g. 2025-12-01)")
|
||||||
|
force_rebuild: bool = Field(
|
||||||
|
False,
|
||||||
|
description="Delete existing snapshots for these tickers before rebuilding",
|
||||||
|
)
|
||||||
Loading…
Reference in New Issue