"""高動能＋低波動選股範本：三項穩健性驗證用的重跑程式（/blog/taiwan-stock-python-stock-selection）。

條件與文中「策略回測與分析」的程式相同，差別有兩處：手續費改用 sim() 預設（原程式打三折），
以及 pct_change 寫明 fill_method=None（pandas 3 的預設；寫明後 pandas 2 也算出同樣結果）。
- 上市櫃；60 日 RSV 全市場排名前 10%、20 日波動排名低於 80%、20 日波動排名高於 60 日、
  收盤價站上 60 日均線、當日成交量 > 100 張
- 取收盤價最低的 200 檔（實際平均約 57 檔符合條件），每月換股

統計口徑：日夏普 = 日報酬平均 / 標準差 × √252，不扣無風險利率；
0050 含息 = etl:adj_close 還原價買進持有，與策略同一段期間；前後兩段 = 策略期間對半切。
把程式開頭的兩個參數換成熱圖上的其他值，就能重跑對應的那一格。

    pip install finlab
    python strategy.py

finlab 需要資料時會自動引導登入，不需要在程式裡填 token。
"""

from functools import reduce

import pandas as pd

import finlab
from finlab import data
from finlab.backtest import sim

STRATEGY_NAME = "高動能低波動選股範本"
MOMENTUM_RANK = 0.9   # 動能分位門檻：熱圖 0.85、0.9、0.95
VOL_RANK = 0.8        # 波動分位上限：熱圖 0.7、0.8、0.9


def build_report():
    with data.universe("TSE_OTC"):
        close = data.get("price:收盤價")
        volume = data.get("price:成交股數")

    ret = close.pct_change(fill_method=None)
    std20 = ret.rolling(20).std().rank(axis=1, pct=True)[close.notna()]   # 短期波動
    std60 = ret.rolling(60).std().rank(axis=1, pct=True)[close.notna()]   # 長期波動
    rsv60 = ((close - close.rolling(60).min())                            # 股價相對高低
             / (close.rolling(60).max() - close.rolling(60).min())[close.notna()])

    conds = [
        rsv60.rank(axis=1, pct=True) > MOMENTUM_RANK,  # 高動能
        std20.rank(axis=1, pct=True) < VOL_RANK,       # 低波動
        std20 > std60,                                 # 短期價格變化大
        close > close.average(60),
        volume > 100_000,
    ]
    position = close[reduce(lambda i, j: i & j, conds)].is_smallest(200)
    return sim(position, resample="M", 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):]
    mid = creturn.index[0] + (creturn.index[-1] - creturn.index[0]) / 2
    for label, part in [("全期", creturn), ("前段", creturn.loc[:mid]), ("後段", creturn.loc[mid:])]:
        s = curve_stats(part)
        b = curve_stats(bench_all.loc[part.index[0]:part.index[-1]])
        print(f"{label} {part.index[0].date()} 至 {part.index[-1].date()}："
              f"策略年化 {s['cagr']:.1%}、日夏普 {s['daily_sharpe']:.2f}、最大回撤 {s['max_drawdown']:.1%}；"
              f"0050 含息年化 {b['cagr']:.1%}、日夏普 {b['daily_sharpe']:.2f}、最大回撤 {b['max_drawdown']:.1%}")


if __name__ == "__main__":
    main()
