"""法說會營收動能策略：三項驗證用的版本（/blog/investor-conference-revenue-momentum-strategy）

條件與本文最終策略相同：法說會前 N 個交易日起持有到法說會隔天，營收 YoY、QoQ、MoM 任一 > 0，10% 停損。
跑兩個版本：
- 原文版：investors_conference 的實際召開日。2024 年起的公布時間顯示，法說會多半只提前約 3 天公布，
  提前 10 個交易日以上的約 6%，這個版本等於事先知道召開日，只當對照。
- 可實作版：召開日換成預測日（同公司去年召開日 + 364 天，同一個星期幾），其他條件相同。

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

    pip install finlab
    python strategy.py

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

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

FEES = {"本文（手續費三折）": {"fee_ratio": 1.425 / 1000 / 3}, "sim() 預設": {}}


def conference_table(predicted):
    """法說會日期表：召開日當天為真。predicted=True 時改用去年召開日 + 364 天。"""
    conf = data.get("investors_conference").reset_index()
    if predicted:
        conf["date"] = conf["date"] + pd.Timedelta(days=364)
        conf = conf[conf["date"] <= data.get("price:收盤價").index[-1]]
    conf = conf.drop_duplicates(["date", "stock_id"])
    return conf.pivot(index="date", columns="stock_id")["公司名稱"].notna()


def build(N=10, stop_loss=0.1, predicted=False, qoq=True, fee=None):
    close = data.get("price:收盤價")
    if qoq:   # 本文最終策略把收盤價前後補值
        close = close.ffill().bfill()
    rev_yy = data.get("monthly_revenue:去年同月增減(%)") * (close >= 0)
    rev_mm = data.get("monthly_revenue:上月比較增減(%)") * (close >= 0)
    rev_qq = data.get("fundamental_features:營收成長率") * (close >= 0)

    # 本文的 (close - close.shift(-5)) / close < 1.07 用到未來 5 天的價格，而且條件恆真，這裡拿掉
    position = conference_table(predicted) * (close >= 0)
    position = position.shift(-N).fillna(False)
    grow = (rev_yy > 0) | (rev_mm > 0)
    if qoq:
        grow = grow | (rev_qq > 0)
    position = (position & grow).rolling(N).sum().fillna(0)
    kw = {} if fee is None else fee
    if stop_loss:
        kw = {**kw, "stop_loss": stop_loss}
    return sim(position, trade_at_price="close", upload=False, **kw)


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):
    """從第一次有部位的前一天起算，0050 含息用同一段期間。"""
    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():
    bench = data.get("etl:adj_close")["0050"].dropna()
    out = {}
    for predicted, label in ((False, "原文版（實際召開日，用到未來資料）"), (True, "可實作版（預測召開日）")):
        print(f"\n=== {label} ===")
        res = out["predicted" if predicted else "actual"] = {"grid": [], "costs": {}, "halves": []}
        wins, base = 0, None
        for N in (5, 10, 20):
            for stop in (0.05, 0.10, 0.15):
                report = build(N, stop, predicted)
                curve, s, b = versus_0050(report.creturn, bench)
                wins += s["sharpe"] > b["sharpe"]
                res["grid"].append({"N": N, "stop_loss": stop, "sharpe": s["sharpe"], "cagr": s["cagr"],
                                    "bench_sharpe": b["sharpe"]})
                print(f"N={N:2d} 停損 {stop:.0%}：日夏普 {s['sharpe']:.2f}（0050 {b['sharpe']:.2f}），年化 {s['cagr']:.1%}")
                if (N, stop) == (10, 0.10):
                    base = curve
        print(f"鄰近參數：{wins}/9 組贏")
        for name, fee in {"不扣成本": {"fee_ratio": 0, "tax_ratio": 0}, **FEES}.items():
            _, s, b = versus_0050(build(10, 0.1, predicted, fee=fee).creturn, bench)
            res["costs"][name] = {"strategy": s, "bench": b}
            print(f"成本 {name}：日夏普 {s['sharpe']:.2f}，年化 {s['cagr']:.1%}，最大回撤 {s['mdd']:.1%}"
                  f"（0050 年化 {b['cagr']:.1%}、最大回撤 {b['mdd']:.1%}）")
        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, b = 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": b})
            print(f"{part.index[0].date()} 到 {part.index[-1].date()}：日夏普 {s['sharpe']:.2f}（0050 {b['sharpe']:.2f}）")

    # 本文的比較：原始條件（YoY 或 MoM）vs 加 QoQ＋停損，放在同一段期間
    # 原始條件從 2007 年起；QoQ（fundamental_features）2013 年才有，最終策略從 2013-05-03 起
    print("\n=== 同一段期間（2013-05-03 起）比較原始條件與最終策略 ===")
    for name, fee in FEES.items():
        for qoq, stop, label in ((False, None, "原始條件"), (True, 0.1, "最終策略")):
            curve = build(10, stop, False, qoq=qoq, fee=fee).creturn.loc["2013-05-03":]
            s = curve_stats(curve)
            out.setdefault("same_window", {})[f"{name} {label}"] = s
            print(f"{name} {label}：日夏普 {s['sharpe']:.2f}，年化 {s['cagr']:.1%}，最大回撤 {s['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()
