"""00905 2.0（益本比＋盈利動能＋股價動能，前 7%）：/blog/smart-etf-00905-optimization 三項驗證用的程式。

原文「最終結果」的程式，只是不截斷結束日、成本改用 sim() 預設：
- 股票池：上市櫃（含金融）
- 益本比＝每股盈餘 ÷ 收盤價；盈利動能（原文稱營利動能）＝（近一季 EPS － 前一季 EPS）÷ 收盤價
- 股價動能：原文沒附程式，照 00905 公開說明書寫成
  0.5 ×（近 6 個月報酬＋近 12 個月報酬）÷ 近三年週報酬年化標準差，無風險利率設 0
- 三項各自橫向標準化後平均，轉成多因子權重係數，取高於 93 分位數的股票、依係數加權
- 從 2020-08-10（特選 Smart 多因子指數發布日）起算，權重每天變動就調整（resample=None）
- 原文不計成本，這裡用 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 = "00905 2.0（益本比＋盈利動能＋股價動能，前 7%）"
QUANTILE = 0.93
LONG_MONTHS = 12
START = "2020-08-10"


def Z(df: pd.DataFrame) -> pd.DataFrame:
    """常態標準化：每天橫向 (x - 平均) / 標準差，超過 ±3 的當離群值不採納（同原文的 Z 函式）。"""
    df = df.replace([np.inf, -np.inf], np.nan)
    z = df.sub(df.mean(axis=1), axis=0).div(df.std(axis=1, ddof=0), axis=0)
    return z.where(z.abs() <= 3)


def to_weight(z: pd.DataFrame) -> pd.DataFrame:
    """多因子權重係數：Z ≥ 0 時 1 + Z，Z < 0 時 (1 - Z)^-1。"""
    return z.where(z < 0, 1 + z).where(z >= 0, 1 / (1 - z))


def price_momentum(adj: pd.DataFrame, index: pd.Index) -> FinlabDataFrame:
    """股價動能＝0.5 ×（近 6 個月報酬＋近 LONG_MONTHS 個月報酬）÷ 近三年週報酬年化標準差（無風險利率設 0）。"""
    weekly = adj.resample("W-FRI").last()
    sigma = (weekly.ffill().pct_change(fill_method=None).rolling(156, min_periods=104).std()
             * np.sqrt(52)).resample("ME").last()
    m = adj.resample("ME").last()
    mom = 0.5 * ((m / m.shift(6) - 1) + (m / m.shift(LONG_MONTHS) - 1)) / sigma
    return mom.reindex(index, method="ffill")


def build_report():
    with data.universe(market="TSE_OTC"):
        close = data.get("price:收盤價")
        adj = data.get("etl:adj_close")
        eps = data.get("financial_statement:每股盈餘")
    earnings_yield = (eps / close).reindex(close.index, method="ffill")
    earnings_mom = ((eps - eps.shift(1)) / close).reindex(close.index, method="ffill")
    score = (Z(earnings_yield) + Z(earnings_mom) + Z(price_momentum(adj, close.index))) / 3
    weight = to_weight(score)
    weight = weight[weight.gt(weight.quantile_row(QUANTILE), axis=0)]
    return sim(weight.loc[START:], resample=None, 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/smart-etf-00905-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()
