Files
auto-stock/backend/alembic/versions/0002_add_performance_indexes.py
shuim 5f0f839039 전략 취약점 15건 수정 (코드 리뷰 기반)
## CRITICAL/HIGH (S1-S8)
- S1: Aggressive 모드 %B 스케일링 캡 1.3 (BB 중앙선 위 매수 방지)
- S2: ML scaler train-only fit (데이터 누수 제거)
- S3: SIDEWAYS = ADX<20 AND slope≈0 (트렌드 초기 차단 해소)
- S4: EOD 청산 실패 시 재시도 + CRITICAL 로그
- S5: 일일 손실 한도에 미실현 P&L 포함
- S6: trailing stop 고점 매 사이클 갱신
- S7: 섹터 필터 미매핑 종목 "기타" 분류 (max 3 적용)
- S8: 스캐너 RSI 기준 25→46, BB 점수 -3%~+1.5% 구간

## MEDIUM (M1-M7)
- M1: 스캐너 최소 거래량 100만→10만주
- M2: ADX 히스테리시스 18/22 (국면 플리핑 방지)
- M3: 분할매도 최소 수익 1.0%→0.5%
- M4: ORB 갭 필터 4% + 레인지 폭 0.3% 최소
- M5: 쿨다운 스트릭 부분매도 시 미변경
- M6: MDD 강제매도 loss_tracker 기록 제거 (허위 ban 방지)
- M7: RSI Wilder 스무딩으로 통일

## 인프라/보안
- 인증 누락 엔드포인트 수정 (analysis, journals)
- nginx 보안 헤더 location 블록 누락 수정
- Alembic 마이그레이션 IF NOT EXISTS 가드 추가
- SellRequest/UsOrderRequest 입력 검증 강화
- 차트 네이버 폴백 추가 (DB 데이터 없을 때)
- 서버 이전 시 자동 DB 마이그레이션 + KRX 초기 수집
- CLAUDE.md 섹션 5.1 백테스트 값 동기화 (4%→6%, -6%→-7%)
- MAX_SWING_POSITIONS 25→20 (CLAUDE.md 준수)
- mdd_manager failed_count에서 skip 종목 제외

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 11:44:14 +09:00

74 lines
4.2 KiB
Python

"""add performance indexes
쿼리 성능 향상을 위한 복합 인덱스 추가.
자주 사용되는 필터 및 조회 패턴에 맞춰 인덱스를 생성합니다.
Revision ID: 0002
Revises: 0001
Create Date: 2026-03-10
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "0002"
down_revision: Union[str, None] = "0001"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def _safe_create_index(table, index_name, columns):
"""인덱스가 이미 존재하면 스킵."""
conn = op.get_bind()
result = conn.execute(sa.text(
"SELECT 1 FROM pg_indexes WHERE tablename=:t AND indexname=:i"
), {"t": table, "i": index_name})
if not result.fetchone():
op.create_index(index_name, table, columns)
def upgrade() -> None:
_safe_create_index("trade_history", "ix_trade_history_status_created_at", ["status", "created_at"])
_safe_create_index("trade_history", "ix_trade_history_stock_order_created", ["stock_code", "order_type", "created_at"])
_safe_create_index("market_data", "ix_market_data_stock_code_timestamp", ["stock_code", "timestamp"])
_safe_create_index("stock_analysis", "ix_stock_analysis_stock_code_analysis_date", ["stock_code", "analysis_date"])
_safe_create_index("portfolio", "ix_portfolio_quantity", ["quantity"])
_safe_create_index("active_trades", "ix_active_trades_stock_code_status", ["stock_code", "status"])
_safe_create_index("active_trades", "ix_active_trades_status", ["status"])
_safe_create_index("watchlist_stocks", "ix_watchlist_stocks_is_active_stock_code", ["is_active", "stock_code"])
_safe_create_index("claude_analysis_log", "ix_claude_analysis_log_stock_code_created_at", ["stock_code", "created_at"])
def downgrade() -> None:
# ── claude_analysis_log ───────────────────────────────────────────────
with op.batch_alter_table("claude_analysis_log", schema=None) as batch_op:
batch_op.drop_index("ix_claude_analysis_log_stock_code_created_at")
# ── watchlist_stocks ──────────────────────────────────────────────────
with op.batch_alter_table("watchlist_stocks", schema=None) as batch_op:
batch_op.drop_index("ix_watchlist_stocks_is_active_stock_code")
# ── active_trades ─────────────────────────────────────────────────────
with op.batch_alter_table("active_trades", schema=None) as batch_op:
batch_op.drop_index("ix_active_trades_status")
batch_op.drop_index("ix_active_trades_stock_code_status")
# ── portfolio ─────────────────────────────────────────────────────────
with op.batch_alter_table("portfolio", schema=None) as batch_op:
batch_op.drop_index("ix_portfolio_quantity")
# ── stock_analysis ────────────────────────────────────────────────────
with op.batch_alter_table("stock_analysis", schema=None) as batch_op:
batch_op.drop_index("ix_stock_analysis_stock_code_analysis_date")
# ── market_data ───────────────────────────────────────────────────────
with op.batch_alter_table("market_data", schema=None) as batch_op:
batch_op.drop_index("ix_market_data_stock_code_timestamp")
# ── trade_history ─────────────────────────────────────────────────────
with op.batch_alter_table("trade_history", schema=None) as batch_op:
batch_op.drop_index("ix_trade_history_stock_order_created")
batch_op.drop_index("ix_trade_history_status_created_at")