"""FinLab ETF category research. Run with finlab, pandas and numpy installed.

python research.py [equal|small|dividend|all] --out OUTPUT_DIRECTORY
Rules and 3x3 grids were fixed before reading this batch's results.
The output contains one directory per article: metrics.json, data.csv, buy-hold.csv
(plus avuv-common.csv for small caps), the FinLab-generated report_strategy.html and
the fixed equal-allocation report_baseline.html. No account token is stored in this file.
"""
import argparse
import json
import re
from datetime import datetime, timezone
from itertools import product
from functools import partial
from pathlib import Path

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

END = "2026-11-17"
CONFIG = {
    "equal": {"slug": "equal-weight-sp500-etf-backtest", "funds": ["RSP"],
              "a": [63, 126, 189], "b": [-0.02, 0, 0.02], "original": [126, 0],
              "start": "2016-10-31", "axes": ["lookback_days", "relative_return_threshold"]},
    "small": {"slug": "small-cap-etf-backtest", "funds": ["IJR", "IWM", "VBR"],
              "a": [63, 126, 189], "b": [1, 2, 3], "original": [126, 2],
              "start": "2016-10-31", "axes": ["lookback_days", "funds_held"]},
    "dividend": {"slug": "dividend-growth-etf-backtest", "funds": ["SCHD", "VIG", "DGRO", "VYM"],
                 "a": [1, 2, 3], "b": [1, 2, 3], "original": [2, 2],
                 "start": "2020-01-31", "axes": ["dividend_growth_years", "funds_held"]},
}
FUNDS = ["QQQ", "SPY", "RSP", "IJR", "IWM", "VBR", "AVUV", "SCHD", "VIG", "DGRO", "VYM", "BIL"]
backtest = partial(sim, resample="M", trade_at_price="close", market="us_fund", upload=False)


def split_list(actions, close, symbol):
    """Split factors by ex-date, kept only where the close moved by the factor."""
    rows = actions[(actions.symbol == symbol) & (actions.split_factor > 0) & (actions.date <= END)]
    c = close[symbol].dropna()
    return [(d, float(f)) for d, f, i in zip(rows.date, rows.split_factor, c.index.get_indexer(rows.date))
            if i > 0 and 0.7 < c.iloc[i] / c.iloc[i - 1] * f < 1.4]


def raw_dividends(actions, symbol):
    """Cash dividends per share at each ex-date, in the shares of that day."""
    rows = actions[(actions.symbol == symbol) & (actions.dividend > 0) & (actions.date <= END)]
    return rows.groupby("date").dividend.sum()


def cash_dividends(raw, splits):
    """Dividends per share in the latest share units: undo every later split."""
    cash = raw.copy()
    for date, factor in splits:
        cash.loc[cash.index < date] /= factor
    return cash


def missed_dividends(adj, close, raw):
    """Ex-dates where adj_close moved like the price alone, i.e. it left the dividend out."""
    c = close.dropna()
    missed = []
    for date, amount in raw.items():
        i = c.index.get_indexer([date])[0]
        if i <= 0:
            continue
        price_return = c.iloc[i] / c.iloc[i - 1] - 1
        total_return = adj.loc[date] / adj.loc[c.index[i - 1]] - 1
        if abs(total_return - price_return) < abs(total_return - price_return - amount / c.iloc[i - 1]):
            missed.append(str(date.date()))
    return missed


def load():
    data.set_market("us_fund")
    data.truncate_end = END
    price = pd.DataFrame(data.get("us_fund_price:adj_close"))[FUNDS].loc[:END]
    close = pd.DataFrame(data.get("us_fund_price:close"))[FUNDS].loc[:END]
    price = price.loc[price.SPY.notna()]
    actions = data.get("us_fund_corporate_actions")
    cash, audit = {}, {}
    for s in FUNDS:
        splits = split_list(actions, close, s)
        raw = raw_dividends(actions, s)
        missed = missed_dividends(price[s], close[s], raw)
        if missed:
            raise ValueError(f"{s}: adj_close missing dividends on {missed}")
        cash[s] = cash_dividends(raw, splits)
        audit[s] = {"start": str(price[s].first_valid_index().date()), "missed_dividends": missed,
                    "splits": [[str(d.date()), f] for d, f in splits], "dividend_events": len(raw)}
    return price, cash, audit


def trailing_cash(cash, days):
    """Ex-date cash over the previous calendar year, all in the latest share units."""
    cumulative = cash.cumsum()
    current = cumulative.reindex(days, method="ffill").fillna(0)
    old = cumulative.reindex(days - pd.DateOffset(years=1), method="ffill").fillna(0)
    return pd.Series(current.to_numpy() - old.to_numpy(), index=days)


def years_ago(frame, years):
    prior = frame.reindex(frame.index - pd.DateOffset(years=years), method="ffill")
    prior.index = frame.index
    return prior


