Files
Bithumb/scripts/2_render_best_technique_chart.py
xavis 2d515dd669 feat(spot): 2단계 인과 기법 분석 파이프라인 마무리
common/spot/futures 경로 정비, 캔들 데이터 모듈 복원, MTF 규칙 자동 저장 및 2단계 설계·최종 정리 문서를 반영해 3단계 착수 기반을 확정한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 16:09:32 +09:00

127 lines
4.0 KiB
Python

#!/usr/bin/env python3
"""2단계: 수익률 1위 기법 sim 차트 (1단계 v3 sim과 동일 형식·기간)."""
from __future__ import annotations
import argparse
import json
import logging
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
sys.path.insert(0, str(SRC))
from deepcoin.config import load_settings
from deepcoin.data.candle_loader import load_candles
from deepcoin.evaluation.causal_sim import (
best_technique_chart_path,
pick_best_technique_row,
render_best_technique_comparison_chart,
run_technique_causal_sim,
)
from deepcoin.techniques.runner import load_ground_truth, load_technique_result
def _configure_logging(verbose: bool) -> None:
"""로깅 레벨을 설정한다."""
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(
level=level,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
def main() -> int:
"""CLI 진입점."""
parser = argparse.ArgumentParser(
description="2단계 최고 수익 기법 sim 차트 (1단계 v3 sim 대조용)"
)
parser.add_argument(
"--technique",
type=str,
default=None,
help="기법 ID (기본: causal_sim_report 수익률 1위)",
)
parser.add_argument(
"--report",
type=str,
default=None,
help="causal_sim_report.json 경로 (기본: .env)",
)
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args()
_configure_logging(args.verbose)
settings = load_settings()
analysis_dir = settings.causal_sim_report_json.parent
report_path = Path(args.report) if args.report else settings.causal_sim_report_json
gt_result = load_ground_truth(settings.ground_truth_file)
gt_meta = gt_result.get("meta", {})
technique_id = args.technique
if not technique_id:
if not report_path.exists():
logging.error(
"리포트 없음: %s — 먼저 2_run_causal_sim.py 실행",
report_path,
)
return 1
report = json.loads(report_path.read_text(encoding="utf-8"))
best = pick_best_technique_row(report)
if not best:
logging.error("리포트에 기법 순위 없음: %s", report_path)
return 1
technique_id = best["technique_id"]
tech_path = settings.techniques_dir / f"{technique_id}.json"
if not tech_path.exists():
logging.error("기법 결과 없음: %s", tech_path)
return 1
result = load_technique_result(tech_path)
df = load_candles(
db_path=settings.db_path,
symbol=settings.symbol,
interval_min=settings.gt_interval_min,
lookback_days=settings.gt_lookback_days,
)
last_close = float(df["close"].iloc[-1])
sim_pnl = run_technique_causal_sim(
result,
initial_cash_krw=settings.gt_initial_cash_krw,
fee_rate=settings.gt_trading_fee_rate,
sim_lookback_days=settings.gt_sim_lookback_days,
data_end=gt_meta.get("data_to"),
last_mark_price=last_close,
)
output_path = best_technique_chart_path(analysis_dir)
render_best_technique_comparison_chart(
db_path=settings.db_path,
symbol=settings.symbol,
gt_result=gt_result,
result=result,
sim_pnl=sim_pnl,
output_path=output_path,
chart_lookback_days=settings.download_days,
)
print("\n=== 최고 수익 기법 sim 차트 (1단계 v3 대조) ===")
print(f"기법: {result.technique_name} ({result.technique_id})")
print(
f"3년 sim: {sim_pnl.get('total_return_pct', 0):+.2f}% | "
f"체결 {sim_pnl.get('buys_executed', 0)}/{sim_pnl.get('sells_executed', 0)}"
)
print(f"차트 기간: 최근 {settings.download_days}일 (1단계 v3 sim과 동일)")
print(f"HTML: {output_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())