"""減資放空與現增放空：兩篇舊文的策略跑到最新資料，做三項驗證（/blog/capital-reduction-event-study-short-strategy）。

1. 減資放空（文中程式）：上市減資恢復買賣前一個交易日產生訊號，恢復買賣日收盤放空、持有 5 個交易日，停損 30%。
   文中把篩選條件寫成 positon，「現金減資」條件沒生效，實際放空全部上市減資股；這裡照寫法跑一次，
   再跑一次內文說的「只放空彌補虧損減資」。
2. 現增放空（原「現金增資放空」一文，已併入本文）：現金增資股數 ÷ 已發行股數 > 10%、每股淨值 > 10 元，
   除權交易日前 5 個交易日收盤放空，持有 25 個交易日。已發行股數照文中用 company_basic_info 的最新股數。
   etl:adj_close 沒有還原現增除權，除權當天的缺口會被當成下跌；融券在除權前要強制回補、借券要補償認股權，
   放空的人拿不到這一段，所以另跑一次「除權交易日收盤才放空」（持有 10／20／30 天）對照。

三項驗證（「贏」＝日夏普高於同期 0050 含息買進持有）：鄰近 9 組至少 7 組贏、回測期間對半切兩段都贏、
sim() 預設手續費 0.1425% 與證交稅 0.3%，再扣融券手續費 0.08%（放空時收，sim 沒有這一項）。
日夏普 = 日報酬平均 / 標準差 × √252，不扣無風險利率；0050 含息 = etl:adj_close 還原價買進持有。

    pip install finlab
    python strategy.py

finlab 需要資料時會自動引導登入，不需要在程式裡填 token。執行後輸出 metrics.json 與 data.csv。
"""
import datetime
import itertools
import json

import numpy as np
import pandas as pd

import finlab
from finlab import data
from finlab.backtest import sim

SHORT_FEE = 0.0008
FIRST_PUBLISHED = {"reduction": "2023-09-20", "issue": "2023-09-17"}


def plain(key):
    df = pd.DataFrame(data.get(key))
    df.index = pd.to_datetime(df.index)
    return df


close = plain("price:收盤價")
days = close.index
bench = plain("etl:adj_close")["0050"].dropna()


def short_positions(rows, hold):
    """(股票, 訊號日位置) → 放空持有表：訊號日起 hold 個交易日為 -1（sim 隔天收盤進場）。"""
    a = np.zeros((len(days), len(close.columns)))
    col = {s: i for i, s in enumerate(close.columns)}
    for s, sig in rows:
        if s in col and sig >= 0:
            a[sig:sig + hold, col[s]] = -1
    position = pd.DataFrame(a, index=days, columns=close.columns)
    return position.loc[:, (position != 0).any()]


# 1. 減資：恢復買賣日的前一個交易日產生訊號
reason = plain("capital_reduction_tse:減資原因").stack().dropna()
reductions = [(s, int(days.searchsorted(d)) - 1, r) for (d, s), r in reason.items()]


def reduction_short(hold, stop_loss, deficit_only, end=None, **cost):
    rows = [(s, sig) for s, sig, r in reductions if r == "彌補虧損" or not deficit_only]
    return sim(short_positions(rows, hold).loc[:end], stop_loss=stop_loss, upload=False, **cost)


# 2. 現增：除權交易日（ex）的位置；文中從 ex 前 5 個交易日產生訊號
dividends = pd.DataFrame(data.get("dividend_announcement")).dropna(subset=["除權交易日", "stock_id"])
dividends = dividends.drop_duplicates(["stock_id", "除權交易日"])
company = pd.DataFrame(data.get("company_basic_info"))
issued_now = company.set_index(company["stock_id"].astype(str))["已發行普通股數或TDR原發行股數"]
net_value = close / plain("price_earning_ratio:股價淨值比").reindex(index=days, columns=close.columns)
issues = []
for s, ex, n, announced in zip(dividends["stock_id"].astype(str), dividends["除權交易日"],
                               dividends["現金增資總股數(股)"], dividends["公告日期"]):
    if n > 0 and s in issued_now.index and s in close.columns:
        ex_pos = int(days.searchsorted(ex))
        if 5 <= ex_pos < len(days) and net_value[s].iloc[ex_pos - 5] > 10:
            issues.append((s, ex_pos, n / issued_now[s], days[ex_pos - 5] < announced))


def issue_short(threshold, hold, offset=-5, end=None, **cost):
    rows = [(s, ex_pos + offset) for s, ex_pos, ratio, _ in issues if ratio > threshold]
    return sim(short_positions(rows, hold).loc[:end], upload=False, **cost)


# ---------------------------------------------------------------------------
def perf(equity):
    equity = equity / equity.iloc[0]
    ret = equity.pct_change().dropna()
    years = (equity.index[-1] - equity.index[0]).days / 365.25
    return {
        "cagr": round(float(equity.iloc[-1] ** (1 / years) - 1), 6),
        "sharpe": round(float(ret.mean() / ret.std() * np.sqrt(252)), 6),
        "mdd": round(float((equity / equity.cummax() - 1).min()), 6),
        "start": str(equity.index[0].date()),
        "end": str(equity.index[-1].date()),
    }


