"""Put/Call 未平倉比率擇時櫃買指數：三項穩健性驗證（/blog/put-call-open-interest-ratio-hedge 驗證段的數字來源）。

條件與原文相同：
- 指標：期交所臺指選擇權「買賣權未平倉量比率%」減 100，也就是（Put 未平倉量 / Call 未平倉量 - 1）× 100%，取 30 日移動平均
- 指標 >= 0 持有櫃買指數，< 0 出清
- 訊號用當天盤後資料，sim() 在下一個交易日收盤成交，手續費 0.1425%、證交稅 0.3%（sim 台股預設）

FinLab 的櫃買指數（stock_index_price:收盤指數 的「上櫃櫃買指數:指數」）從 2016 年起，所以驗證期間是 2016-01-04 到最新資料。
另外用加權指數（taiex_total_index:收盤指數，1999 年起）從 0050 上市後的 2003-07-01 起，跑同樣的三項檢查當對照。
三項檢查：
1. 鄰近參數：移動平均天數 20、30、40 乘上門檻 -10、0、+10，9 組日夏普要有 7 組以上高於同期 0050 含息
2. 前後兩段：期間對半切，兩段都要高於 0050 含息
3. 交易成本：sim() 預設手續費與證交稅

統計口徑：日夏普 = 日報酬平均 / 標準差 × √252，不扣無風險利率；
0050 含息 = etl:adj_close 還原價買進持有，與策略同一段期間、不扣成本。
執行後會在目前目錄輸出 data.csv（淨值曲線）與 metrics.json（統計）。

    pip install finlab
    python strategy.py

finlab 需要資料時會自動引導登入，不需要在程式裡填 token。
"""

import json

import pandas as pd

import finlab
from finlab import data
from finlab.backtest import sim
from finlab.markets.tw import TWMarket

STRATEGY_NAME = "Put/Call 未平倉比率擇時櫃買指數"
START = "2016-01-01"
MA_DAYS = 30     # 指標移動平均天數
THRESHOLD = 0    # 指標 >= 門檻才持有
MA_GRID = [20, 30, 40]
THRESHOLD_GRID = [-10, 0, 10]


class IndexMarket(TWMarket):
    """把指數當成可交易標的：成交、估值都用指數收盤，成本沿用台股預設。"""

    def __init__(self, prices: pd.DataFrame):
        super().__init__()
        self.prices = prices

    @staticmethod
    def get_name():
        return "tw_index"

    def get_price(self, trade_at_price, adj=True):
        return self.prices


def put_call_indicator() -> pd.Series:
    pc = pd.DataFrame(data.get("tw_option_put_call_ratio"))
    ratio = pc.set_index(pd.to_datetime(pc["date"]))["買賣權未平倉量比率%"].astype(float)
    return ratio.sort_index() - 100


def timing_curve(indicator, prices, start, ma_days=MA_DAYS, threshold=THRESHOLD, **cost):
    """指標達門檻持有指數，否則空手；回傳從 start 起的淨值（第一次進場前是現金）與部位。"""
    signal = indicator.rolling(ma_days, min_periods=1).mean() >= threshold
    position = signal.reindex(prices.index, method="ffill").to_frame(prices.columns[0]).astype(float)
    position = position[position.index >= start]
    report = sim(position, market=IndexMarket(prices), upload=False, name=STRATEGY_NAME, **cost)
    return report.creturn.reindex(position.index).ffill().fillna(1.0), position.iloc[:, 0]


def curve_stats(curve: pd.Series) -> dict:
    curve = curve / curve.iloc[0]
    daily = curve.pct_change().dropna()
    years = (curve.index[-1] - curve.index[0]).days / 365.25
    return {
        "cagr": curve.iloc[-1] ** (1 / years) - 1,
        "daily_sharpe": daily.mean() / daily.std() * 252 ** 0.5,
        "max_drawdown": (curve / curve.cummax() - 1).min(),
        "total_return": curve.iloc[-1] - 1,
    }


def window_stats(creturn: pd.Series, bench_all: pd.Series) -> dict:
    bench = bench_all.loc[creturn.index[0]:creturn.index[-1]]
    return {"strategy": curve_stats(creturn), "benchmark_0050": curve_stats(bench),
            "window": f"{creturn.index[0].date()}/{creturn.index[-1].date()}"}


def rounded(obj):
    if isinstance(obj, dict):
        return {k: rounded(v) for k, v in obj.items()}
    return round(float(obj), 6) if isinstance(obj, float) else obj


