수개월간 매수 0건 + 백테스트가 손실로 보이던 근본 원인들을 수정. - ADX 발산(mean_reversion_strategy, run_backtest): Wilder 평활에 /period 누락으로 ADX가 100 초과 발산 → 실서비스 SIDEWAYS 게이트(ADX<20) 영구 무력화. 공식 복원(표준 Wilder와 대수적으로 동일 검증). - 백테스트 워밍업(run_backtest): 국면판정 220봉을 start_date부터 세서 14개월 미만 백테스트의 ~90%가 강제 BEAR → 가짜 손실. start_date 340일 전부터 프리로드하고 성과는 sim_start_date부터만 집계. CAGR 분모도 워밍업 제외한 실제 거래일로 수정. → 최근1년 -0.33%→+6.95%, 가산성 회복. - ML HOLD 게이트(trade_executor): 신뢰도 무관 매수 차단 → 데이터 부족으로 ML이 실패(conf=0)한 HOLD까지 모든 매수를 막던 것을 conf>=0.6 조건부로. - 빈 Redis 추천 캐시(swing/scheduler): 빈 캐시를 '히트'로 처리해 DB 폴백을 건너뛰던 것을 recommendations_by_rule 비면 DB 폴백하도록. - alembic 로깅(env.py, main.py): lifespan의 alembic upgrade가 fileConfig로 앱 로거를 꺼 startup 이후 로그 전멸 → 스킵(스키마는 create_all 담당). 검증: code-verifier 통과(실전 경로 CONFIRMED 버그 없음), walk-forward 6/9구간 양(+)·과적합 아님(조건부 견고). 서바이버십 편향은 별도 이슈로 검증 진행 중. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HBmzf1HDnvFHLraJ8eaaKJ
90 lines
3.4 KiB
Python
90 lines
3.4 KiB
Python
"""Alembic 환경 설정 (async / asyncpg)
|
|
|
|
- settings.DATABASE_URL 에서 연결 문자열을 읽어 동기 드라이버(psycopg2) URL 로 변환
|
|
- 모델 메타데이터를 임포트해 autogenerate 지원
|
|
"""
|
|
import asyncio
|
|
from logging.config import fileConfig
|
|
|
|
from sqlalchemy import pool
|
|
from sqlalchemy.engine import Connection
|
|
from sqlalchemy.ext.asyncio import async_engine_from_config
|
|
|
|
from alembic import context
|
|
|
|
# ── 프로젝트 루트를 sys.path 에 추가 (alembic.ini prepend_sys_path = .) ───────
|
|
import sys
|
|
import os
|
|
|
|
# backend/ 가 작업 디렉토리이므로 app 패키지를 바로 임포트 가능
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
|
|
|
from app.core.config import settings
|
|
from app.core.database import Base
|
|
|
|
# 모든 모델 임포트 — autogenerate 가 테이블을 인식하도록
|
|
import app.models.models # noqa: F401
|
|
|
|
# ── alembic.ini 로거 설정 ─────────────────────────────────────────────────────
|
|
# [FIX] disable_existing_loggers=False: 앱 내(main.py lifespan)에서 alembic upgrade를
|
|
# 호출할 때 fileConfig가 기본값(True)으로 앱의 모든 로거를 비활성화해 startup 이후
|
|
# 로그가 전멸하는 문제 방지. CLI 단독 실행 시에도 무해.
|
|
config = context.config
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name, disable_existing_loggers=False)
|
|
|
|
# ── DB URL: asyncpg → psycopg2 (Alembic 동기 드라이버용) ────────────────────
|
|
_db_url = settings.DATABASE_URL
|
|
if "+asyncpg" in _db_url:
|
|
_db_url = _db_url.replace("+asyncpg", "")
|
|
elif _db_url.startswith("postgresql://"):
|
|
pass # already sync-compatible
|
|
config.set_main_option("sqlalchemy.url", _db_url)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
# ── 오프라인 마이그레이션 ─────────────────────────────────────────────────────
|
|
def run_migrations_offline() -> None:
|
|
url = config.get_main_option("sqlalchemy.url")
|
|
context.configure(
|
|
url=url,
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
# ── 온라인 마이그레이션 (async) ───────────────────────────────────────────────
|
|
def do_run_migrations(connection: Connection) -> None:
|
|
context.configure(connection=connection, target_metadata=target_metadata)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
async def run_async_migrations() -> None:
|
|
_async_url = settings.DATABASE_URL
|
|
if not "+asyncpg" in _async_url:
|
|
_async_url = _async_url.replace("postgresql://", "postgresql+asyncpg://")
|
|
|
|
connectable = async_engine_from_config(
|
|
{"sqlalchemy.url": _async_url},
|
|
prefix="sqlalchemy.",
|
|
poolclass=pool.NullPool,
|
|
)
|
|
async with connectable.connect() as connection:
|
|
await connection.run_sync(do_run_migrations)
|
|
await connectable.dispose()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
asyncio.run(run_async_migrations())
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|