Files
auto-stock/backend/alembic/versions/0004_add_us_stock_support.py
shuim de7921d270 fix: CRITICAL/HIGH 버그 30건 수정 + 전체 코드 주석 추가 + 중복 정리
## CRITICAL 수정 (20건)
- day_trading: global 선언 누락, loss_tracker 연동, ban 체크 추가
- trade_executor: BUY 체결가 order_price로 수정, remaining_pct 누적 계산
- risk_validator: get_current_price dict 파싱, MAX_POSITION_SIZE 동기화, DB 세션 누수
- risk_management/recommendations: date.today() → KST 변환
- mdd_manager: Lock 밖 executed_key 참조 수정
- correlation_filter: output → output2 키 수정
- portfolio: 해외 종목 USD/KRW 환율 적용 분리
- Sharpe Ratio 거래빈도 기반 연간화
- telegram_notifier: send_message() 공개 래퍼 추가
- position_manager: 앱 재시작 시 DB 포지션 복원
- swing exit_service: remaining_pct 조건 범위 수정
- run_backtest: original_qty 기반 remaining_pct 계산
- us_market_schedule: 2027년 미국 공휴일 추가
- Login.tsx: res.ok 검증 추가
- mean_reversion_strategy: RSI 로그 하드코딩 수정

## HIGH 수정 (10건)
- db_worker: DLQ 파일 백업 메커니즘 추가
- korea_investment_api: 만료 토큰 임의 연장 제거
- market_data: chart_cache 최대 100개 + TTL 만료
- main.py: rate_limit_store 1시간 미접근 IP 정리
- recommendations: fire-and-forget try/except 추가
- swing/scheduler: DB 세션 3개 분리
- Dashboard: wsMessages 전체 순회
- Layout: /health 엔드포인트 + 30초 폴링
- ml_ensemble: POST /train require_api_key 추가
- day_trading: record_trade_result_safe() 전환

## 코드 정리
- 프론트엔드: isUsStock, formatTime 공통 유틸 추출
- 백엔드: dead code 제거, 중복 import 통합
- MCP: JSON 파싱 헬퍼 추출 (~60줄 감소)
- 전체 ~100개 파일 한국어 주석 추가
- 테스트 13건 코드 기준 수정 (468 passed)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 16:05:41 +09:00

154 lines
6.0 KiB
Python

"""add US stock trading support
미국 주식 매매 지원을 위한 스키마 확장.
- portfolio, trade_history, active_trades에 currency_code, exchange_code 컬럼 추가
- trade_history에 fx_rate(체결 시점 환율) 컬럼 추가
- exchange_rates 환율 이력 테이블 생성
- us_stock_universe 미국 종목 유니버스 테이블 생성
Revision ID: 0004
Revises: 0003
Create Date: 2026-03-10
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect as sa_inspect
revision: str = "0004"
down_revision: Union[str, None] = "0003"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ── portfolio: currency_code, exchange_code 추가 ──────────────────────
with op.batch_alter_table("portfolio", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"currency_code",
sa.String(3),
nullable=False,
server_default="KRW",
)
)
batch_op.add_column(
sa.Column(
"exchange_code",
sa.String(10),
nullable=True,
)
)
batch_op.create_index(
"ix_portfolio_currency_code",
["currency_code"],
)
# ── trade_history: currency_code, exchange_code, fx_rate 추가 ────────
with op.batch_alter_table("trade_history", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"currency_code",
sa.String(3),
nullable=False,
server_default="KRW",
)
)
batch_op.add_column(
sa.Column(
"exchange_code",
sa.String(10),
nullable=True,
)
)
batch_op.add_column(
sa.Column(
"fx_rate",
sa.Numeric(10, 4),
nullable=True,
)
)
batch_op.create_index(
"ix_trade_history_currency_code",
["currency_code"],
)
# ── active_trades: currency_code, exchange_code 추가 ─────────────────
with op.batch_alter_table("active_trades", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"currency_code",
sa.String(3),
nullable=False,
server_default="KRW",
)
)
batch_op.add_column(
sa.Column(
"exchange_code",
sa.String(10),
nullable=True,
)
)
batch_op.create_index(
"ix_active_trades_currency_code",
["currency_code"],
)
# ── exchange_rates 테이블 생성 (이미 존재하면 스킵) ────────────────────
bind = op.get_bind()
inspector = sa_inspect(bind)
existing_tables = inspector.get_table_names()
if "exchange_rates" not in existing_tables:
op.create_table(
"exchange_rates",
sa.Column("id", sa.Integer, primary_key=True, index=True),
sa.Column("currency_pair", sa.String(7), nullable=False, index=True),
sa.Column("rate", sa.Numeric(12, 4), nullable=False),
sa.Column("source", sa.String(50), server_default="KIS"),
sa.Column("recorded_at", sa.DateTime, server_default=sa.func.now(), index=True),
)
# ── us_stock_universe 테이블 생성 (이미 존재하면 스킵) ─────────────────
if "us_stock_universe" not in existing_tables:
op.create_table(
"us_stock_universe",
sa.Column("id", sa.Integer, primary_key=True, index=True),
sa.Column("ticker", sa.String(10), nullable=False, index=True),
sa.Column("company_name", sa.String(200), nullable=False),
sa.Column("exchange", sa.String(10), nullable=False),
sa.Column("sector", sa.String(100), nullable=True),
sa.Column("market_cap", sa.BigInteger, nullable=True),
sa.Column("is_active", sa.Boolean, server_default=sa.text("true"), index=True),
sa.Column("updated_at", sa.DateTime, server_default=sa.func.now()),
sa.UniqueConstraint("ticker", name="uq_us_ticker"),
)
def downgrade() -> None:
# ── 테이블 삭제 ──────────────────────────────────────────────────────
op.drop_table("us_stock_universe")
op.drop_table("exchange_rates")
# ── active_trades 롤백 ───────────────────────────────────────────────
with op.batch_alter_table("active_trades", schema=None) as batch_op:
batch_op.drop_index("ix_active_trades_currency_code")
batch_op.drop_column("exchange_code")
batch_op.drop_column("currency_code")
# ── trade_history 롤백 ───────────────────────────────────────────────
with op.batch_alter_table("trade_history", schema=None) as batch_op:
batch_op.drop_index("ix_trade_history_currency_code")
batch_op.drop_column("fx_rate")
batch_op.drop_column("exchange_code")
batch_op.drop_column("currency_code")
# ── portfolio 롤백 ───────────────────────────────────────────────────
with op.batch_alter_table("portfolio", schema=None) as batch_op:
batch_op.drop_index("ix_portfolio_currency_code")
batch_op.drop_column("exchange_code")
batch_op.drop_column("currency_code")