"""冰風暴概念股季節效應：三項驗證用的版本（/blog/ice-storm-concept-stocks-seasonal-effect）

概念股與本文 Colab 範例相同：security_industry_themes 裡含「汽車:保險桿、汽車:引擎蓋、汽車:鈑金、乙二醇」的公司
（產業題材是現在的分類，已下市的公司不在名單上）。
1. 各月平均報酬與勝率：概念股等權日報酬指數，原文期間（到 2022-12）、到最新資料，以及 2023 年起的樣本外；
   另列同月的 0050 含息與扣掉 0050 之後的超額報酬。
2. 本文建議的操作「11 月底進場、吃 12 月的漲幅」做成策略：11 月最後一個交易日＋a 收盤買進等權概念股，
   12 月最後一個交易日＋b 收盤賣出，其餘時間空手；另跑一個其餘時間持有 0050 的版本。

三項驗證（「贏」＝日夏普高於同期 0050 含息買進持有）：
  1. 鄰近參數：a（-5、0、+5 個交易日）× b（-5、0、+5 個交易日），9 組至少 7 組贏。
  2. 前後兩段：回測期間對半切，兩段各自要贏。
  3. 交易成本：sim() 預設手續費 0.1425% 與證交稅 0.3%。
0050 含息：etl:adj_close 還原價買進持有，不經 sim、不含成本。日夏普＝日報酬平均 ÷ 標準差 × √252，不扣無風險利率。

    pip install finlab
    python strategy.py

finlab 需要資料時會自動引導登入，不需要在程式裡填 token。結果另存 validation.json。
"""
import json
import math

import pandas as pd
from finlab import data
from finlab.backtest import sim

PATTERN = "汽車[:：]保險桿|汽車[:：]引擎蓋|汽車[:：]鈑金|乙二醇"


def concept_stocks():
    themes = data.get("security_industry_themes")
    return sorted(themes[themes["category"].astype(str).str.contains(PATTERN)]["stock_id"].astype(str))


def monthly_table(monthly, bench_monthly):
    """各月平均報酬與勝率，另列同月 0050 含息與扣掉 0050 之後的超額報酬。"""
    bench = bench_monthly.reindex(monthly.index)
    t = pd.DataFrame({"pct": monthly, "bench": bench, "excess": monthly - bench, "month": monthly.index.month})
    g = t.groupby("month")
    return pd.DataFrame({"平均報酬": g["pct"].mean(), "勝率": g["pct"].apply(lambda x: (x > 0).mean()),
                         "次數": g["pct"].size(), "0050 平均": g["bench"].mean(), "超額平均": g["excess"].mean(),
                         "超額勝率": g["excess"].apply(lambda x: (x > 0).mean())})


def window_position(stocks, a, b, idx, with_0050):
    """11 月最後一個交易日＋a 收盤買、12 月最後一個交易日＋b 收盤賣（sim 在訊號隔天收盤成交，所以持有表提前一天）。"""
    last = pd.Series(range(len(idx)), index=idx).groupby([idx.year, idx.month]).max()
    position = pd.DataFrame(False, index=idx, columns=stocks)
    inside = pd.Series(False, index=idx)
    for year in sorted({y for y, m in last.index if m == 11}):
        if (year, 12) not in last.index:
            continue
        buy, sell = last[(year, 11)] + a, last[(year, 12)] + b
        if sell >= len(idx):
            continue
        inside.iloc[buy - 1:sell - 1] = True
    position.loc[inside] = True
    if with_0050:
        position["0050"] = ~inside
    return position


def curve_stats(curve):
    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,
            "sharpe": daily.mean() / daily.std() * math.sqrt(252),
            "mdd": (curve / curve.cummax() - 1).min()}


def versus_0050(curve, bench):
    curve = curve.dropna()
    first_move = (curve != curve.iloc[0]).argmax()
    curve = curve.iloc[max(first_move - 1, 0):]
    return curve, curve_stats(curve), curve_stats(bench.loc[curve.index[0]:curve.index[-1]])