def equity_of(report, borrow=True):
    """從第一次有部位的前一天起算，扣融券手續費。"""
    equity = report.creturn.dropna()
    first_move = (equity != equity.iloc[0]).argmax()
    equity = equity.iloc[max(first_move - 1, 0):]
    if borrow:
        trades = report.get_trades()
        fee = trades.groupby(pd.to_datetime(trades["entry_date"]))["position"].apply(lambda w: SHORT_FEE * w.abs().sum())
        equity = equity * (1 - fee.reindex(equity.index).fillna(0)).cumprod()
    return equity


def versus_0050(equity):
    b = bench.reindex(equity.index).ffill()
    mid = equity.index[0] + (equity.index[-1] - equity.index[0]) / 2
    out = {}
    for name, part in [("full", slice(None)), ("first_half", slice(None, mid)), ("second_half", slice(mid, None))]:
        s, k = perf(equity.loc[part]), perf(b.loc[part])
        out[name] = {"strategy": s, "bench": k, "win": s["sharpe"] > k["sharpe"]}
    return out


STRATEGIES = {
    # 名稱: (回測函式, 參數 1, 參數 2, 原參數, 首發日鍵, 文中成本)
    "減資放空（文中程式：全部上市減資）": (lambda a, b, **c: reduction_short(a, b, False, **c),
                             ("持有天數", [3, 5, 10]), ("停損", [0.2, 0.3, 0.4]), (5, 0.3),
                             "reduction", {"fee_ratio": 1.425 / 1000 / 3}),
    "減資放空（只放空彌補虧損）": (lambda a, b, **c: reduction_short(a, b, True, **c),
                        ("持有天數", [3, 5, 10]), ("停損", [0.2, 0.3, 0.4]), (5, 0.3),
                        "reduction", {"fee_ratio": 1.425 / 1000 / 3}),
    "現增放空（文中程式）": (issue_short, ("現增股數占已發行門檻", [0.05, 0.1, 0.15]), ("持有天數", [15, 25, 35]), (0.1, 25),
                    "issue", {"fee_ratio": 1.425 / 1000 * 2}),
    "現增放空（除權交易日收盤才放空）": (lambda a, b, **c: issue_short(a, b, offset=0, **c),
                          ("現增股數占已發行門檻", [0.05, 0.1, 0.15]), ("持有天數", [10, 20, 30]), (0.1, 20),
                          "issue", {"fee_ratio": 1.425 / 1000 * 2}),
}

results, curves = {}, {}
for name, (run, (xname, xs), (yname, ys), center, published, article_cost) in STRATEGIES.items():
    rows = []
    for x, y in itertools.product(xs, ys):
        report = run(x, y)
        equity = equity_of(report)
        row = {xname: x, yname: y, **versus_0050(equity)}
        if (x, y) == center:
            curves[name] = equity
            trades = report.get_trades()
            row["trades"] = int(len(trades))
            row["win_rate"] = round(float((trades["return"] > 0).mean()), 4)
            row["sim_cost_only"] = perf(equity_of(report, borrow=False))
            row["zero_cost"] = perf(equity_of(run(x, y, fee_ratio=0, tax_ratio=0), borrow=False))
            # 首發前的資料、文中的手續費：文章當時看得到的結果
            row["as_published"] = perf(equity_of(run(x, y, end=FIRST_PUBLISHED[published], **article_cost), borrow=False))
        rows.append(row)
        print(name, x, y, f"日夏普 {row['full']['strategy']['sharpe']:.2f}，0050 {row['full']['bench']['sharpe']:.2f}", flush=True)
    base = next(r for r in rows if (r[xname], r[yname]) == center)
    wins = sum(r["full"]["win"] for r in rows)
    checks = {"neighbors": wins / len(rows) >= 0.7,
              "halves": base["first_half"]["win"] and base["second_half"]["win"],
              "cost": base["full"]["win"]}
    checks["all"] = all(checks.values())
    results[name] = {"center": center, "wins": wins, "checks": checks, "grid": rows}
    print(name, f"鄰近 {wins}/9", checks, flush=True)

results["現增放空（文中程式）"]["entries_before_announcement"] = round(
    float(np.mean([early for _, _, ratio, early in issues if ratio > 0.1])), 4)

curves = pd.DataFrame(curves)
curves = curves / curves.bfill().iloc[0]
curves["0050含息"] = bench.reindex(curves.index).ffill()
curves["0050含息"] = curves["0050含息"] / curves["0050含息"].dropna().iloc[0]
curves.index.name = "date"
curves.round(6).to_csv("data.csv")
metrics = {
    "run_date": str(datetime.date.today()),
    "finlab_version": finlab.__version__,
    "data_end": str(days[-1].date()),
    "short_fee": SHORT_FEE,
    "strategies": results,
    "generated_by": "static/blog/capital-reduction-event-study-short-strategy/validation/strategy.py",
}
with open("metrics.json", "w", encoding="utf-8") as f:
    json.dump(metrics, f, ensure_ascii=False, indent=1)
