# -*- coding: utf-8 -*-
# =============================================================================
# AlgoLab · 레버리지 ETF 검증용 데이터 캐시
#   - QQQ/SPY: adjclose(배당 재투자 총수익) — 3배 시뮬레이션의 기초자산
#   - TQQQ/UPRO: 실물 3배 ETF — 시뮬레이션이 실물과 맞는지 검증용(정직 검증)
#   - ^IRX: 13주 국채 수익률(%) — 레버리지 조달비용 실측용. 가정으로 때우지 않는다.
# 출력: 연구/lev_<slug>_daily.csv  (date,close)
# =============================================================================
import csv, datetime, json, os, urllib.request, time

HERE = os.path.dirname(os.path.abspath(__file__))
ASOF = datetime.date(2026, 7, 22)          # spy_daily.csv와 동일 기준일

TARGETS = [("QQQ", "qqq", True), ("SPY", "spy", True),
           ("TQQQ", "tqqq", True), ("UPRO", "upro", True),
           ("%5EIRX", "irx", False)]


def fetch(sym, adj):
    u = (f"https://query1.finance.yahoo.com/v8/finance/chart/{sym}"
         f"?range=40y&interval=1d&events=div%2Csplit")
    req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"})
    j = json.loads(urllib.request.urlopen(req, timeout=40).read())
    r = j["chart"]["result"][0]
    q = r["indicators"]["quote"][0]
    ac = None
    if adj:
        try:
            ac = r["indicators"]["adjclose"][0]["adjclose"]
        except Exception:
            ac = None
    rows = []
    for i, ts in enumerate(r["timestamp"]):
        d = datetime.datetime.utcfromtimestamp(ts).date()
        c = q["close"][i]
        if c is None or d > ASOF:
            continue
        if ac and ac[i]:
            c = ac[i]
        rows.append([d, round(c, 6)])
    return rows


for sym, slug, adj in TARGETS:
    rows = fetch(sym, adj)
    p = os.path.join(HERE, f"lev_{slug}_daily.csv")
    with open(p, "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["date", "close"])
        w.writerows(rows)
    print(f"{slug}: {len(rows)} rows  {rows[0][0]} ~ {rows[-1][0]}")
    time.sleep(1)
