Files
kis_bot/scripts/run_optuna_momentum_ls_then_bt.sh
2026-07-30 18:05:07 +09:00

148 lines
4.4 KiB
Bash
Executable File

#!/bin/bash
# 모멘텀 Optuna (LS 유니버스 이력) → 현재 DB 백테(LS) 비교용
# --apply-best 없음 · 실매 미적용 · 봇 재시작 없음
#
# nohup bash scripts/run_optuna_momentum_ls_then_bt.sh \
# >> logs/optuna_mom_ls_then_bt_nohup.out 2>&1 &
# tail -f "$(cat logs/optuna_mom_ls_then_bt_latest_master.logpath)"
set -euo pipefail
cd /home/hoon/kis_bot
mkdir -p logs kis_trader/backtest/results
# LS 이력은 수집 시작일(현재 ~2026-07-27 10:45~) 이전 슬롯이 없음.
# 키움 타임라인 혼입 버그 수정 후: LS 데이터가 있는 구간만 탐색.
START="${START:-2026-07-27}"
END="${END:-2026-07-28}"
MODE="${MODE:-tpe}"
TRIALS="${TRIALS:-200}"
MIN_TRADES="${MIN_TRADES:-1}"
HIST_SRC="${HIST_SRC:-ls}"
PY="${PY:-}"
if [[ -z "$PY" ]]; then
if [[ -x .venv/bin/python ]]; then
PY=".venv/bin/python"
else
PY="python3"
fi
fi
TS0="$(date +%Y%m%d_%H%M%S)"
STUDY="momentum_${MODE}_ls_${START//-/}_${END//-/}_${TS0}"
MASTER="logs/optuna_mom_ls_then_bt_${TS0}_master.log"
OPTUNA_LOG="logs/optuna_momentum_${MODE}_ls_${TS0}.log"
BT_LOG="logs/bt_momentum_ls_currdb_${TS0}.log"
{
echo "======== 모멘텀 Optuna(LS)→백테 시작 $(date -Is) ========"
echo "START=$START END=$END MODE=$MODE TRIALS=$TRIALS"
echo "universe_history_source=$HIST_SRC apply-best=OFF 실매적용=없음"
echo "study=$STUDY"
echo "optuna_log=$OPTUNA_LOG"
echo "bt_log=$BT_LOG"
echo "master=$MASTER"
free -h | sed -n '1,2p'
} | tee -a "$MASTER"
echo "$MASTER" > logs/optuna_mom_ls_then_bt_latest_master.logpath
echo "$OPTUNA_LOG" > logs/optuna_mom_ls_then_bt_latest_optuna.logpath
echo "$STUDY" > logs/optuna_mom_ls_then_bt_latest.study
set +e
"$PY" -u kis_trader/backtest/param_search_optuna.py \
--strategy momentum \
--mode "$MODE" \
--start "$START" \
--end "$END" \
--trials "$TRIALS" \
--min_trades "$MIN_TRADES" \
--min_win_rate 0 \
--min_pf 0 \
--sort-by score \
--orderbook-filter off \
--universe-history-source "$HIST_SRC" \
--study-name "$STUDY" \
--no-progress \
--n-jobs 1 \
>> "$OPTUNA_LOG" 2>&1
RC_OPT=$?
set -e
{
echo ""
echo "-------- Optuna 종료 rc=$RC_OPT $(date -Is) --------"
if [[ $RC_OPT -ne 0 ]]; then
echo "❌ Optuna 실패 — 백테 스킵. log=$OPTUNA_LOG"
fi
# best 요약 (있으면)
"$PY" - <<PY || true
import json, glob, os
from pathlib import Path
root = Path("kis_trader/backtest/results")
cands = sorted(root.glob("*${STUDY}*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
cands += sorted(root.glob("optuna_momentum*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
seen=set(); files=[]
for p in cands:
if p in seen: continue
seen.add(p); files.append(p)
hit=None
for p in files[:30]:
try:
d=json.loads(p.read_text(encoding="utf-8"))
except Exception:
continue
if d.get("optuna_study_name")=="${STUDY}" or "${STUDY}" in p.name:
hit=p; break
if not hit and files:
# 최신 momentum optuna 결과 폴백 표시만
for p in files[:10]:
try:
d=json.loads(p.read_text(encoding="utf-8"))
except Exception:
continue
if str(d.get("strategy","")).lower() in ("momentum","") and "optuna" in str(d.keys()):
hit=p; break
if hit:
d=json.loads(hit.read_text(encoding="utf-8"))
print("best_json", hit)
print("best_value", d.get("optuna_best_value"), "trial", d.get("optuna_best_trial_number"))
s=d.get("summary") or d.get("best_summary") or {}
if s:
print("best_summary trades", s.get("total_trades"), "wr", s.get("win_rate"), "pnl", s.get("total_pnl"))
else:
print("best_json: (아직 매칭 파일 없음 — optuna 로그 확인)")
PY
} | tee -a "$MASTER"
if [[ $RC_OPT -ne 0 ]]; then
exit "$RC_OPT"
fi
{
echo ""
echo "-------- 현재 DB 백테(LS) START $(date -Is) --------"
echo "LOG=$BT_LOG"
} | tee -a "$MASTER"
set +e
"$PY" -u scripts/run_strategy_backtest_cli.py \
--strategy momentum \
--start "$START" \
--end "$END" \
--universe history \
--universe-history-source "$HIST_SRC" \
--orderbook-filter off \
--job-id "mom_ls_currdb_${TS0}" \
>> "$BT_LOG" 2>&1
RC_BT=$?
set -e
{
echo "-------- 현재 DB 백테 종료 rc=$RC_BT $(date -Is) --------"
echo "optuna_log=$OPTUNA_LOG"
echo "bt_log=$BT_LOG"
echo "실매 미적용(apply-best 없음) · 봇 재시작 없음"
echo "======== 전체 종료 $(date -Is) ========"
} | tee -a "$MASTER"
exit "$RC_BT"