# -*- coding: utf-8 -*-
"""股價淨值比（PB）選股回測：重現文章裡每一張表的數字。

對應文章：https://finlab.finance/blog/price-book-ratio-stock-strategy
資料截止日：2026-09-30（2026-10-11 重跑）
基準：0050 含息（etl:adj_close 還原價買進持有，不含交易成本），一律與比較對象同一天起算
成本：finlab sim() 台股預設（手續費 0.1425%、賣出證交稅 0.3%），未另設滑價

三層實驗：
  1. 五分位：全上市櫃有 PB 資料的個股，每季按 PB 由低到高分五組，等權持有
     另附「排除金融保險業後重分五組」的最低組，檢查金融股對結果的影響
  2. 絕對門檻：PB<0.5、PB<0.8、PB<1.0 全部持有，每季換股
  3. 排雷策略：流動性與股價過濾 → 季線之上 → 池內 PB 最低 20% →
     近四季經常稅後淨利 > 0、每股淨值不低於一年前 → PB×股價最小 20 檔，每季換股
     另附拿掉兩條排雷的對照組，隔離排雷的貢獻

執行：
  uv run --python 3.12 --with finlab python strategy.py

印出內容：文章各表（五分位、逐年報酬、門檻、排雷策略、2018 起同窗、
2026-06 之後的新資料、全市場 PB 分位數）。想用最新資料重跑，把 DATA_END 改成 None
（數字會隨新資料與 finlab 歷史資料修補而變動）。

本程式僅供量化研究與教學，過去績效不代表未來表現，不構成任何投資建議。
"""
from __future__ import annotations

import finlab
import pandas as pd
from finlab import data
from finlab.backtest import sim

DATA_END = "2026-09-30"   # 文章的資料截止日；改成 None 取最新資料
PREV_END = "2026-06-09"   # 上一版文章的資料截止日，用來追蹤之後的新資料
STRAT_START = "2013-07-01"  # 排雷要一年淨值歷史與四季財報，策略層從這天開始
COMPARE_START = "2018-01-01"  # 與站內其他策略文相同的比較起點
EVENT_DATES = ["2015-08-24", "2020-03-19"]  # 全球股災、疫情低點
THRESHOLDS = [0.5, 0.8, 1.0]
CHEAP_LINE = 1.2   # 「PB 小於 1.2 算便宜」這類絕對標準
TOP_N = 20
REBALANCE = "Q"    # 每季最後一個交易日換股
QUARTERS_PER_YEAR = 4
TRADING_DAYS_PER_YEAR = 252
LOOKBACK_ONE_YEAR = 245  # 約一年的交易日
MIN_AVG_VOLUME = 500_000  # 60 日均量（股）
MIN_PRICE = 5


# ---------- 統計工具 ----------
def summarize(curve: pd.Series) -> dict:
    """淨值序列的績效指標，期間以序列首末日為準。"""
    curve = curve.dropna()
    daily = curve.pct_change().dropna()
    monthly = curve.resample("ME").last().pct_change().dropna()
    years = (curve.index[-1] - curve.index[0]).days / 365.25
    total = curve.iloc[-1] / curve.iloc[0] - 1
    return {
        "start": str(curve.index[0].date()),
        "end": str(curve.index[-1].date()),
        "cagr": round(((1 + total) ** (1 / years) - 1) * 100, 2),
        "daily_sharpe": round(daily.mean() / daily.std() * TRADING_DAYS_PER_YEAR ** 0.5, 2),
        "daily_sortino": round(daily.mean() / daily[daily < 0].std() * TRADING_DAYS_PER_YEAR ** 0.5, 2),
        "monthly_sortino": round(monthly.mean() / monthly[monthly < 0].std() * 12 ** 0.5, 2),
        "max_drawdown": round((curve / curve.cummax() - 1).min() * 100, 2),
        "annual_vol": round(daily.std() * TRADING_DAYS_PER_YEAR ** 0.5 * 100, 2),
        "total_return": round(total * 100, 1),
    }


