"""
The financial-statement long-short strategy from the 2023 article, rebuilt with FinLab's
current US data and checked three ways.

FinLab research, 2026-10. Reproduces the numbers in
https://finlab.finance/blog/financial-report-strategy-long-short

The article's recipe (it used Quandl fields that FinLab no longer carries)
  1. Take every numeric field of the quarterly income statement, balance sheet and cash
     flow statement, plus market value, and derive 9 variants of each: 2- and 4-quarter
     averages, change over 4 quarters, value / 4-quarter average, value / 4- and
     8-quarter high, and so on (1,220 features with FinLab's fields in 2026-10).
  2. At each calendar quarter end, correlate every feature with the next 60 trading days'
     return (buying at the next open), across all liquid stocks and quarters.
  3. Drop features that are more than 0.8 correlated with another one, then keep the 30
     most positive and the 30 most negative. (The article's code keeps the features it
     meant to drop: `corr[corr.index.isin(to_drop)]`. We follow the code; the version
     that keeps the others is reported as well.)
  4. Score = sum of the cross-sectional percentile ranks of the 30 positive features
     minus the same for the 30 negative ones.
  5. Every week, buy the 10 highest scores and short the 20 lowest among stocks with 60-day
     average dollar volume > $10M and volume > 5,000 shares, each side weighted by 20-day
     volatility, half the account per side, at most 10% in one stock.
Stocks come from the 1,000 most traded US common stocks (delisted ones included, ex
financials, price > $5, 60-day average dollar volume > $5M).

Steps 2-3 look at returns from the whole backtest, so the backtest knows the future.
The out-of-sample check picks the features with first-half data only and trades the
second half.

"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 (long 5/10/20 x short 10/20/40 stocks) beat QQQ,
  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; short borrowing fees are not charged).

Run:  python strategy.py   (about 30 minutes the first time, which downloads about 140
      statement fields; needs about 8 GB of memory)
Writes metrics.json and data.csv next to this file.
"""
import json
from functools import cache
from pathlib import Path

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

START = "2018-01-02"     # 8 quarters of filings (2016-Q1 on) before the first trade
END = "2026-10-29"
LABEL_DAYS = 60
FEATURES_PER_SIDE = 30
LONGS, SHORTS = (5, 10, 20), (10, 20, 40)
ORIGINAL = (10, 20)
COST_PER_SIDE = 0.001
TABLES = ["us_income_statement", "us_balance_sheet", "us_cash_flow"]
NOT_FEATURES = {"reported_currency", "cik", "filing_date", "accepted_date", "calendar_year",
                "fiscal_year", "original_date"}
OUT = Path(__file__).resolve().parent

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


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


def prices():
    return get("us_price:adj_close")


