"""LPPLS 泡沫擇時 0050：三項穩健性驗證（/blog/lppl-bubble-crash-prediction-python 驗證段的數字來源）。

LPPLS 信心指標的計算與文章附的 strategy.py 相同（同一組窗格、過濾條件與固定種子），只是不截斷結束日：
- 每 5 個交易日一個觀測點，對 30~120 天共 19 個窗格擬合，通過過濾的比例就是信心值
- 持有 0050；正泡沫信心 >= 出場門檻出場，信心退回 <= 回補門檻或負泡沫信心 >= 0.2 回補
- 部位變更於訊號的次一交易日收盤成交，sim() 預設手續費 0.1425% 與證交稅 0.3%

三項檢查：
1. 鄰近參數：出場門檻 0.15、0.20、0.25 乘上回補門檻 0.05、0.10、0.15，9 組日夏普要有 7 組以上高於同期 0050 含息
2. 前後兩段：期間對半切，兩段都要高於 0050 含息
3. 交易成本：sim() 預設手續費與證交稅

統計口徑：日夏普 = 日報酬平均 / 標準差 × √252，不扣無風險利率；
0050 含息 = etl:adj_close 還原價買進持有，與策略同一段期間、不扣成本。
擬合約 9,000 次，一般筆電跑幾分鐘。執行後會在目前目錄輸出 data.csv（淨值曲線）與 metrics.json（統計）。
想重現文章首發的數字，設環境變數 DATA_END=2026-06-09 再執行。

    pip install finlab numpy scipy
    python strategy.py

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

import json
import os
from concurrent.futures import ProcessPoolExecutor

import numpy as np
import pandas as pd
from scipy.optimize import minimize

START = "2018-01-01"
END = os.environ.get("DATA_END")  # 不設就跑到最新資料
STRATEGY_NAME = "LPPLS 泡沫擇時 0050"

# ---------- LPPLS 設定 ----------
WINDOWS = list(range(30, 121, 5))      # 回看窗格 30~120 個交易日,共 19 個
OBS_STEP = 5                           # 每 5 個交易日計算一次信心指標
N_STARTS = 6                           # 每個窗格的多起點搜尋次數
SEED_BASE = 20260611                   # 固定種子,確保可重現

# 合格擬合的參數過濾條件(Sornette et al. 2015)
M_MIN, M_MAX = 0.01, 1.2               # 冪律指數 m
W_MIN, W_MAX = 2.0, 25.0               # log 週期角頻率 omega
OSC_MIN = 2.5                          # 窗格內至少 2.5 次完整震盪
DAMPING_MIN = 0.8                      # 阻尼比 m|B| / (omega|C|)
TC_LO_FRAC, TC_HI_FRAC = -0.05, 0.10   # tc 相對窗格長度的允許範圍

# 擇時門檻
EXIT_THRESHOLD = 0.20                  # 正泡沫信心 >= 0.2 出場
REENTER_THRESHOLD = 0.10               # 信心退回 <= 0.1 回補
NEG_REENTER = 0.20                     # 負泡沫信心 >= 0.2 直接回補(超跌反轉)
EXIT_GRID = [0.15, 0.20, 0.25]
REENTER_GRID = [0.05, 0.10, 0.15]

# 子行程共用的對數價格陣列(由 initializer 填入,避免重複序列化)
_LOGP: np.ndarray | None = None


def _init_worker(logp: np.ndarray) -> None:
    global _LOGP
    _LOGP = logp


def lppl_design_matrix(t: np.ndarray, tc: float, m: float, w: float) -> np.ndarray:
    """LPPL 線性部分的設計矩陣 [1, f, g, h]。"""
    dt = np.abs(tc - t) + 1e-8
    f = dt ** m
    log_dt = np.log(dt)
    g = f * np.cos(w * log_dt)
    h = f * np.sin(w * log_dt)
    return np.column_stack([np.ones_like(t), f, g, h])


def lppl_sse(theta: np.ndarray, t: np.ndarray, y: np.ndarray) -> float:
    """給定 (tc, m, omega),解出線性參數後的殘差平方和。"""
    tc, m, w = theta
    X = lppl_design_matrix(t, tc, m, w)
    coef, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
    residual = y - X @ coef
    return float(residual @ residual)


def fit_one_window(args: tuple[int, int]) -> dict:
    """擬合單一 (觀測點, 窗格長度),回傳參數與過濾結果。"""
    end_idx, win = args
    t1 = end_idx - win + 1
    t = np.arange(t1, end_idx + 1, dtype=float)
    y = _LOGP[t1:end_idx + 1]
    t2 = float(end_idx)
    dt_win = float(win)

    # 多起點 Nelder-Mead,種子由 (觀測點, 窗格) 決定,完全可重現
    rng = np.random.default_rng(SEED_BASE + end_idx * 1000 + win)
    bounds = [
        (t2 - 0.2 * dt_win, t2 + 0.2 * dt_win),  # tc
        (0.01, 1.99),                            # m
        (2.0, 25.0),                             # omega
    ]
    best = None
    for _ in range(N_STARTS):
        x0 = np.array([rng.uniform(lo, hi) for lo, hi in bounds])
        result = minimize(
            lppl_sse, x0, args=(t, y), method="Nelder-Mead",
            bounds=bounds, options={"maxiter": 400, "xatol": 1e-4, "fatol": 1e-8},
        )
        if best is None or result.fun < best.fun:
            best = result

    tc, m, w = best.x
    X = lppl_design_matrix(t, tc, m, w)
    coef, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
    A, B, C1, C2 = coef
    C = float(np.hypot(C1, C2))

    # 過濾條件:全部通過才算「合格擬合」
    osc = (w / (2 * np.pi)) * np.log((tc - t1) / (tc - t2)) if tc > t2 else 0.0
    damping = (m * abs(B)) / (w * C) if C > 0 else np.inf
    tc_ok = (t2 + TC_LO_FRAC * dt_win) <= tc <= (t2 + TC_HI_FRAC * dt_win)
    qualified = (
        (M_MIN < m < M_MAX)
        and (W_MIN < w < W_MAX)
        and tc_ok
        and (osc > OSC_MIN)
        and (damping > DAMPING_MIN)
    )
    return {
        "end_idx": end_idx,
        "window": win,
        "tc": float(tc),
        "m": float(m),
        "omega": float(w),
        "B": float(B),
        "qualified_pos": bool(qualified and B < 0),
        "qualified_neg": bool(qualified and B > 0),
    }


def build_exposure(pos_conf: pd.Series, neg_conf: pd.Series,
                   exit_threshold=EXIT_THRESHOLD, reenter_threshold=REENTER_THRESHOLD) -> pd.Series:
    """狀態機:正泡沫信心高出場,信心退潮或負泡沫高回補。"""
    exposure = pd.Series(1.0, index=pos_conf.index)
    holding = True
    for date in pos_conf.index:
        p = pos_conf.loc[date]
        n = neg_conf.loc[date]
        if holding and p >= exit_threshold:
            holding = False
        elif not holding and (p <= reenter_threshold or n >= NEG_REENTER):
            holding = True
        exposure.loc[date] = 1.0 if holding else 0.0
    return exposure


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


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:
    import finlab
    from finlab import data
    from finlab.backtest import sim

    finlab.login()
    price = data.get("etl:adj_close")["0050"].dropna()
    if END:
        price = price[price.index <= END]
    logp = np.log(price.values)
    dates = price.index

    # 觀測點:每 5 個交易日一個,需有 120 天歷史,從 2017-07 起算暖身
    first_obs = max(120, int(np.searchsorted(dates, np.datetime64("2017-07-01"))))
    obs_idx = list(range(first_obs, len(dates), OBS_STEP))
    tasks = [(i, w) for i in obs_idx for w in WINDOWS]
    print(f"fitting {len(tasks)} windows on {len(obs_idx)} observation dates...")
    with ProcessPoolExecutor(max_workers=8, initializer=_init_worker, initargs=(logp,)) as executor:
        fits = pd.DataFrame(list(executor.map(fit_one_window, tasks, chunksize=32)))

    grouped = fits.groupby("end_idx")[["qualified_pos", "qualified_neg"]].mean()
    pos_conf = pd.Series(grouped["qualified_pos"].values,
                         index=dates[grouped.index]).reindex(dates).ffill().fillna(0)
    neg_conf = pd.Series(grouped["qualified_neg"].values,
                         index=dates[grouped.index]).reindex(dates).ffill().fillna(0)
    pos_conf, neg_conf = pos_conf[dates >= START], neg_conf[dates >= START]
    bench_all = price[price.index >= START]

    def timing_curve(exit_threshold=EXIT_THRESHOLD, reenter_threshold=REENTER_THRESHOLD, **cost):
        exposure = build_exposure(pos_conf, neg_conf, exit_threshold, reenter_threshold)
        report = sim(pd.DataFrame({"0050": exposure}), upload=False, name=STRATEGY_NAME, **cost)
        return report.creturn.reindex(bench_all.index).ffill().fillna(1.0), exposure

    runs = {(x, r): timing_curve(x, r) for x in EXIT_GRID for r in REENTER_GRID}
    creturn, exposure = runs[EXIT_THRESHOLD, REENTER_THRESHOLD]
    main_stats = window_stats(creturn, bench_all)
    grid = {f"{x}|{r}": {**window_stats(c, bench_all), "trades": int((e.diff().abs() > 0).sum())}
            for (x, r), (c, e) in runs.items()}
    mid = creturn.index[creturn.index.searchsorted(creturn.index[0] + (creturn.index[-1] - creturn.index[0]) / 2)]
    halves = {"first": window_stats(creturn.loc[:mid], bench_all),
              "second": window_stats(creturn.loc[mid:], bench_all)}
    no_cost, _ = timing_curve(fee_ratio=0, tax_ratio=0)

    s, b = main_stats["strategy"], main_stats["benchmark_0050"]
    s.update(time_in_market=exposure.mean(), trades=int((exposure.diff().abs() > 0).sum()))
    print(f"期間 {main_stats['window']}，持股時間 {s['time_in_market']:.1%}，進出 {s['trades']} 筆")
    print(f"策略：年化 {s['cagr']:.2%}，日夏普 {s['daily_sharpe']:.2f}，最大回撤 {s['max_drawdown']:.2%}")
    print(f"0050 含息：年化 {b['cagr']:.2%}，日夏普 {b['daily_sharpe']:.2f}，最大回撤 {b['max_drawdown']:.2%}")
    wins = sum(g["strategy"]["daily_sharpe"] > g["benchmark_0050"]["daily_sharpe"] for g in grid.values())
    print(f"鄰近參數：{wins}/9 組日夏普高於 0050 含息")
    for k, g in grid.items():
        print(f"  出場 {k.split('|')[0]} 回補 {k.split('|')[1]}：{g['strategy']['daily_sharpe']:.2f}（進出 {g['trades']} 筆）")
    for k, h in halves.items():
        print(f"{k} {h['window']}：{h['strategy']['daily_sharpe']:.2f} 對 {h['benchmark_0050']['daily_sharpe']:.2f}")

    signal_days = pos_conf[pos_conf >= EXIT_THRESHOLD]
    curves = pd.DataFrame({STRATEGY_NAME: creturn, "0050含息": bench_all / bench_all.iloc[0],
                           "pos_conf": pos_conf, "neg_conf": neg_conf, "exposure": exposure})
    curves.index.name = "date"
    curves.round(6).to_csv("data.csv")
    metrics = {
        "window": main_stats["window"],
        "star": STRATEGY_NAME,
        "variants": {STRATEGY_NAME: s},
        "benchmark_0050": b,
        "no_cost": curve_stats(no_cost),
        "grid": grid,
        "halves": halves,
        "exit_signal_dates": [str(d.date()) for d in signal_days.index],
        "max_pos_conf": {"value": float(pos_conf.max()), "date": str(pos_conf.idxmax().date())},
        "fits": len(tasks),
        "run_date": str(pd.Timestamp.today().date()),
        "finlab_version": finlab.__version__,
        "generated_by": "static/blog/lppl-bubble-crash-prediction-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()