def from_start(curve: pd.Series, start) -> pd.Series:
    """從 start 當天起算、歸一成 1 的淨值。"""
    curve = curve[curve.index >= start].dropna()
    return curve / curve.iloc[0]


def holdings_stats(report) -> dict:
    """每季換股日的持股檔數與周轉率（等權目標權重的單邊換手）。"""
    position = report.position
    held = (position > 0).sum(axis=1)
    weights = position.div(position.sum(axis=1), axis=0).fillna(0)
    one_way = (weights.diff().abs().sum(axis=1) / 2).iloc[1:]
    return {
        "avg_holdings": round(float(held.mean()), 1),
        "min_holdings": int(held.min()),
        "min_holdings_date": str(held.idxmin().date()),
        "max_holdings": int(held.max()),
        "max_holdings_date": str(held.idxmax().date()),
        "annual_turnover": round(float(one_way.mean()) * QUARTERS_PER_YEAR, 2),
        "holdings_series": held,
    }


def yearly_returns(curve: pd.Series) -> pd.Series:
    """逐年報酬（%）；第一年從序列首日起算，最後一年算到資料截止日。"""
    year_end = curve.groupby(curve.index.year).last()
    previous = year_end.shift(1)
    previous.iloc[0] = curve.iloc[0]
    return (year_end / previous - 1) * 100


def period_return(curve: pd.Series, start, end) -> float:
    """start 當天收盤到 end 當天收盤的報酬（%）。"""
    return round(float(curve.asof(pd.Timestamp(end)) / curve.asof(pd.Timestamp(start)) - 1) * 100, 2)