# ---------------------------------------------------------------------------
# Universe
# ---------------------------------------------------------------------------
@cache
def universe():
    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")
    )
    ids = pd.Index(sorted(p.loc[keep, "stock_id"].astype(str))).intersection(prices().columns)
    close, volume = get("us_price:close")[ids], get("us_price:volume")[ids]
    dollar_volume = (close * volume).rolling(60, min_periods=20).mean()
    daily_return = prices()[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
    liquid = dollar_volume.is_largest(1000) & (dollar_volume > 5e6) & (close > 5) & ~recently_extreme
    # the article's own filter
    liquid &= ((close * volume).average(60) > 1e7) & (volume > 5000)
    ever = liquid.columns[liquid.loc["2016":].any()]
    return liquid[ever]


def ids():
    return universe().columns


def period_ends(days, freq):
    """The last trading day of each period."""
    return pd.DatetimeIndex(pd.Series(days, index=days).groupby(days.to_period(freq)).max().values)


def quarter_ends():
    return period_ends(prices().loc["2016-06":END].index, "Q")


@cache
def week_ends():
    days = prices().loc[START:END].index
    return pd.DatetimeIndex([days[0], *period_ends(days, "W")]).unique()


# ---------------------------------------------------------------------------
# Features: quarter x ticker, picked up on each company's filing date
# ---------------------------------------------------------------------------
@cache
def filing_dates():
    return get("us_income_statement:filing_date").reindex(columns=ids())


def latest_quarter(dates):
    """For each date and ticker, the row of the latest quarter already filed (-1: none)."""
    filed = filing_dates().to_numpy(dtype="datetime64[ns]")
    out = np.full((len(dates), filed.shape[1]), -1)
    for i, d in enumerate(dates.to_numpy()):
        known = filed <= d
        last = known.shape[0] - 1 - np.argmax(known[::-1], axis=0)
        out[i] = np.where(known.any(axis=0), last, -1)
    return out


def sample(frame, rows):
    """A quarter x ticker frame read at dates, given latest_quarter(dates)."""
    values = frame.reindex(columns=ids()).to_numpy(dtype="float32")
    picked = np.take_along_axis(values, np.clip(rows, 0, None), axis=0)
    picked[rows < 0] = np.nan
    return picked


def raw_fields():
    fields = {}
    for table in TABLES:
        for key in data.search(table):
            if key.startswith(table + ":") and key.split(":")[1] not in NOT_FEATURES:
                frame = get(key).reindex(index=filing_dates().index, columns=ids())
                frame = frame.apply(pd.to_numeric, errors="coerce")
                fields[key.split(":")[1] + "@" + table.split("_")[1]] = frame.astype("float32")
    # market value on each filing date, like Quandl's quarterly marketcap field
    value = get("etl:us_market_value").reindex(columns=ids())
    value = value.reindex(pd.date_range(value.index[0], value.index[-1])).ffill()
    filed = filing_dates().stack()   # (quarter, ticker) -> filing date
    rows = value.index.get_indexer(pd.to_datetime(filed).values)
    cols = value.columns.get_indexer(filed.index.get_level_values(1))
    picked = np.where(rows >= 0, value.to_numpy()[np.clip(rows, 0, None), cols], np.nan)
    fields["market_value"] = pd.Series(picked, index=filed.index).unstack().reindex(
        index=filing_dates().index, columns=ids()).astype("float32")
    return fields


def variants(name, df):
    """The article's 9 derived features."""
    avg2, avg4 = df.rolling(2).mean(), df.rolling(4).mean()
    out = {
        name: df, name + "_avg2": avg2, name + "_avg4": avg4,
        name + "_diff4": df / df.shift(4), name + "_1_avg4": df / avg4,
        name + "_avg2_avg4": avg2 / avg4, name + "_avg2_diff4": avg2 / avg2.shift(4),
        name + "_avg4_diff4": avg4 / avg4.shift(4),
        name + "_df_max4": df / df.rolling(4).max(), name + "_df_max8": df / df.rolling(8).max(),
    }
    return {k: v.replace([np.inf, -np.inf], np.nan) for k, v in out.items()}


@cache
def features():
    out = {}
    for name, df in raw_fields().items():
        if df.notna().to_numpy().mean() > 0.05:
            out.update(variants(name, df))
    return out


# ---------------------------------------------------------------------------
# Feature selection
# ---------------------------------------------------------------------------
@cache
def panel():
    """Rows: (quarter end, eligible ticker); columns: features; plus the 60-day label."""
    dates = quarter_ends()
    rows = latest_quarter(dates)
    eligible = universe().reindex(dates).fillna(False).to_numpy()
    flat = eligible.ravel()
    table = {name: sample(df, rows).ravel()[flat] for name, df in features().items()}
    index = pd.MultiIndex.from_arrays([np.repeat(dates, eligible.shape[1])[flat],
                                       np.tile(ids(), len(dates))[flat]])
    opens = get("us_price:adj_open")[ids()]
    position = opens.index.searchsorted(dates, side="right")   # next trading day
    start = opens.iloc[np.clip(position, 0, len(opens) - 1)].to_numpy()
    end = opens.iloc[np.clip(position + LABEL_DAYS, 0, len(opens) - 1)].to_numpy()
    label = np.where(position[:, None] + LABEL_DAYS < len(opens), end / start - 1, np.nan)
    return pd.DataFrame(table, index=index), pd.Series(label.ravel()[flat], index=index)


@cache
def selected(until=None, as_written=True):
    """The 30 most positive and 30 most negative features, with labels known by `until`."""
    frame, label = panel()
    if until is not None:
        known = frame.index.get_level_values(0) + pd.Timedelta(days=95) < pd.Timestamp(until)
        frame, label = frame[known], label[known]
    corr = frame.corrwith(label).dropna().sort_values()
    matrix = frame[corr.index].corr().abs()
    upper = matrix.where(np.triu(np.ones(matrix.shape), k=1).astype(bool))
    to_drop = [c for c in upper.columns if any(upper[c] > 0.8)]
    kept = corr[corr.index.isin(to_drop)] if as_written else corr[~corr.index.isin(to_drop)]
    return tuple(kept.tail(FEATURES_PER_SIDE).index), tuple(kept.head(FEATURES_PER_SIDE).index), \
        {k: round(float(v), 6) for k, v in pd.concat([kept.tail(10), kept.head(10)]).items()}


@cache
def score(until=None, as_written=True):
    longs, shorts, _ = selected(until, as_written)
    rows = latest_quarter(week_ends())
    total = 0
    for names, sign in ((longs, 1), (shorts, -1)):
        for name in names:
            ranked = pd.DataFrame(features()[name]).rank(axis=1, pct=True).fillna(0)
            total = total + sign * sample(ranked, rows)
    return pd.DataFrame(total, index=week_ends(), columns=ids())


def weights(n_long, n_short, until=None, as_written=True):
    signal = score(until, as_written)[universe().reindex(week_ends()).fillna(False)]
    vol = prices()[ids()].pct_change(fill_method=None).rolling(20).std().reindex(week_ends())
    long = signal.rank(axis=1, ascending=False, method="first") <= n_long
    short = signal.rank(axis=1, ascending=True, method="first") <= n_short
    long, short = vol.where(long, 0), vol.where(short, 0)
    return long.div(long.sum(axis=1), axis=0).fillna(0) - short.div(short.sum(axis=1), axis=0).fillna(0)


@cache
def backtest(n_long, n_short, until=None, as_written=True, fee_ratio=None, start=START):
    w = weights(n_long, n_short, until, as_written).loc[start:]
    days = prices().loc[w.index[0]:END].index
    report = sim(w.reindex(days, method="ffill"), resample=w.index, position_limit=0.1,
                 fee_ratio=fee_ratio, upload=False)
    return report.creturn.loc[days[1]:END]


# ---------------------------------------------------------------------------
# Statistics
# ---------------------------------------------------------------------------
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),
        "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 main():
    print(f"{len(features())} features, panel {panel()[0].shape}", flush=True)
    grid = []
    for n_long in LONGS:
        for n_short in SHORTS:
            curve = backtest(n_long, n_short)
            row = {"long": n_long, "short": n_short, **stats(curve), "halves": halves(curve)}
            grid.append(row)
            print(f"long {n_long} short {n_short}: Sharpe {row['sharpe']:.3f} vs QQQ {row['qqq_sharpe']:.3f}"
                  f" CAGR {row['cagr']:.1%} MDD {row['mdd']:.1%}", flush=True)
    base = next(g for g in grid if (g["long"], g["short"]) == ORIGINAL)
    cost = stats(backtest(*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"]}

    middle = base["halves"][1]["start"]
    out_of_sample = stats(backtest(*ORIGINAL, until=middle, start=middle))
    intended = backtest(*ORIGINAL, as_written=False)
    out = {
        "window": {"start": START, "end": END}, "features": len(features()),
        "panel_rows": int(panel()[0].shape[0]), "original": list(ORIGINAL),
        "grid": grid, "grid_wins": wins, "cost_0.1pct": cost, "checks": checks,
        "passes": all(checks.values()),
        "top_features": selected()[2],
        "out_of_sample": {"features_from_data_before": middle, **out_of_sample,
                          "in_sample_same_dates": stats(backtest(*ORIGINAL).loc[middle:]),
                          "top_features": selected(middle)[2]},
        "keep_uncorrelated": {**stats(intended), "halves": halves(intended)},
        "finlab_version": finlab.__version__,
    }
    print("PASS" if out["passes"] else "FAIL", checks, f"grid {wins}/9", flush=True)
    print("out of sample", out_of_sample, flush=True)
    curve = backtest(*ORIGINAL)
    frame = pd.DataFrame({"Long-short, features picked with all data": curve,
                          "Long-short, features picked before the second half (traded from then)":
                              backtest(*ORIGINAL, until=middle, start=middle),
                          "Long-short, uncorrelated features kept": intended,
                          "QQQ (buy and hold)": qqq_prices().reindex(curve.index)})
    (frame / frame.bfill().iloc[0]).round(6).to_csv(OUT / "data.csv", index_label="date")
    (OUT / "metrics.json").write_text(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
