"""長週期 RSI 追漲策略：三項穩健性驗證用的重跑程式（/blog/rsi-stock-selection-long-period）。

條件照原文：
- 買進：60 日 RSI > 55，而且最新已公布的 ROE（稅後）> 0
- 賣出：收盤跌破 60 日均線（季線），或持有滿 60 個交易日；當天賣出的不在同一天買回
- 符合條件的全部等權持有，不限檔數；訊號當天收盤確認，sim() 隔天收盤成交
RSI 用 Wilder 平滑；ROE 是季資料，從各公司財報上傳日起才用（FinLab 季財報從 2013 年第 1 季起）。
原文沒有計入手續費，這裡用 sim() 預設手續費 0.1425% 與證交稅 0.3%。

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

    pip install finlab
    python strategy.py

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

import numpy as np
import pandas as pd

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

STRATEGY_NAME = "長週期 RSI 追漲"
RSI_PERIOD = 60       # RSI 週期：熱圖 40、60、80
RSI_THRESHOLD = 55    # RSI 門檻：熱圖 50、55、60
MAX_HOLD_DAYS = 60


def rsi(close: pd.DataFrame, n: int) -> pd.DataFrame:
    diff = close.diff()
    gain = diff.clip(lower=0).ewm(alpha=1 / n, adjust=False, min_periods=n).mean()
    loss = (-diff.clip(upper=0)).ewm(alpha=1 / n, adjust=False, min_periods=n).mean()
    return 100 * gain / (gain + loss)


def build_report(**sim_kwargs):
    close = pd.DataFrame(data.get("price:收盤價"))
    roe = pd.DataFrame(data.get("fundamental_features:ROE稅後").index_str_to_date())
    roe = roe.reindex(roe.index.union(close.index)).ffill().reindex(close.index)
    close = close[roe.columns.intersection(close.columns)]

    entry = (rsi(close, RSI_PERIOD) > RSI_THRESHOLD) & (roe[close.columns] > 0)
    exit_ = close < close.rolling(60).mean()

    # 逐日判斷：持有中遇到跌破季線或滿 60 天就賣，空手時符合買進條件就買
    held = np.zeros(close.shape, dtype=bool)
    count = np.zeros(close.shape[1], dtype=int)
    entry_v, exit_v = entry.values, exit_.values
    for i in range(len(close)):
        holding = count > 0
        sell = holding & (exit_v[i] | (count >= MAX_HOLD_DAYS))
        count[holding] += 1
        count[sell] = 0
        count[~holding & entry_v[i] & ~exit_v[i]] = 1     # 只買昨天空手的股票，今天賣出的不會同一天買回
        held[i] = count > 0
    position = pd.DataFrame(held, index=close.index, columns=close.columns)
    position = position.loc[:, position.any()]
    return sim(position, upload=False, name=STRATEGY_NAME, **sim_kwargs)


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()
