"""低價股動能突破策略：三項穩健性驗證用的重跑程式（/blog/low-price-stock-quant-strategy）。

條件與文中 VIP 區的「低價股策略」程式相同，差別有三處：手續費改用 sim() 預設（原程式打三折）、
upload=False，以及拿掉只影響 MAE/MFE 圖的 mae_mfe_window。
- 上市櫃、排除金融類股；近 5 日至少 1 日收盤價創 120 日新高、近 60 日高低區間 < 30%、
  收盤價在排除金融類股的上市櫃股票 40% 分位以下且 ≤ 25 元、5 日均量 > 100 張
- 取收盤價最低的 5 檔，每月換股、開盤價進出、單檔上限 20%、停損 5%

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

    pip install finlab
    python strategy.py

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

import pandas as pd

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

STRATEGY_NAME = "低價股策略"
NEW_HIGH_DAYS = 120   # 創新高天數：熱圖 100、120、140
PRICE_CAP = 25        # 股價上限（元）：熱圖 20、25、30


def build_report():
    df = data.get("security_categories")
    category_range = [ind for ind in list(set(df["category"])) if "金融" not in ind]
    with data.universe(market="TSE_OTC", category=category_range):
        close = data.get("price:收盤價")
        high = data.get("price:最高價")
        low = data.get("price:最低價")
        vol = data.get("price:成交股數")

        condition1 = (close == close.rolling(NEW_HIGH_DAYS).max()).sustain(5, 1)
        condition2 = (1 - low.rolling(60).min() / high.rolling(60).max()) < 0.3
        condition3 = close <= close.quantile_row(0.4)
        condition4 = close <= PRICE_CAP
        condition5 = vol.average(5) > 100 * 1000
        position = condition1 & condition2 & condition3 & condition4 & condition5

        position = close * (position.astype(int))
        position = position[position > 0].is_smallest(5)
        return sim(position, resample="M", upload=False, stop_loss=0.05, trade_at_price="open",
                   position_limit=1 / 5, 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()