def weights(name, a, b, price, ttm):
    funds = CONFIG[name]["funds"]
    if name == "equal":
        relative = price.RSP / price.SPY
        hold = (relative / relative.shift(a) - 1 > b).astype(float)
        return pd.DataFrame({"RSP": hold, "SPY": 1 - hold})
    score = price[funds].pct_change(a, fill_method=None) if name == "small" else (
        ttm[funds] / years_ago(ttm[funds], a) - 1)
    picked = score.rank(axis=1, ascending=False, method="first") <= b
    return picked.div(picked.sum(axis=1).replace(0, np.nan), axis=0).fillna(0)


def stats(curve, rf=None):
    curve = curve / curve.iloc[0]
    returns = curve.pct_change().dropna()
    daily = returns if rf is None else returns - rf.reindex(returns.index)
    return {"start": str(curve.index[0].date()), "end": str(curve.index[-1].date()),
            "cagr": float(curve.iloc[-1] ** (365.25 / (curve.index[-1] - curve.index[0]).days) - 1),
            "daily_sharpe": float(daily.mean() / daily.std() * np.sqrt(252)),
            "mdd": float((curve / curve.cummax() - 1).min()),
            "volatility": float(returns.std() * np.sqrt(252))}


def halves(curves):
    cut = len(curves) // 2
    return [{s: stats(part[s]) for s in part} for part in (curves.iloc[:cut], curves.iloc[cut:])]


def rolling(curves):
    out = {}
    for years in [1, 3, 5]:
        returns = curves.pct_change(252 * years, fill_method=None).dropna()
        out[str(years)] = {s: {"windows": len(returns), "min": float(returns[s].min()),
                               "median": float(returns[s].median()), "max": float(returns[s].max()),
                               "beat_qqq": float((returns[s] > returns.QQQ).mean())} for s in curves}
    return out


REPORT_LABELS = {
    "equal": ("RSP/SPY rotation", "RSP／SPY 輪動"),
    "small": ("Small-cap rotation", "小型股輪動"),
    "dividend": ("Dividend rotation", "配息成長輪動"),
    "control": ("Fixed equal allocation", "固定等權配置"),
}


def label_report(html, labels):
    """Name this experiment, show the QQQ benchmark and distinguish CAPM alpha from total-return differences."""
    replacements = {
        # The dashboard chooses these fixed benchmark labels from the US market name.
        "標普 500（不含息）{value}": "QQQ（含息）{value}",
        "S&P 500 (no dividends) {value}": "QQQ total return {value}",
        'answer_profitability: "年化 {cagr}，超額報酬 {alpha}"':
            'answer_profitability: "年化 {cagr}，風險調整 alpha {alpha}"',
        'name_alpha: "超額報酬 (Alpha)"': 'name_alpha: "風險調整 alpha"',
        'metrics_profitability_alpha: "超額報酬 (Alpha)"':
            'metrics_profitability_alpha: "風險調整 alpha"',
        'answer_profitability: "{cagr} a year, alpha {alpha}"':
            'answer_profitability: "{cagr} a year, CAPM alpha {alpha}"',
    }
    for old, new in replacements.items():
        html = html.replace(old, new)
    for original, label in [("Annual return", labels[0] + ": annual return"),
                            ("年化報酬", labels[1] + "年化")]:
        html = re.sub(r'(?<!\w)annualReturn: "' + original + '"',
                      'annualReturn: ' + json.dumps(label, ensure_ascii=False), html)
    return html


def export_report(report, path, title, benchmark, labels):
    """Keep FinLab's dashboard, with the same QQQ/zero-rate convention as the tables."""
    report.benchmark = benchmark
    daily = benchmark.reindex(report.daily_creturn.index, method="ffill")
    report.daily_benchmark = daily / daily.iloc[0]
    report.get_stats = partial(report.get_stats, riskfree_rate=0.0)
    report.get_metrics = partial(report.get_metrics, riskfree_rate=0.0)
    report.get_benchmark_stats = partial(report.get_benchmark_stats, riskfree_rate=0.0)
    report.to_html(str(path), title=title)
    path.write_text(label_report(path.read_text(encoding="utf-8"), labels), encoding="utf-8")


