"""同業本益比產業選股＋個股條件：跑到最新資料的版本（/blog/industry-pe-comparison-stock-strategy 三項驗證的數字來源）。

條件與文中 VIP 區「策略優化」那段程式相同，只是不截斷結束日：
- 產業：原文列出、2018 年底前回測表現最好的 15 個產業（下方 INDUSTRIES；原程式取評分熱力圖
  前 15 名，原文說和報酬排名大致相同）
- 產業內本益比低於同業中位數的公司，任一產業選到就選入
- 個股條件：近 3 月平均營收連 3 個月高於近 12 月平均、單月營收年增 20% 以上、
  近 3 月平均營收年增 15% 以上、五日均量 100 張以上
- 符合條件中五日均量最小的 10 檔，每兩週換股、單檔上限 20%、停損 20%，
  sim() 預設手續費 0.1425% 與證交稅 0.3%
- 產業分類是 security_industry_themes 目前的版本，套用到整段歷史

統計口徑：日夏普 = 日報酬平均 / 標準差 × √252，不扣無風險利率；
0050 含息 = etl:adj_close 還原價買進持有，與策略同一段期間。
執行後會在目前目錄輸出 data.csv（淨值曲線）與 metrics.json（統計）。

    pip install finlab
    python strategy.py

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

import ast
import json

import pandas as pd

import finlab
from finlab import data
from finlab.backtest import sim
from finlab.dataframe import FinlabDataFrame

STRATEGY_NAME = "同業本益比產業選股＋個股條件"
INDUSTRIES = ["紡織", "電機機械", "大數據", "雲端運算", "醫療器材", "電動車輛產業", "貿易百貨", "食品",
              "軟體服務", "汽車", "金融", "太陽能產業", "石化及塑橡膠", "資通訊安全", "人工智慧"]
TOP_N = 10     # 持股檔數
YOY_MIN = 20   # 單月營收年增門檻（%）


def industry_position():
    themes = data.get("security_industry_themes").copy()
    themes["category"] = themes["category"].apply(ast.literal_eval)
    exploded = themes.explode("category")
    pe = data.get("price_earning_ratio:本益比")
    parts = []
    for ind in INDUSTRIES:
        stock_ids = sorted(set(exploded.loc[exploded["category"] == ind, "stock_id"]) & set(pe.columns))
        ind_pe = pe[stock_ids]
        parts.append(ind_pe < ind_pe.median(axis=1))
    position = pd.concat(parts, axis=1)
    # 一家公司可能橫跨多個產業，只要有一個產業選到就選入
    return FinlabDataFrame(position.T.groupby(level=0).max().T)


def build_report():
    vol = data.get("price:成交股數")
    rev = data.get("monthly_revenue:當月營收")
    rev_yoy = data.get("monthly_revenue:去年同月增減(%)")
    rev_ma3 = rev.average(3)
    rev_ma12 = rev.average(12)
    vol_ma5 = vol.average(5)

    extra_conds = (((rev_ma3 > rev_ma12).sustain(3)) & (rev_yoy >= YOY_MIN)
                   & (rev_ma3 / rev_ma3.shift(12) >= 1.15) & (vol_ma5 >= 100 * 1000))
    buy = industry_position() & extra_conds
    buy = buy * vol_ma5
    buy = buy[buy > 0].is_smallest(TOP_N)
    return sim(buy, position_limit=0.2, resample="2W", stop_loss=0.2, 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/industry-pe-comparison-stock-strategy/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()