# ---------- 回測 ----------
def run_all() -> dict:
    if DATA_END is not None:
        data.truncate_end = DATA_END  # 所有資料（含 sim 內部抓價）都截在資料截止日

    close = data.get("price:收盤價")
    volume = data.get("price:成交股數")
    adj_close = data.get("etl:adj_close")
    pb = data.get("price_earning_ratio:股價淨值比")
    net_income = data.get("fundamental_features:經常稅後淨利").index_str_to_date()
    categories = data.get("security_categories")

    pb = pb.where(pb > 0)  # 淨值為負或缺值的股票不列入
    pb_market = pb.where(close.notna() & pb.notna())  # 當天有收盤價與 PB 的全上市櫃個股

    # 1) 五分位：每天按全市場 PB 百分位分組，sim 在每季最後一個交易日換股
    pb_rank = pb_market.rank(axis=1, pct=True)
    quintile_reports = {}
    for k in range(1, 6):
        in_group = (pb_rank > (k - 1) / 5) & (pb_rank <= k / 5)
        quintile_reports[f"Q{k}"] = sim(in_group, resample=REBALANCE, upload=False)

    # 排除金融保險業後重新分五組，只取最低組
    financial_ids = set(
        categories.loc[categories["category"].astype(str).str.contains("金融"), "stock_id"].astype(str)
    )
    non_financial = [c for c in pb_market.columns if c not in financial_ids]
    q1_ex_fin = pb_market[non_financial].rank(axis=1, pct=True) <= 0.2
    q1_ex_fin_report = sim(q1_ex_fin, resample=REBALANCE, upload=False)

    # 2) 絕對門檻：PB 低於門檻全部持有
    threshold_reports = {}
    for line in THRESHOLDS:
        below = pb_market < line
        threshold_reports[f"PB<{line}"] = sim(below, resample=REBALANCE, upload=False)

    # 3) 排雷策略：流動性、股價、季線、池內 PB 百分位、兩條排雷
    pool = (volume.rolling(60).mean() > MIN_AVG_VOLUME) & (close > MIN_PRICE)
    above_ma = close > close.rolling(60).mean()
    profitable = net_income.rolling(4).sum().reindex(close.index, method="ffill") > 0
    book_per_share = close / pb
    book_not_shrinking = book_per_share >= book_per_share.shift(LOOKBACK_ONE_YEAR)
    low_pb = pb.where(pool).rank(axis=1, pct=True) <= 0.2

    with_filters = low_pb & profitable & book_not_shrinking & above_ma
    without_filters = low_pb & above_ma
    strategy_position = (pb * close).where(with_filters).is_smallest(TOP_N)
    control_position = (pb * close).where(without_filters).is_smallest(TOP_N)
    strategy_report = sim(strategy_position[strategy_position.index >= STRAT_START],
                          resample=REBALANCE, upload=False)
    control_report = sim(control_position[control_position.index >= STRAT_START],
                         resample=REBALANCE, upload=False)

    bench_price = adj_close["0050"].dropna()

    # ---- 同窗起算：各層取所有比較對象首個淨值日的最晚者，0050 同一天起算 ----
    factor_reports = {**quintile_reports, **threshold_reports, "Q1 排除金融": q1_ex_fin_report}
    factor_start = max(r.creturn.dropna().index[0] for r in factor_reports.values())
    factor_curves = {name: from_start(r.creturn, factor_start) for name, r in factor_reports.items()}
    factor_curves["0050"] = from_start(bench_price, factor_start)

    strat_reports = {"排雷策略": strategy_report, "無排雷對照": control_report}
    strat_start = max(r.creturn.dropna().index[0] for r in strat_reports.values())
    strat_curves = {name: from_start(r.creturn, strat_start) for name, r in strat_reports.items()}
    strat_curves["0050"] = from_start(bench_price, strat_start)

    compare_start = strategy_report.creturn.index[strategy_report.creturn.index >= COMPARE_START][0]
    compare_curves = {
        "排雷策略": from_start(strategy_report.creturn, compare_start),
        "0050": from_start(bench_price, compare_start),
    }

    # ---- 指標 ----
    factor_stats = {name: summarize(c) for name, c in factor_curves.items()}
    strat_stats = {name: summarize(c) for name, c in strat_curves.items()}
    compare_stats = {name: summarize(c) for name, c in compare_curves.items()}
    holdings = {name: holdings_stats(r) for name, r in {**factor_reports, **strat_reports}.items()}

    # 最低組裡金融保險業的檔數占比（每季換股日）
    q1_held = quintile_reports["Q1"].position > 0
    fin_cols = [c for c in q1_held.columns if c in financial_ids]
    fin_share = q1_held[fin_cols].sum(axis=1) / q1_held.sum(axis=1) * 100

    # ---- 逐年報酬：最低組、最高組 vs 0050 ----
    yearly = pd.DataFrame({name: yearly_returns(factor_curves[name]) for name in ["Q1", "Q5", "0050"]})

    # ---- 2024 起累積報酬、上一版截止日之後的新資料 ----
    since_2024 = {name: period_return(factor_curves[name], "2023-12-31", factor_stats[name]["end"])
                  for name in ["Q1", "Q2", "Q3", "Q4", "Q5", "0050"]}
    forward_curves = {"Q1": factor_curves["Q1"], "Q5": factor_curves["Q5"],
                      "排雷策略": strat_curves["排雷策略"], "無排雷對照": strat_curves["無排雷對照"],
                      "0050": factor_curves["0050"]}
    end_date = factor_stats["0050"]["end"]
    forward = {name: period_return(c, PREV_END, end_date) for name, c in forward_curves.items()}

    # ---- 全市場 PB 分位數 ----
    pb_median = pb_market.median(axis=1)
    pb_p20 = pb_market.quantile(0.2, axis=1)
    cheap_share = (pb_market < CHEAP_LINE).sum(axis=1) / pb_market.notna().sum(axis=1) * 100
    snapshot_dates = [pd.Timestamp(d) for d in EVENT_DATES] + [pb_median.index[-1]]
    pb_snapshots = [{
        "date": str(d.date()),
        "median": round(float(pb_median.asof(d)), 2),
        "p20": round(float(pb_p20.asof(d)), 2),
        "share_below_cheap_line": round(float(cheap_share.asof(d)), 1),
    } for d in snapshot_dates]

    return {
        "data_end": end_date,
        "factor_start": str(factor_start.date()),
        "strategy_start": str(strat_start.date()),
        "compare_start": str(compare_start.date()),
        "factor_stats": factor_stats,
        "strategy_stats": strat_stats,
        "compare_stats": compare_stats,
        "holdings": holdings,
        "q1_financial_share": {
            "avg": round(float(fin_share.mean()), 1),
            "latest": round(float(fin_share.iloc[-1]), 1),
            "latest_date": str(fin_share.index[-1].date()),
        },
        "yearly": yearly,
        "since_2024": since_2024,
        "forward": forward,
        "pb_snapshots": pb_snapshots,
        "pb_series": pd.DataFrame({"median": pb_median, "p20": pb_p20, "share_below_1_2": cheap_share}),
        "curves": {"factor": factor_curves, "strategy": strat_curves, "compare": compare_curves},
        "strategy_report": strategy_report,
    }