def run(name, price, cash, audit, output):
    cfg = CONFIG[name]
    symbols = [*cfg["funds"], "QQQ", "SPY"]
    out = output / cfg["slug"]
    out.mkdir(parents=True, exist_ok=True)
    ttm = pd.DataFrame({s: trailing_cash(cash[s], price.index) for s in cfg["funds"]})
    # Cash history starts 2016-01-04, so trailing-year cash is complete from 2017-01-04
    # and, after up to three more years of growth lookback, from January 2020.
    ttm.loc[ttm.index < pd.Timestamp("2017-01-04")] = np.nan
    rf = price.BIL.pct_change(fill_method=None)
    grid = []
    for a, b in product(cfg["a"], cfg["b"]):
        position = weights(name, a, b, price, ttm).loc[cfg["start"]:END]
        rep = backtest(position)
        eq = rep.creturn.loc[:END]
        benchmark = price.QQQ.reindex(eq.index)
        grid.append({"a": a, "b": b, **stats(eq), "qqq_sharpe": stats(benchmark)["daily_sharpe"]})
        if [a, b] == cfg["original"]:
            report, curve, chosen = rep, eq, position
    curves = price[symbols].reindex(curve.index).assign(rule=curve)
    curves = curves.div(curves.iloc[0])
    # Explicit 10 bps per buy/sell supplements the US market's zero-cost defaults.
    cost = backtest(chosen, fee_ratio=0.001).creturn.reindex(curve.index)
    split = halves(curves)
    rule_stats = {s: stats(curves[s]) for s in curves}
    cost_stats = stats(cost)
    benchmark_sharpe = rule_stats["QQQ"]["daily_sharpe"]
    checks = {"grid_wins": sum(row["daily_sharpe"] > row["qqq_sharpe"] for row in grid),
              "grid_size": len(grid), "both_halves": all(h["rule"]["daily_sharpe"] > h["QQQ"]["daily_sharpe"] for h in split),
              "default_cost": rule_stats["rule"]["daily_sharpe"] > benchmark_sharpe,
              "cost_10bps": cost_stats["daily_sharpe"] > benchmark_sharpe}
    held = price[symbols].dropna()
    launched = price[["AVUV", *symbols]].dropna() if name == "small" else None
    growth = {}
    if name == "dividend":
        asof = pd.Timestamp(END)
        for s in cfg["funds"]:
            annual = cash[s].groupby(cash[s].index.year).sum()
            prior, now = trailing_cash(cash[s], pd.DatetimeIndex([asof - pd.DateOffset(years=5), asof])).tolist()
            # Ten-year CAGR requires a full trailing year starting in November 2015.
            growth[s] = {"ttm_cash": now, "ttm_5y_before": prior, "cagr_5y": (now / prior) ** 0.2 - 1,
                         "cagr_10y": None, "missing_10y_reason": "Cash history starts 2016; full November 2015-2016 base year unavailable",
                         "calendar_cash": {str(y): float(v) for y, v in annual.items()}}
    # Exclude the incomplete final month: its signal has not executed yet.
    decisions = chosen.groupby(chosen.index.to_period("M")).last().iloc[:-1]
    turnover = decisions.diff().abs().sum(axis=1) / 2
    metrics = {"run_date": datetime.now(timezone.utc).isoformat(), "finlab_version": finlab.__version__,
               "data_end": END, "rule": cfg, "audit": {s: audit[s] for s in symbols},
               "buy_hold": {s: stats(held[s]) for s in held}, "buy_hold_halves": halves(held),
               "buy_hold_rolling": rolling(held), "rule_stats": rule_stats,
               "rule_excess_sharpe": {s: stats(curves[s], rf)["daily_sharpe"] for s in curves},
               "grid": grid, "halves": split, "cost_stats": cost_stats, "checks": checks,
               "turnover_monthly_mean": float(turnover.iloc[1:].mean()), "turnover_monthly_max": float(turnover.max()),
               "dividend_growth": growth,
               "avuv_common": {s: stats(launched[s]) for s in launched} if launched is not None else None}
    (out / "metrics.json").write_text(json.dumps(metrics, indent=2, ensure_ascii=False, allow_nan=False) + "\n")
    curves.to_csv(out / "data.csv", index_label="date")
    held.div(held.iloc[0]).to_csv(out / "buy-hold.csv", index_label="date")
    if launched is not None:
        launched.div(launched.iloc[0]).to_csv(out / "avuv-common.csv", index_label="date")
    export_report(report, out / "report_strategy.html", f"FinLab {name} ETF research", price.QQQ, REPORT_LABELS[name])
    baseline = pd.DataFrame(1 / len(cfg["funds"]), index=chosen.index, columns=cfg["funds"])
    export_report(backtest(baseline), out / "report_baseline.html", f"FinLab {name} ETF equal-allocation control", price.QQQ, REPORT_LABELS["control"])
    print(name, json.dumps(checks), "original", rule_stats["rule"], flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("topic", choices=[*CONFIG, "all"], default="all", nargs="?")
    parser.add_argument("--out", type=Path, default=Path.cwd())
    args = parser.parse_args()
    price, cash, audit = load()
    for name in CONFIG if args.topic == "all" else [args.topic]:
        run(name, price, cash, audit, args.out)


if __name__ == "__main__":
    main()
