"""00919 優化版（ROE＋年化股息率，五月／十二月各選 10 檔）：/blog/etf-00919-optimization 三項驗證用的程式。

原文 VIP 段「終極策略版本」的程式（原文 Colab 範例檔的優化版），只是不截斷結束日：
- 股票池：上市櫃普通股，股價在 20 日均線之上、近四季 ROE 都為正
- 五月：只看已公告現金股利的公司，市值、股利率、近兩年平均現金殖利率、ROE 四項排名相加取前 10 檔
- 十二月：股利率換成預估股利率（股利率 ×（1＋前三季 EPS 年增率）），其餘相同
- 跟 00919 一樣在 5 月第 17 個交易日、12 月第 7 個交易日後第 5 個交易日換股，單檔上限 10%
- 原文資料從 2022-10-20 起算、回測從 2022-12-27 起（第一次換股是 2023 年 5 月）
- 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 numpy as np
import pandas as pd

import finlab
from finlab import data
from finlab.backtest import sim
from finlab.dataframe import FinlabDataFrame

STRATEGY_NAME = "00919 優化版（ROE＋年化股息率，前 10 檔）"
MA_DAYS = 20
TOP_N = 10
DATA_FROM = "2022-10-20"
START = "2022-12-27"


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 board_cash_dividend() -> FinlabDataFrame:
    """每股現金股利，日期取股東會日期（沒有就用董事會決議日）。"""
    df = data.get("board_dividend_announcement")
    dates = df["股東會日期"].fillna(df["董事會決議（擬議）股利分派日"])
    out = (df.drop_duplicates(["stock_id", "股東配發之現金(股利)總金額(元)"], keep="first")
             .groupby([df.stock_id, dates]).first()["盈餘分配之現金股利(元/股)"]
             .dropna().reset_index()
             .pivot(index="股東會日期", columns="stock_id", values="盈餘分配之現金股利(元/股)"))
    return FinlabDataFrame(out.rename_axis("date").rename_axis("symbol", axis=1))


def build_report():
    with data.universe(market="TSE_OTC"):
        market_value = data.get("etl:market_value")
        close = data.get("price:收盤價").loc[DATA_FROM:]
        roe = data.get("fundamental_features:ROE稅後")
        eps = data.get("fundamental_features:每股稅後淨利")
        board_dividend = board_cash_dividend().ffill().fillna(0)

    div_yield = board_dividend.rolling(252, min_periods=1).sum() / close
    eps_3q = eps.fillna(0).rolling(3).sum()
    growth = (eps_3q / eps_3q.shift(4).replace(0, np.nan) - 1).fillna(0)
    est_yield = (div_yield * (1 + growth).clip(lower=0)).fillna(0)
    div_annual = (board_dividend / close).rolling(520, min_periods=1).sum()

    conds = (close > 0) & (close > close.average(MA_DAYS)) & (roe.rolling(4).min() > 0)
    common = (market_value.rank(axis=1, pct=True) + div_annual.rank(axis=1, pct=True)
              + roe.rank(axis=1, pct=True))
    may = (common + div_yield.rank(axis=1, pct=True))[conds & (board_dividend > 0)].is_largest(TOP_N)
    dec = (common + est_yield.rank(axis=1, pct=True))[conds].is_largest(TOP_N)

    effective = review_effective_dates(close.index, [(5, 17), (12, 7)])
    position = pd.DataFrame(False, index=effective, columns=close.columns)
    for date in effective:
        picks = may if date.month == 5 else dec
        row = picks.reindex(index=[date], method="ffill").iloc[0]
        position.loc[date] = row.reindex(position.columns).fillna(False).astype(bool)
    return sim(position.loc[START:], resample=effective, position_limit=0.1, 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-00919-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()
