"""
The Taiwan version of Minervini's SEPA screen from the article, checked three ways.

FinLab research, 2026-10. Reproduces the Taiwan numbers in
https://finlab.finance/blog/super-performance-growth-stock-screening

The rule is the article's Taiwan code: trend template (close above its 150- and 200-day
averages, 150-day above 200-day, 200-day higher than 25 days ago, 50-day above both,
25% above the 250-day low, within 25% of the 250-day high, 250-day return in the top 10%,
close above the 50-day average), monthly revenue up two months in a row, EPS positive and
up two quarters in a row, gross profit up two quarters in a row, and VCP (10-day average
volume below 60% of the 60-day average, 10-day price standard deviation below half the
60-day one). A stock is held from the day it qualifies until it closes below its 20-day
average; every holding gets an equal share.

"Beats 0050" means a higher daily Sharpe ratio (no risk-free rate) than buying and holding
0050, dividends included, over exactly the same dates. The rule passes only if
  1. at least 7 of the 9 settings (RS cut-off top 20/10/5% x exit average 15/20/25 days)
     beat 0050,
  2. the original setting beats 0050 in both halves of the backtest, and
  3. it beats 0050 with finlab's default Taiwan costs (0.1425% commission each way,
     0.3% tax on sales); the article used a 70% commission discount.

Run:  python sepa_tw.py      writes sepa_tw_metrics.json and sepa_tw_data.csv next to this file
"""
import json
from functools import cache
from pathlib import Path

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

END = "2026-10-29"
RS_CUTOFFS = (0.8, 0.9, 0.95)
EXIT_AVERAGES = (15, 20, 25)
ORIGINAL = (0.9, 20)
ARTICLE_FEE = 1.425 / 1000 / 3
OUT = Path(__file__).resolve().parent

data.truncate_end = END


@cache
def get(key):
    return data.get(key)


@cache
def buy(rs_cutoff):
    close, low, high = get("price:收盤價"), get("price:最低價"), get("price:最高價")
    revenue, eps = get("monthly_revenue:當月營收"), get("financial_statement:每股盈餘")
    grossprofit, volume = get("financial_statement:營業毛利"), get("price:成交股數")

    cond1 = (close > close.average(200)) & (close > close.average(150))
    cond2 = close.average(150) > close.average(200)
    cond3 = close.average(200) > close.average(200).shift(25)
    cond4 = (close.average(50) > close.average(200)) & (close.average(50) > close.average(150))
    cond5 = close > low.rolling(250).min() * 1.25
    cond6 = close > high.rolling(250).max() * 0.75
    rs = close / close.shift(250)
    cond7 = rs > rs.quantile_row(rs_cutoff)
    cond8 = close > close.average(50)

    revenue_cond = revenue.rise().sustain(2)
    eps_cond = eps.rise().sustain(2) & (eps > 0)
    grossprofit_cond = grossprofit.rise().sustain(2)

    volumereduce = volume.average(10) < volume.average(60) * 0.6
    pricecontract = close.rolling(10).std() < close.rolling(60).std() * 0.5
    vcp = volumereduce & pricecontract
    return (cond1 & cond2 & cond3 & cond4 & cond5 & cond6 & cond7 & cond8
            & revenue_cond & eps_cond & grossprofit_cond & vcp)


@cache
def position(rs_cutoff, exit_average):
    close = get("price:收盤價")
    return buy(rs_cutoff).hold_until(close < close.average(exit_average))


@cache
def report(rs_cutoff, exit_average, fee_ratio=None):
    return sim(position(rs_cutoff, exit_average), fee_ratio=fee_ratio, upload=False)


def active(curve):
    """From the day before the first trade to the end of the data."""
    curve = curve.dropna()
    moved = (curve != curve.iloc[0]).to_numpy().nonzero()[0]
    return curve.iloc[max(moved[0] - 1, 0):]


def daily_sharpe(curve):
    returns = curve.pct_change().dropna()
    return returns.mean() / returns.std() * 252 ** 0.5


def stats(curve):
    curve = curve.dropna()
    bench = get("etl:adj_close")["0050"].reindex(curve.index)
    years = (curve.index[-1] - curve.index[0]).days / 365.25
    sharpe, bench_sharpe = daily_sharpe(curve), daily_sharpe(bench)
    return {
        "start": str(curve.index[0].date()), "end": str(curve.index[-1].date()),
        "sharpe": round(sharpe, 6), "0050_sharpe": round(bench_sharpe, 6),
        "cagr": round((curve.iloc[-1] / curve.iloc[0]) ** (1 / years) - 1, 6),
        "0050_cagr": round((bench.iloc[-1] / bench.iloc[0]) ** (1 / years) - 1, 6),
        "mdd": round((curve / curve.cummax() - 1).min(), 6),
        "beats_0050": bool(sharpe > bench_sharpe),
    }


def halves(curve):
    start, end = curve.index[0], curve.index[-1]
    middle = start + (end - start) / 2
    return [stats(curve.loc[:middle]), stats(curve.loc[middle:])]


def main():
    grid = []
    for rs_cutoff in RS_CUTOFFS:
        for exit_average in EXIT_AVERAGES:
            r = report(rs_cutoff, exit_average)
            curve = active(r.creturn)
            held = position(rs_cutoff, exit_average).loc[curve.index[0]:].sum(axis=1)
            row = {"rs_cutoff": rs_cutoff, "exit_average": exit_average, **stats(curve),
                   "halves": halves(curve), "average_stocks": round(float(held.mean()), 2),
                   "days_in_cash": round(float((held == 0).mean()), 4)}
            grid.append(row)
            print(f"RS top {1 - rs_cutoff:.0%} exit {exit_average}d: Sharpe {row['sharpe']:.3f} vs 0050 "
                  f"{row['0050_sharpe']:.3f} CAGR {row['cagr']:.1%} MDD {row['mdd']:.1%} "
                  f"avg {row['average_stocks']} stocks", flush=True)
    base = next(g for g in grid if (g["rs_cutoff"], g["exit_average"]) == ORIGINAL)
    wins = sum(g["beats_0050"] for g in grid)
    checks = {"grid": wins >= 7, "halves": all(h["beats_0050"] for h in base["halves"]),
              "cost": base["beats_0050"]}
    article_cost = stats(active(report(*ORIGINAL, fee_ratio=ARTICLE_FEE).creturn))
    out = {"end": END, "original": list(ORIGINAL), "grid": grid, "grid_wins": wins,
           "article_cost": article_cost, "checks": checks, "passes": all(checks.values()),
           "finlab_version": finlab.__version__}
    print("PASS" if out["passes"] else "FAIL", checks, f"grid {wins}/9", flush=True)
    curve = active(report(*ORIGINAL).creturn)
    frame = pd.DataFrame({"SEPA Taiwan (article code)": curve,
                          "0050 (buy and hold)": get("etl:adj_close")["0050"].reindex(curve.index)})
    (frame / frame.iloc[0]).round(6).to_csv(OUT / "sepa_tw_data.csv", index_label="date")
    (OUT / "sepa_tw_metrics.json").write_text(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
