"""
Minervini's SEPA growth-stock screen on US stocks, rebuilt with FinLab data and checked three ways.

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

The rule, as the article describes its US backtest
  Trend template   close above its 150- and 200-day averages, 150-day above 200-day,
                   200-day average higher than 25 days ago, 50-day above both,
                   close above the 50-day average, 25% above the 52-week low, within 25%
                   of the 52-week high, and 12-month return in the top 10% (RS rating)
  Fundamentals     revenue and gross profit up two quarters in a row, EPS positive and
                   up two quarters in a row (US companies report quarterly, not monthly)
  VCP              10-day average volume below 60% of the 60-day average, and 10-day
                   price standard deviation below half the 60-day one
  Entry            every condition true for 3 days in a row; financials excluded
  Holding          the 15 qualifying stocks furthest from their 5-day average; a stock
                   is sold as soon as it stops qualifying
Stocks come from the 1,000 most traded US common stocks (delisted ones included, ex
financials, price > $5, 60-day average dollar volume > $5M).

"Beats QQQ" means a higher daily Sharpe ratio (no risk-free rate) than buying and holding
QQQ, dividends included, over exactly the same dates. The rule passes only if
  1. at least 7 of the 9 settings beat QQQ: RS cut-off top 20/10/5% x VCP volume ratio
     50/60/70% (so few stocks qualify that the 15-stock cap almost never binds, so the
     number of stocks is not a useful parameter),
  2. the original setting beats QQQ in both halves of the backtest, and
  3. it still beats QQQ after paying 0.1% per buy and per sell (finlab's US default
     cost is zero).

A second version drops the VCP filter (trend template and fundamentals only), with the grid
RS cut-off x fundamentals rising 1/2/3 quarters in a row.

Run:  python sepa_us.py      writes sepa_us_metrics.json and sepa_us_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

START = "2017-08-01"
END = "2026-10-29"
COST_PER_SIDE = 0.001
HOLDINGS = 15
RS_CUTOFFS = (0.8, 0.9, 0.95)    # 12-month return above this cross-sectional quantile
VOLUME_RATIOS = (0.5, 0.6, 0.7)  # VCP: 10-day average volume below this share of the 60-day average
QUARTERS = (1, 2, 3)             # without VCP: fundamentals rising this many quarters in a row
VERSIONS = {
    # name: (second parameter, its values, original setting)
    "with_vcp": ("volume_ratio", VOLUME_RATIOS, (0.9, 0.6)),
    "without_vcp": ("quarters", QUARTERS, (0.9, 2)),
}
OUT = Path(__file__).resolve().parent

data.set_market("us")
data.truncate_end = END


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


def common_stocks():
    """Common stocks from the company profile, delisted ones included, ex financials."""
    p = get("us_company_profile")
    keep = (
        (p["security_type"] == "common_stock")
        & ~p["is_etf"].fillna(False).astype(bool)
        & ~p["is_fund"].fillna(False).astype(bool)
        & ~p["is_adr"].fillna(False).astype(bool)
        & (p["sector"] != "Financial Services")
    )
    return pd.Index(sorted(p.loc[keep, "stock_id"].astype(str))).intersection(get("us_price:adj_close").columns)


@cache
def universe():
    ids = common_stocks()
    close, volume = get("us_price:close")[ids], get("us_price:volume")[ids]
    dollar_volume = (close * volume).rolling(60, min_periods=20).mean()
    daily_return = get("us_price:adj_close")[ids].pct_change(fill_method=None)
    recently_extreme = (daily_return.abs() >= 0.5).astype(float).rolling(252, min_periods=1).max().shift(1).fillna(0) > 0
    return dollar_volume.is_largest(1000) & (dollar_volume > 5e6) & (close > 5) & ~recently_extreme


def daily(quarterly_condition):
    """A quarterly true/false table -> trading day x ticker, from each filing date on."""
    dated = quarterly_condition.astype(float).index_str_to_date()
    days = get("us_price:adj_close").index
    return dated.reindex(dated.index.union(days)).ffill().reindex(index=days, columns=universe().columns).fillna(0) > 0


@cache
def trend(rs_cutoff):
    ids = universe().columns
    close = get("us_price:adj_close")[ids]
    low, high = get("us_price:adj_low")[ids], get("us_price:adj_high")[ids]
    ma50, ma150, ma200 = close.average(50), close.average(150), close.average(200)
    rs = (close / close.shift(250))[universe()]
    return (
        (close > ma150) & (close > ma200) & (ma150 > ma200) & (ma200 > ma200.shift(25))
        & (ma50 > ma150) & (ma50 > ma200) & (close > low.rolling(250).min() * 1.25)
        & (close > high.rolling(250).max() * 0.75) & (close > ma50)
        & (rs > rs.quantile_row(rs_cutoff))
    )


@cache
def fundamentals(quarters):
    eps = get("us_income_statement:eps_diluted")
    return (
        daily(get("us_income_statement:revenue").rise().sustain(quarters))
        & daily(eps.rise().sustain(quarters) & (eps > 0))
        & daily(get("us_income_statement:gross_profit").rise().sustain(quarters))
    )


@cache
def vcp(volume_ratio):
    ids = universe().columns
    close = get("us_price:adj_close")[ids]
    volume = get("us_price:volume")[ids] * get("us_price:close")[ids] / close   # split-adjusted
    return ((volume.average(10) < volume.average(60) * volume_ratio)
            & (close.rolling(10).std() < close.rolling(60).std() * 0.5))


@cache
def qualifies(rs_cutoff, volume_ratio=None, quarters=2):
    """volume_ratio=None leaves out the VCP filter."""
    qualified = trend(rs_cutoff) & fundamentals(quarters) & universe()
    if volume_ratio is not None:
        qualified &= vcp(volume_ratio)
    return qualified.sustain(3)


@cache
def position(version, rs_cutoff, value):
    close = get("us_price:adj_close")[universe().columns]
    ma5 = close.average(5)
    bias = ((close - ma5) / ma5).abs()
    parameter = VERSIONS[version][0]
    return bias[qualifies(rs_cutoff, **{parameter: value})].is_largest(HOLDINGS).loc[START:END]


@cache
def backtest(version, rs_cutoff, value, fee_ratio=None):
    report = sim(position(version, rs_cutoff, value), fee_ratio=fee_ratio, upload=False)
    days = get("us_price:adj_close").loc[START:END].index
    return report.creturn.reindex(days).ffill().fillna(1.0).loc[days[1]:]


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


@cache
def qqq_prices():
    data.set_market("us_fund")
    q = data.get("us_fund_price:adj_close")["QQQ"]
    data.set_market("us")
    return q


def stats(curve):
    curve = curve.dropna()
    bench = qqq_prices().reindex(curve.index)
    years = (curve.index[-1] - curve.index[0]).days / 365.25
    sharpe, qqq_sharpe = daily_sharpe(curve), daily_sharpe(bench)
    return {
        "start": str(curve.index[0].date()), "end": str(curve.index[-1].date()),
        "sharpe": round(sharpe, 6), "qqq_sharpe": round(qqq_sharpe, 6),
        "cagr": round((curve.iloc[-1] / curve.iloc[0]) ** (1 / years) - 1, 6),
        "qqq_cagr": round((bench.iloc[-1] / bench.iloc[0]) ** (1 / years) - 1, 6),
        "mdd": round((curve / curve.cummax() - 1).min(), 6),
        "beats_qqq": bool(sharpe > qqq_sharpe),
    }


def halves(curve):
    middle = curve.index[len(curve) // 2]
    return [stats(curve.loc[:middle]), stats(curve.loc[middle:])]


def holding_profile(version, rs_cutoff, value):
    held = position(version, rs_cutoff, value).sum(axis=1)
    return {"average_stocks": round(float(held.mean()), 2), "days_in_cash": round(float((held == 0).mean()), 4)}


def evaluate(version):
    name, values, original = VERSIONS[version]
    grid = []
    for rs_cutoff in RS_CUTOFFS:
        for value in values:
            curve = backtest(version, rs_cutoff, value)
            row = {"rs_cutoff": rs_cutoff, name: value, **stats(curve),
                   "halves": halves(curve), **holding_profile(version, rs_cutoff, value)}
            grid.append(row)
            print(f"{version} RS top {1 - rs_cutoff:.0%} {name}={value}: Sharpe {row['sharpe']:.3f} vs QQQ "
                  f"{row['qqq_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[name]) == original)
    cost = stats(backtest(version, *original, fee_ratio=COST_PER_SIDE))
    wins = sum(g["beats_qqq"] for g in grid)
    checks = {"grid": wins >= 7, "halves": all(h["beats_qqq"] for h in base["halves"]),
              "cost": cost["beats_qqq"]}
    print(version, "PASS" if all(checks.values()) else "FAIL", checks, f"grid {wins}/9", flush=True)
    return {"original": list(original), "grid": grid, "grid_wins": wins, "cost_0.1pct": cost,
            "checks": checks, "passes": all(checks.values())}


def main():
    out = {"window": {"start": START, "end": END}, "holdings": HOLDINGS,
           "finlab_version": finlab.__version__}
    out.update({version: evaluate(version) for version in VERSIONS})
    curves = {"SEPA as in the article": backtest("with_vcp", *VERSIONS["with_vcp"][2]),
              "SEPA without VCP": backtest("without_vcp", *VERSIONS["without_vcp"][2])}
    frame = pd.DataFrame({**curves, "QQQ (buy and hold)": qqq_prices().reindex(curves["SEPA as in the article"].index)})
    (frame / frame.iloc[0]).round(6).to_csv(OUT / "sepa_us_data.csv", index_label="date")
    (OUT / "sepa_us_metrics.json").write_text(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
