"""00900 優化版（七月＋十二月股利率＋殖利率，前 30 檔）：/blog/etf-00900-optimization 三項驗證用的程式。

原文 VIP 段「優化後的成績單」的程式（原文 Colab 範例檔的優化版），只是不截斷結束日：
- 股票池：上市櫃普通股，市值前 200 大、近 3 個月日均成交金額排名前 90%、近四季營業利益合計為正
- 七月股利率＝最近一次現金股利（依除息日）在近四個季底的值加總 ÷ 收盤價
- 十二月股利率＝近四季 EPS × 近 720 天平均現金股利發放率 ÷ 收盤價
  （兩者照原文範例檔的寫法，和 00900 指數的近四季股利總和、三年平均發放率略有出入）
- 七月股利率、十二月股利率、殖利率三項排名相加取前 30 檔等權
- 跟 00900 一樣在 4、7、12 月第 7 個交易日後第 5 個交易日換股，從 2021-12-22（00900 上市）起算
- sim() 預設手續費 0.1425% 與證交稅 0.3%

統計口徑：日夏普 = 日報酬平均 / 標準差 × √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.dataframe import FinlabDataFrame

STRATEGY_NAME = "00900 優化版（七月＋十二月股利率＋殖利率，前 30 檔）"
TOP_MARKET_CAP = 200
TOP_N = 30
START = "2021-12-22"


def review_effective_dates(trading_dates: pd.DatetimeIndex, rules) -> pd.DatetimeIndex:
    """rules: [(月份, 審核基準日是當月第幾個交易日)]；生效日＝基準日後第 5 個交易日。"""
    out = []
    for year in range(trading_dates[0].year, trading_dates[-1].year + 1):
        for month, nth in rules:
            month_dates = trading_dates[(trading_dates.year == year) & (trading_dates.month == month)]
            if len(month_dates) < nth:
                continue
            i = trading_dates.searchsorted(month_dates[nth - 1]) + 5
            if i < len(trading_dates):
                out.append(trading_dates[i])
    return pd.DatetimeIndex(sorted(out))


def build_report():
    effective = review_effective_dates(data.get("price:收盤價").index, [(4, 7), (7, 7), (12, 7)])
    with data.universe(market="TSE_OTC"):
        close = data.get("price:收盤價")
        market_value = data.get("etl:market_value")
        trans_amount = data.get("price:成交金額")
        da = data.get("dividend_announcement")
        op_income = data.get("fundamental_features:營業利益")
        eps = data.get("fundamental_features:每股稅後淨利")
        yield_ratio = data.get("price_earning_ratio:殖利率(%)")

    cash_dividend = FinlabDataFrame(
        da.drop_duplicates(["stock_id", "盈餘分配之股東現金股利(元/股)"], keep="first")
          .groupby([da.stock_id, da["除息交易日"]]).first()["盈餘分配之股東現金股利(元/股)"]
          .dropna().reset_index()
          .pivot(index="除息交易日", columns="stock_id", values="盈餘分配之股東現金股利(元/股)"))
    quarterly_div = cash_dividend.ffill().fillna(0).resample("QE").last()
    div_4q = quarterly_div.rolling(4).sum()
    payout = quarterly_div / eps
    payout_3y = payout.resample("D").last().ffill().fillna(0).rolling(720, min_periods=1).mean()
    jul_yield = div_4q / close
    dec_yield = (eps.rolling(4).sum() * payout_3y) / close

    conds = (
        (close > 0)
        & market_value.is_largest(TOP_MARKET_CAP)
        & (trans_amount.rolling(60).mean().rank(axis=1, pct=True) >= 0.1)
        & (op_income.rolling(4).sum() > 0)
    )
    score = (jul_yield.rank(axis=1, pct=True) + dec_yield.rank(axis=1, pct=True)
             + yield_ratio.rank(axis=1, pct=True))
    position = (score * conds).is_largest(TOP_N)
    return sim(position.loc[START:], resample=effective, upload=False, name=STRATEGY_NAME)


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 main() -> None:
    finlab.login()
    bench_all = data.get("etl:adj_close")["0050"].dropna()
    report = build_report()

    # 從第一次有部位的那天起算，0050 含息用同一段期間
    creturn = report.creturn.dropna()
    first_move = (creturn != creturn.iloc[0]).argmax()
    creturn = creturn.iloc[max(first_move - 1, 0):]
    bench = bench_all.loc[creturn.index[0]:creturn.index[-1]]

    strategy_stats = curve_stats(creturn)
    bench_stats = curve_stats(bench)
    holdings = (report.position.fillna(0) != 0).sum(axis=1)
    strategy_stats["avg_holdings"] = holdings[holdings > 0].mean()

    start, end = creturn.index[0].date(), creturn.index[-1].date()
    print(f"期間 {start} 至 {end}")
    for label, s in [("策略", strategy_stats), ("0050 含息", bench_stats)]:
        print(f"{label}：年化 {s['cagr']:.2%}，日夏普 {s['daily_sharpe']:.2f}，最大回撤 {s['max_drawdown']:.2%}")

    curves = pd.DataFrame({STRATEGY_NAME: creturn / creturn.iloc[0], "0050含息": bench / bench.iloc[0]})
    curves.index.name = "date"
    curves.round(6).to_csv("data.csv")
    metrics = {
        "window": f"{start}/{end}",
        "star": STRATEGY_NAME,
        "variants": {STRATEGY_NAME: {k: round(float(v), 6) for k, v in strategy_stats.items()}},
        "benchmark_0050": {k: round(float(v), 6) for k, v in bench_stats.items()},
        "run_date": str(pd.Timestamp.today().date()),
        "finlab_version": finlab.__version__,
        "generated_by": "static/blog/etf-00900-optimization/validation/strategy.py",
    }
    with open("metrics.json", "w", encoding="utf-8") as f:
        json.dump(metrics, f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    main()
