#!/usr/bin/env python3 """ 매매 규칙 설정을 데이터베이스에 로드하는 스크립트 Usage: python load_trading_rules.py """ import asyncio import json from pathlib import Path from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from sqlalchemy import select from app.core.config import settings from app.models.models import TradingRule async def load_trading_rules(): """trading_rules_config.json 파일을 읽어서 데이터베이스에 저장""" # 설정 파일 읽기 config_path = Path(__file__).parent / "trading_rules_config.json" if not config_path.exists(): print(f"❌ 설정 파일을 찾을 수 없습니다: {config_path}") return with open(config_path, "r", encoding="utf-8") as f: config = json.load(f) # 데이터베이스 연결 engine = create_async_engine(settings.DATABASE_URL, echo=True) async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async with async_session() as session: print("\n📋 매매 규칙 로드 중...\n") # 기존 규칙 삭제 (선택적) result = await session.execute(select(TradingRule)) existing_rules = result.scalars().all() if existing_rules: print(f"⚠️ 기존 규칙 {len(existing_rules)}개 발견") response = input("기존 규칙을 모두 삭제하고 새로 로드하시겠습니까? (y/N): ") if response.lower() == 'y': for rule in existing_rules: await session.delete(rule) await session.commit() print("✅ 기존 규칙 삭제 완료\n") # 새 규칙 추가 rules = config.get("rules", []) for idx, rule_data in enumerate(rules, 1): trading_rule = TradingRule( name=rule_data["name"], description=rule_data.get("description", ""), rule_type=rule_data["rule_type"], conditions=rule_data["conditions"], actions=rule_data["actions"], is_active=rule_data.get("is_active", True), priority=rule_data.get("priority", idx) ) session.add(trading_rule) print(f"✅ [{idx}/{len(rules)}] {rule_data['name']} - {'활성화' if rule_data.get('is_active') else '비활성화'}") await session.commit() print(f"\n🎉 총 {len(rules)}개의 매매 규칙이 로드되었습니다!") # 포트폴리오 제약 조건 및 리스크 관리 설정 출력 print("\n" + "="*60) print("📊 포트폴리오 제약 조건:") print("="*60) for key, value in config.get("portfolio_constraints", {}).items(): if isinstance(value, float): print(f" • {key}: {value*100:.1f}%" if value < 1 else f" • {key}: {value:,.0f}") else: print(f" • {key}: {value}") print("\n" + "="*60) print("⚠️ 리스크 관리:") print("="*60) for key, value in config.get("risk_management", {}).items(): if isinstance(value, float) and value < 1: print(f" • {key}: {value*100:.1f}%") else: print(f" • {key}: {value}") print("\n" + "="*60) print("✅ 설정 로드 완료!") print("="*60) await engine.dispose() if __name__ == "__main__": asyncio.run(load_trading_rules())