def main():
    stocks = concept_stocks()
    adj_close = data.get("etl:adj_close")
    bench = adj_close["0050"].dropna()
    print("概念股：", "、".join(stocks))
    out = {"stocks": stocks, "monthly": {}}

    # 1. 本文的類股指數：成分股日報酬取平均後連乘
    pct = adj_close[stocks].pct_change(fill_method=None).iloc[1:]
    index = pct.mean(axis=1).add(1).cumprod()
    monthly = (index.resample("ME").last().pct_change() * 100).dropna()
    bench_monthly = (bench.resample("ME").last().pct_change() * 100).dropna()
    for label, part in (("原文期間 2007-05 到 2022-12", monthly.loc[:"2022-12"]),
                        ("到最新資料", monthly), ("樣本外 2023-01 起", monthly.loc["2023-01":])):
        table = monthly_table(part, bench_monthly)
        out["monthly"][label] = table.reset_index().to_dict(orient="records")
        print(f"\n{label}（平均報酬 %、勝率）")
        print(table.round(2).to_string())

    # 2. 11 月底進場、12 月底出場
    idx = data.get("price:收盤價").index
    for with_0050, label in ((False, "其餘時間空手"), (True, "其餘時間持有 0050")):
        print(f"\n=== {label} ===")
        res = out["with_0050" if with_0050 else "cash"] = {"grid": [], "halves": []}
        wins = 0
        for a in (-5, 0, 5):
            for b in (-5, 0, 5):
                report = sim(window_position(stocks, a, b, idx, with_0050), upload=False)
                curve, s, bs = versus_0050(report.creturn, bench)
                wins += s["sharpe"] > bs["sharpe"]
                res["grid"].append({"a": a, "b": b, "sharpe": s["sharpe"], "cagr": s["cagr"], "bench_sharpe": bs["sharpe"]})
                print(f"a={a:+d} b={b:+d}：日夏普 {s['sharpe']:.2f}（0050 {bs['sharpe']:.2f}），年化 {s['cagr']:.1%}")
                if (a, b) == (0, 0):
                    base, sd = curve, s
        print(f"鄰近參數：{wins}/9 組贏")
        mid = base.index[0] + (base.index[-1] - base.index[0]) / 2
        for lo, hi in ((base.index[0], mid), (mid, base.index[-1])):
            part = base.loc[lo:hi]
            s, bs = curve_stats(part), curve_stats(bench.loc[part.index[0]:part.index[-1]])
            res["halves"].append({"start": str(part.index[0].date()), "end": str(part.index[-1].date()),
                                  "strategy": s, "bench": bs})
            print(f"{part.index[0].date()} 到 {part.index[-1].date()}：日夏普 {s['sharpe']:.2f}（0050 {bs['sharpe']:.2f}），"
                  f"年化 {s['cagr']:.1%}（0050 {bs['cagr']:.1%}）")
        zero = sim(window_position(stocks, 0, 0, idx, with_0050), upload=False, fee_ratio=0, tax_ratio=0)
        _, s, bs = versus_0050(zero.creturn, bench)
        res["costs"] = {"zero": s, "default": sd, "bench": bs}
        print(f"不扣成本：日夏普 {s['sharpe']:.2f}、年化 {s['cagr']:.1%}、最大回撤 {s['mdd']:.1%}；"
              f"sim() 預設：日夏普 {sd['sharpe']:.2f}、年化 {sd['cagr']:.1%}、最大回撤 {sd['mdd']:.1%}；"
              f"0050 含息：日夏普 {bs['sharpe']:.2f}、年化 {bs['cagr']:.1%}、最大回撤 {bs['mdd']:.1%}")

    with open("validation.json", "w", encoding="utf-8") as f:
        json.dump(out, f, ensure_ascii=False, indent=1, default=float)


if __name__ == "__main__":
    main()