# ---------- 輸出 ----------
def print_table(title: str, stats: dict, holdings: dict | None = None) -> None:
    print(f"\n=== {title} ===")
    for name, s in stats.items():
        line = (f"{name:<10} {s['start']}~{s['end']}  年化 {s['cagr']:6.2f}%  日夏普 {s['daily_sharpe']:.2f}  "
                f"日索提諾 {s['daily_sortino']:.2f}  月索提諾 {s['monthly_sortino']:.2f}  "
                f"最大回撤 {s['max_drawdown']:.2f}%  年化波動 {s['annual_vol']:.2f}%  總報酬 {s['total_return']:.1f}%")
        if holdings and name in holdings:
            h = holdings[name]
            line += (f"  平均持股 {h['avg_holdings']} 檔（最少 {h['min_holdings']} 檔 {h['min_holdings_date']}、"
                     f"最多 {h['max_holdings']} 檔 {h['max_holdings_date']}）  年周轉 {h['annual_turnover']} 倍")
        print(line)


def print_report(res: dict) -> None:
    print(f"資料截止日 {res['data_end']}")
    factor_names = ["Q1", "Q2", "Q3", "Q4", "Q5", "Q1 排除金融", "0050"]
    print_table("五分位（每季換股）", {n: res["factor_stats"][n] for n in factor_names}, res["holdings"])
    q1, q5 = res["factor_stats"]["Q1"], res["factor_stats"]["Q5"]
    print(f"Q1 減 Q5 年化差 {q1['cagr'] - q5['cagr']:.2f} 個百分點")
    share = res["q1_financial_share"]
    print(f"最低組裡金融保險業占比：平均 {share['avg']}%，{share['latest_date']} 為 {share['latest']}%")

    print("\n=== 逐年報酬（%）：最低、最高 PB 五分位 vs 0050 含息 ===")
    print(res["yearly"].round(1).to_string())
    print("2024 起累積報酬（%）：", res["since_2024"])

    threshold_names = [f"PB<{line}" for line in THRESHOLDS] + ["0050"]
    print_table("絕對門檻（每季換股）", {n: res["factor_stats"][n] for n in threshold_names}, res["holdings"])

    print_table("排雷策略與對照（每季換股）", res["strategy_stats"], res["holdings"])
    print_table("2018 起同窗", res["compare_stats"])

    print(f"\n=== {PREV_END} 之後到資料截止日的報酬（%） ===")
    print(res["forward"])

    print("\n=== 全市場 PB 分位數 ===")
    for snap in res["pb_snapshots"]:
        print(f"{snap['date']}  中位數 {snap['median']}  20% 分位數 {snap['p20']}  "
              f"PB<{CHEAP_LINE} 占比 {snap['share_below_cheap_line']}%")


if __name__ == "__main__":
    finlab.login()  # 首次取資料時會自動引導登入
    print_report(run_all())
