Files
kis_bot/kis_trader/backtest/optuna_search_space.py
Your Name fc27e726f9 feat: 새로운 안전 규칙 및 최적화 적용을 통한 트레이딩 시스템 개선
변경 사항 (Changes):

구문 오류(Syntax error) 및 토큰 낭비를 방지하기 위해 에이전트 쉘(Agent shell)과 파이썬 코드 스니펫에 다수의 신규 안전 규칙(Safety rules)을 추가함.

스키마 검증 및 적절한 SQL 포맷팅을 보장하기 위해 임시(Ad-hoc) 데이터베이스 쿼리 작성 가이드라인을 도입함.

코드 수정 후 UI 기능이 정상 작동하는지 확인하기 위해, 백테스트 웹 서비스 재시작 및 브라우저 검증에 대한 새로운 규칙을 구현함.

시스템 전반의 무결성(Integrity)을 유지하기 위해 실전 매매(Live trading), 웹 백테스팅, 파라미터 탐색(Parameter searches) 간의 일관성 검사(Consistency checks) 체계를 확립함.

기대 효과 (Impact):

이러한 개선 사항들은 트레이딩 시스템의 견고성(Robustness)과 신뢰성을 향상시키며, 에러 발생을 최소화하고 다양한 시스템 컴포넌트 간의 원활한 상호작용을 보장함.
2026-07-17 01:09:09 +09:00

83 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""
kis_trader/backtest/optuna_search_space.py — Optuna 탐색 공간 (Grid 축 재사용)
==============================================================================
각 전략 Grid 와 동일한 이산 축을 trial.suggest_categorical 로 샘플링.
"""
from __future__ import annotations
from typing import Any, Dict, List
import optuna
from kis_trader.backtest.param_search_breakout import _breakout_grids
from kis_trader.backtest.param_search_momentum import (
_momentum_combo_grid_valid,
_momentum_grids,
)
from kis_trader.backtest.param_search_scalping import _scalp_grids
from kis_trader.backtest.tail_param_search import _tail_grids
def _dedupe_preserve_order(values: List[Any]) -> List[Any]:
seen = set()
out: List[Any] = []
for v in values:
key = v if isinstance(v, (int, float, str, bool)) else repr(v)
if key in seen:
continue
seen.add(key)
out.append(v)
return out
def _suggest_from_grid(trial: optuna.Trial, grid: Dict[str, List[Any]]) -> Dict[str, Any]:
combo: Dict[str, Any] = {}
for key, values in grid.items():
if not values:
continue
choices = _dedupe_preserve_order(list(values))
combo[key] = trial.suggest_categorical(key, choices)
return combo
def suggest_scalp_params(trial: optuna.Trial, mode: str) -> Dict[str, Any]:
combo = _suggest_from_grid(trial, _scalp_grids()[mode])
combo["use_macd_cross"] = False
return combo
def suggest_tail_params(trial: optuna.Trial, mode: str) -> Dict[str, Any]:
return _suggest_from_grid(trial, _tail_grids(mode))
def suggest_momentum_params(trial: optuna.Trial, mode: str) -> Dict[str, Any]:
combo = _suggest_from_grid(trial, _momentum_grids()[mode])
if not _momentum_combo_grid_valid(combo):
raise optuna.TrialPruned("momentum invalid combo")
return combo
def suggest_breakout_params(trial: optuna.Trial, mode: str) -> Dict[str, Any]:
combo = _suggest_from_grid(trial, _breakout_grids()[mode])
if "prev_chg_min" in combo and "prev_chg_max" in combo:
if float(combo["prev_chg_min"]) >= float(combo["prev_chg_max"]):
raise optuna.TrialPruned("breakout prev_chg invalid")
return combo
def scalp_grid_axis_keys(mode: str) -> List[str]:
return list(_scalp_grids()[mode].keys())
def tail_grid_axis_keys(mode: str) -> List[str]:
return list(_tail_grids(mode).keys())
def momentum_grid_axis_keys(mode: str) -> List[str]:
return list(_momentum_grids()[mode].keys())
def breakout_grid_axis_keys(mode: str) -> List[str]:
return list(_breakout_grids()[mode].keys())