"""金控股配對交易：三項穩健性驗證（/blog/taiwan-stock-correlation-python 驗證段的數字來源）。

條件與文中回測相同，只是不截斷結束日：
- 股票池：14 檔金控股，2018 年起每半年重選配對
- 形成期：進場前 252 個交易日，日報酬相關大於 0.6 且 Engle-Granger 共整合 p 小於 0.05，取 p 值最小的 5 組
- 交易期：形成期 OLS 對沖比算價差，60 日滾動 z-score，|z| > 2 進場（作多便宜腿、放空貴腿各 50%），
  z 回到 0 或交易期結束時出場
- 成本：手續費 0.1425%、證交稅 0.3%（與 sim() 台股預設相同），另加借券成本年化 1%（估計值）。
  策略有放空部位，損益由本程式自行計算，不經 sim()

三項檢查：
1. 鄰近參數：進場門檻 |z| 1.5、2、2.5 乘上 z-score 滾動天數 40、60、80，9 組日夏普要有 7 組以上高於同期 0050 含息
2. 前後兩段：期間對半切，兩段都要高於 0050 含息
3. 交易成本：上述成本（另跑不扣成本的對照）

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

    pip install finlab statsmodels
    python strategy.py

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

import json
from itertools import combinations

import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import coint

import finlab
from finlab import data

STRATEGY_NAME = "金控股配對交易"
START = "2018-01-01"
FIN = ["2880", "2881", "2882", "2883", "2884", "2885", "2886", "2887", "2888", "2889", "2890", "2891", "2892", "5880"]
FORM = 252          # 形成期長度（交易日）
CORR_MIN, P_MAX = 0.6, 0.05
MAX_PAIRS = 5
Z_IN = 2.0          # |z| 超過此值進場
Z_WIN = 60          # z-score 滾動視窗
COST = {"fee": 0.001425, "tax": 0.003, "borrow": 0.01}
Z_IN_GRID = [1.5, 2.0, 2.5]
Z_WIN_GRID = [40, 60, 80]


def walk_forward(prices: pd.DataFrame) -> list:
    """每半年用前 252 個交易日重選配對，回傳 [(交易期日期, [(A, B, 對沖比)])]。"""
    rets = prices.pct_change(fill_method=None)
    logp = np.log(prices)
    dates, end = prices.index, prices.index[-1]
    periods = []
    for period_start in pd.date_range(START, end, freq="6MS"):
        period_end = min(period_start + pd.DateOffset(months=6) - pd.Timedelta(days=1), end)
        history = dates[dates < period_start][-FORM:]
        trade_idx = dates[(dates >= period_start) & (dates <= period_end)]
        if len(history) < FORM or len(trade_idx) == 0:
            continue
        candidates = []
        for a, b in combinations(prices.columns, 2):
            pa, pb = logp.loc[history, a], logp.loc[history, b]
            if pa.isna().any() or pb.isna().any():
                continue
            if not rets.loc[history, a].corr(rets.loc[history, b]) > CORR_MIN:
                continue
            pvalue = coint(pa, pb)[1]
            if pvalue < P_MAX:
                candidates.append((pvalue, a, b, float(np.polyfit(pb, pa, 1)[0])))
        periods.append((trade_idx, [c[1:] for c in sorted(candidates)[:MAX_PAIRS]]))
    return periods


def trade_pair(prices, a, b, beta, trade_idx, z_in, z_win, fee, tax, borrow) -> pd.Series:
    """交易期：z-score 狀態機，回傳該配對的每日報酬（已扣成本）。"""
    rets = prices.pct_change(fill_method=None)
    spread = np.log(prices[a]) - beta * np.log(prices[b])
    z = (spread - spread.rolling(z_win).mean()) / spread.rolling(z_win).std()
    position = 0  # +1：作多 A 放空 B；-1：放空 A 作多 B
    pair_ret = pd.Series(0.0, index=trade_idx)
    for i, d in enumerate(trade_idx):
        ra, rb, zv = rets.at[d, a], rets.at[d, b], z.get(d, np.nan)
        if position != 0:
            if np.isnan(ra) or np.isnan(rb):  # 下市或停牌，強制出場
                position = 0
                continue
            pair_ret.iloc[i] = position * 0.5 * (ra - rb) - borrow / 252 * 0.5
            crossed = (position == -1 and zv <= 0) or (position == 1 and zv >= 0)
            if crossed or i == len(trade_idx) - 1:
                pair_ret.iloc[i] -= 0.5 * (fee + tax) + 0.5 * fee  # 出場成本
                position = 0
        elif not np.isnan(zv) and abs(zv) > z_in and i < len(trade_idx) - 1:
            position = -1 if zv > 0 else 1
            pair_ret.iloc[i] -= 0.5 * fee + 0.5 * (fee + tax)  # 進場成本
    return pair_ret


def strategy_curve(prices, periods, z_in=Z_IN, z_win=Z_WIN, cost=COST) -> pd.Series:
    returns = []
    for trade_idx, pairs in periods:
        port = pd.Series(0.0, index=trade_idx)
        for a, b, beta in pairs:
            port += trade_pair(prices, a, b, beta, trade_idx, z_in, z_win, **cost) / len(pairs)
        returns.append(port)
    return (1 + pd.concat(returns).sort_index()).cumprod()


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 trimmed(creturn: pd.Series) -> pd.Series:
    """從第一次有部位的前一天起算。"""
    creturn = creturn.dropna()
    first_move = (creturn != creturn.iloc[0]).argmax()
    return creturn.iloc[max(first_move - 1, 0):]


def window_stats(creturn: pd.Series, bench_all: pd.Series) -> dict:
    bench = bench_all.loc[creturn.index[0]:creturn.index[-1]]
    return {"window": f"{creturn.index[0].date()}/{creturn.index[-1].date()}",
            "strategy": curve_stats(creturn), "benchmark_0050": curve_stats(bench)}


def rounded(obj):
    if isinstance(obj, dict):
        return {k: rounded(v) for k, v in obj.items()}
    return round(float(obj), 6) if isinstance(obj, float) else obj


def main() -> None:
    finlab.login()
    adj = data.get("etl:adj_close")
    bench_all = adj["0050"].dropna()
    prices = adj[[c for c in FIN if c in adj.columns]].loc["2016-01-01":]
    periods = walk_forward(prices)
    creturn = trimmed(strategy_curve(prices, periods))
    mid = creturn.loc[creturn.index[0] + (creturn.index[-1] - creturn.index[0]) / 2:].index[0]
    result = {
        "main": window_stats(creturn, bench_all),
        "no_cost": curve_stats(trimmed(strategy_curve(prices, periods, cost=dict.fromkeys(COST, 0)))),
        "grid": {f"z 視窗 {w} 日、進場 |z| {z}": window_stats(trimmed(strategy_curve(prices, periods, z, w)), bench_all)
                 for w in Z_WIN_GRID for z in Z_IN_GRID},
        "halves": {"first": window_stats(creturn.loc[:mid], bench_all),
                   "second": window_stats(creturn.loc[mid:], bench_all)},
    }

    wins = sum(g["strategy"]["daily_sharpe"] > g["benchmark_0050"]["daily_sharpe"] for g in result["grid"].values())
    print(f"期間 {result['main']['window']}")
    for label, s in [("策略", result["main"]["strategy"]), ("0050 含息", result["main"]["benchmark_0050"]),
                     ("不扣成本", result["no_cost"])]:
        print(f"{label}：年化 {s['cagr']:.2%}，日夏普 {s['daily_sharpe']:.2f}，最大回撤 {s['max_drawdown']:.2%}")
    print(f"鄰近參數：{wins}/9 組日夏普高於 0050 含息")
    for label, g in result["grid"].items():
        print(f"  {label}：{g['strategy']['daily_sharpe']:.2f}"
              f"（年化 {g['strategy']['cagr']:.2%}；0050 {g['benchmark_0050']['daily_sharpe']:.2f}）")
    for key, part in result["halves"].items():
        print(f"{key} {part['window']}：{part['strategy']['daily_sharpe']:.2f} 對 {part['benchmark_0050']['daily_sharpe']:.2f}")

    metrics = {
        "star": STRATEGY_NAME,
        **result,
        "run_date": str(pd.Timestamp.today().date()),
        "finlab_version": finlab.__version__,
        "generated_by": "static/blog/taiwan-stock-correlation-python/validation/strategy.py",
    }
    with open("metrics.json", "w", encoding="utf-8") as f:
        json.dump(rounded(metrics), f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    main()