def validate(indicator, index: pd.Series, start: str, bench_all: pd.Series):
    """回傳原參數的淨值，與原參數、鄰近 9 組、前後兩段、不扣成本的統計；index 是被擇時的指數。"""
    prices = index.to_frame()
    runs = {(ma_days, threshold): timing_curve(indicator, prices, start, ma_days, threshold)
            for ma_days in MA_GRID for threshold in THRESHOLD_GRID}
    creturn, position = runs[MA_DAYS, THRESHOLD]
    mid = creturn.index[creturn.index.searchsorted(creturn.index[0] + (creturn.index[-1] - creturn.index[0]) / 2)]
    return creturn, {
        "main": window_stats(creturn, bench_all),
        "time_in_market": position.mean(),
        "index_buy_hold": curve_stats(index.loc[creturn.index[0]:]),
        "no_cost": curve_stats(timing_curve(indicator, prices, start, fee_ratio=0, tax_ratio=0)[0]),
        "grid": {f"{ma_days}|{threshold}": window_stats(c, bench_all) for (ma_days, threshold), (c, _) in runs.items()},
        "halves": {"first": window_stats(creturn.loc[:mid], bench_all),
                   "second": window_stats(creturn.loc[mid:], bench_all)},
    }


def report_lines(label: str, v: dict) -> None:
    s, b, h = v["main"]["strategy"], v["main"]["benchmark_0050"], v["index_buy_hold"]
    wins = sum(g["strategy"]["daily_sharpe"] > g["benchmark_0050"]["daily_sharpe"] for g in v["grid"].values())
    print(f"【{label}】期間 {v['main']['window']}，持有時間 {v['time_in_market']:.1%}")
    print(f"  擇時：年化 {s['cagr']:.2%}，日夏普 {s['daily_sharpe']:.2f}，最大回撤 {s['max_drawdown']:.2%}")
    print(f"  指數買進持有：年化 {h['cagr']:.2%}，日夏普 {h['daily_sharpe']:.2f}，最大回撤 {h['max_drawdown']:.2%}")
    print(f"  0050 含息：年化 {b['cagr']:.2%}，日夏普 {b['daily_sharpe']:.2f}，最大回撤 {b['max_drawdown']:.2%}")
    print(f"  鄰近參數：{wins}/9 組日夏普高於 0050 含息")
    for k, g in v["grid"].items():
        ma_days, threshold = k.split("|")
        print(f"    MA {ma_days} 門檻 {threshold}：{g['strategy']['daily_sharpe']:.2f}（0050 {g['benchmark_0050']['daily_sharpe']:.2f}）")
    for k, part in v["halves"].items():
        print(f"  {k} {part['window']}：{part['strategy']['daily_sharpe']:.2f} 對 {part['benchmark_0050']['daily_sharpe']:.2f}")


def main() -> None:
    finlab.login()
    bench_all = data.get("etl:adj_close")["0050"].dropna()
    indicator = put_call_indicator()
    otc_index = data.get("stock_index_price:收盤指數")["上櫃櫃買指數:指數"].dropna()
    creturn, otc = validate(indicator, otc_index.rename("OTC"), START, bench_all)
    _, taiex = validate(indicator, data.get("taiex_total_index:收盤指數")["TAIEX"].dropna(), "2003-07-01", bench_all)
    report_lines("櫃買指數（本文頭條）", otc)
    report_lines("加權指數（2003-07 起對照）", taiex)

    otc_hold = otc_index.loc[creturn.index[0]:]
    bench = bench_all.reindex(creturn.index)
    curves = pd.DataFrame({STRATEGY_NAME: creturn / creturn.iloc[0], "櫃買指數": otc_hold / otc_hold.iloc[0],
                           "0050含息": bench / bench.iloc[0]})
    curves.index.name = "date"
    curves.round(6).to_csv("data.csv")
    metrics = {
        "window": otc["main"]["window"],
        "star": STRATEGY_NAME,
        "variants": {STRATEGY_NAME: {**otc["main"]["strategy"], "time_in_market": otc["time_in_market"]}},
        "benchmark_0050": otc["main"]["benchmark_0050"],
        "otc_index_buy_hold": otc["index_buy_hold"],
        "no_cost": otc["no_cost"],
        "grid": otc["grid"],
        "halves": otc["halves"],
        "taiex_since_2003": taiex,
        "run_date": str(pd.Timestamp.today().date()),
        "finlab_version": finlab.__version__,
        "generated_by": "static/blog/put-call-open-interest-ratio-hedge/validation/strategy.py",
    }
    with open("metrics.json", "w", encoding="utf-8") as f:
        json.dump(rounded(metrics), f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    main()
