Source code · Python

edge.py

458 lines · Part of ES trading: edge and risk · All code · Read only; the files run as published

"""Is the edge real? Statistics on the trader's own weekly ES P&L. Input: app/lib/futuresLog.json, weekly P&L by month (net of fees, onecontract) and the trade counts. A new month is a new row in that file. Every test runs on the weekly P&L, not on the equity curve. The curve is arunning sum, so it trends by construction and tests on it mislead; the ADFpair in stationarity() shows the difference."""import jsonimport mathfrom pathlib import Path import numpy as npimport pandas as pdimport statsmodels.api as smfrom arch.bootstrap import StationaryBootstrapfrom scipy import statsfrom statsmodels.stats.diagnostic import acorr_ljungbox, breaks_cusumolsresid, het_archfrom statsmodels.stats.proportion import proportion_confintfrom statsmodels.tsa.stattools import acf, adfuller, kpss SEED = 20261106BLOCK = 4          # expected block length (weeks) for the stationary bootstrapDRAWS = 20000      # bootstrap and Monte Carlo drawsYEAR = 52SHOW = 60          # simulated years drawn as individual paths in the charts  def load_log(path: Path) -> tuple[pd.DataFrame, dict]:    log = json.loads(Path(path).read_text())    rows = [        {"month": m["month"], "week": i + 1, "label": f"{m['month'][:3]} W{i + 1}", "pnl": float(p), "m": k}        for k, m in enumerate(log["months"]) for i, p in enumerate(m["weeks"])    ]    return pd.DataFrame(rows), log  # ---------------------------------------------------------------------------# 1. Is the mean weekly P&L above zero?# --------------------------------------------------------------------------- def mean_tests(x: np.ndarray) -> dict:    n = len(x)    lags = int(math.floor(4 * (n / 100) ** (2 / 9)))  # Newey-West rule of thumb    ols = sm.OLS(x, np.ones(n)).fit()    hac = sm.OLS(x, np.ones(n)).fit(cov_type="HAC", cov_kwds={"maxlags": lags})    nz = x[x != 0]    wins, losses = int((x > 0).sum()), int((x < 0).sum())     bs = StationaryBootstrap(BLOCK, x, seed=SEED)    means = np.array([d[0][0].mean() for d in bs.bootstrap(DRAWS)])    lo, hi = np.percentile(means, [2.5, 97.5])    # Centred bootstrap: resample the P&L with its mean removed (a trader with    # the same week-to-week noise and no edge) and ask how often that trader's    # average is as high as the one observed.    bs0 = StationaryBootstrap(BLOCK, x - x.mean(), seed=SEED + 1)    null_means = np.array([d[0][0].mean() for d in bs0.bootstrap(DRAWS)])     edges = np.linspace(min(means.min(), null_means.min()), means.max(), 41)    return {        "n": n,        "mean": x.mean(),        "sd": x.std(ddof=1),        "t_iid": float(ols.tvalues[0]),        "p_iid_one_sided": float(stats.t.sf(ols.tvalues[0], n - 1)),        "hac_lags": lags,        "se_hac": float(hac.bse[0]),        "t_hac": float(hac.tvalues[0]),        "p_hac_one_sided": float(stats.norm.sf(hac.tvalues[0])),        "wilcoxon_p": float(stats.wilcoxon(nz, alternative="greater").pvalue),        "sign_test": {"wins": wins, "losses": losses, "p": float(stats.binomtest(wins, wins + losses, 0.5, "greater").pvalue)},        "bootstrap": {            "block": BLOCK, "draws": DRAWS, "ci95": [lo, hi],            "share_at_or_below_zero": float((means <= 0).mean()),            "p_no_edge": float((null_means >= x.mean()).mean()),            "hist": {                "edges": edges.round(1).tolist(),                "observed": np.histogram(means, edges)[0].tolist(),                "no_edge": np.histogram(null_means, edges)[0].tolist(),            },        },    }  def win_rate(log: dict) -> dict:    n = sum(p["trades"] for p in log["trade_counts"])    k = sum(p["winners"] for p in log["trade_counts"])    lo, hi = proportion_confint(k, n, 0.05, method="wilson")    return {"trades": n, "winners": k, "rate": k / n, "wilson95": [lo, hi],            "p_vs_half": float(stats.binomtest(k, n, 0.5, "greater").pvalue)}  # ---------------------------------------------------------------------------# 2. Sharpe ratio, probabilistic Sharpe ratio and minimum track record# --------------------------------------------------------------------------- def sharpe(x: np.ndarray) -> dict:    """Futures P&L needs no cash to fund it, so it is already an excess return:    no risk-free rate is subtracted. Bailey and Lopez de Prado (2012) for the    PSR and the minimum track record length, using weekly (not annualised)    Sharpe ratios and the sample skewness and kurtosis."""    n = len(x)    sr = x.mean() / x.std(ddof=1)    g3 = stats.skew(x, bias=False)    g4 = stats.kurtosis(x, fisher=False, bias=False)    denom = math.sqrt(1 - g3 * sr + (g4 - 1) / 4 * sr ** 2)     def psr(annual_target: float) -> float:        target = annual_target / math.sqrt(YEAR)        return float(stats.norm.cdf((sr - target) * math.sqrt(n - 1) / denom))     def min_trl(annual_target: float, conf: float = 0.95) -> float:        target = annual_target / math.sqrt(YEAR)        return float(1 + (1 - g3 * sr + (g4 - 1) / 4 * sr ** 2) * (stats.norm.ppf(conf) / (sr - target)) ** 2)     bs = StationaryBootstrap(BLOCK, x, seed=SEED + 2)    srs = np.array([d[0][0].mean() / d[0][0].std(ddof=1) for d in bs.bootstrap(DRAWS)]) * math.sqrt(YEAR)    return {        "weekly": sr,        "annual": sr * math.sqrt(YEAR),        "annual_ci95": np.percentile(srs, [2.5, 97.5]).tolist(),        "skew": g3,        "kurtosis": g4,        "psr": {"0": psr(0), "1": psr(1), "2": psr(2), "3": psr(3)},        "min_trl_weeks": {"0": min_trl(0), "1": min_trl(1), "2": min_trl(2)},    }  # ---------------------------------------------------------------------------# 3. Shape and independence of the weekly P&L# --------------------------------------------------------------------------- def distribution(x: np.ndarray) -> dict:    n = len(x)    jb = stats.jarque_bera(x)    sw = stats.shapiro(x)    order = np.sort(x)    z = stats.norm.ppf((np.arange(1, n + 1) - 0.375) / (n + 0.25))  # Blom plotting positions    return {        "skew": float(stats.skew(x, bias=False)),        "excess_kurtosis": float(stats.kurtosis(x, bias=False)),        "jb": {"stat": float(jb.statistic), "p": float(jb.pvalue)},        "shapiro": {"stat": float(sw.statistic), "p": float(sw.pvalue)},        "zeros": int((x == 0).sum()),        "qq": [[round(float(a), 3), float(b)] for a, b in zip(z, order)],        "qq_line": {"intercept": float(x.mean()), "slope": float(x.std(ddof=1))},    }  def runs_test(signs: np.ndarray, draws: int = 100000) -> dict:    """Wald-Wolfowitz runs test on winning (1) and losing (0) weeks, with a    permutation p-value because ten losing weeks are too few for the normal    approximation alone."""    def runs(s):        return 1 + int((s[1:] != s[:-1]).sum())    n1, n2 = int(signs.sum()), int(len(signs) - signs.sum())    r = runs(signs)    mu = 2 * n1 * n2 / (n1 + n2) + 1    var = 2 * n1 * n2 * (2 * n1 * n2 - n1 - n2) / ((n1 + n2) ** 2 * (n1 + n2 - 1))    rng = np.random.default_rng(SEED + 3)    sims = np.array([runs(rng.permutation(signs)) for _ in range(draws)])    p_perm = float((np.abs(sims - mu) >= abs(r - mu)).mean())    return {"runs": r, "expected": mu, "z": (r - mu) / math.sqrt(var), "p_normal": float(2 * stats.norm.sf(abs((r - mu) / math.sqrt(var)))), "p_permutation": p_perm}  def independence(x: np.ndarray) -> dict:    lb = acorr_ljungbox(x, lags=[1, 4], return_df=True)    lb2 = acorr_ljungbox(x ** 2, lags=[4], return_df=True)    lm = het_arch(x, nlags=2)    nz = x[x != 0]    lb_nz = acorr_ljungbox(nz, lags=[2, 4], return_df=True)    return {        "acf": acf(x, nlags=4, fft=False)[1:].tolist(),        "acf_band": 1.96 / math.sqrt(len(x)),        "ljung_box": {"lag1": {"q": float(lb.lb_stat.iloc[0]), "p": float(lb.lb_pvalue.iloc[0])},                      "lag4": {"q": float(lb.lb_stat.iloc[1]), "p": float(lb.lb_pvalue.iloc[1])}},        "ljung_box_squared_lag4": {"q": float(lb2.lb_stat.iloc[0]), "p": float(lb2.lb_pvalue.iloc[0])},        "arch_lm": {"lags": 2, "lm": float(lm[0]), "p": float(lm[1])},        "runs": runs_test((nz > 0).astype(int)),        # The log has five slots a month and some are zero, so check that the        # pattern survives with the zero weeks dropped.        "without_zero_weeks": {"acf2": float(acf(nz, nlags=2, fft=False)[2]),                               "ljung_box_lag2_p": float(lb_nz.lb_pvalue.iloc[0]), "ljung_box_lag4_p": float(lb_nz.lb_pvalue.iloc[1])},    }  # ---------------------------------------------------------------------------# 4. Stationarity and stability over the year# --------------------------------------------------------------------------- def stationarity(x: np.ndarray) -> dict:    adf_pnl = adfuller(x, autolag="AIC")    adf_eq = adfuller(np.cumsum(x), autolag="AIC")    kp = kpss(x, regression="c", nlags="auto")    return {        "adf_pnl": {"stat": float(adf_pnl[0]), "p": float(adf_pnl[1]), "lags": int(adf_pnl[2])},        "adf_equity": {"stat": float(adf_eq[0]), "p": float(adf_eq[1]), "lags": int(adf_eq[2])},        "kpss_pnl": {"stat": float(kp[0]), "p": float(kp[1])},    }  def stability(df: pd.DataFrame) -> dict:    x = df.pnl.to_numpy()    half = len(x) // 2    a, b = x[:half], x[half:]    cusum = breaks_cusumolsresid(x - x.mean(), ddof=1)    return {        "first": {"from": df.month.iloc[0], "to": df.month.iloc[half - 1], "weeks": len(a), "mean": a.mean(), "total": a.sum()},        "second": {"from": df.month.iloc[half], "to": df.month.iloc[-1], "weeks": len(b), "mean": b.mean(), "total": b.sum()},        "welch_p": float(stats.ttest_ind(a, b, equal_var=False).pvalue),        "mann_whitney_p": float(stats.mannwhitneyu(a, b).pvalue),        "cusum": {"stat": float(cusum[0]), "p": float(cusum[1])},    }  # ---------------------------------------------------------------------------# 5. Weekly VaR and expected shortfall, and what a 50 week backtest can show# --------------------------------------------------------------------------- def kupiec_lr(breaches: int, t: int, p: float) -> float:    """Kupiec proportion of failures likelihood ratio (chi-square, 1 df)."""    x = breaches    phat = x / t    ll0 = (t - x) * math.log(1 - p) + (x * math.log(p) if x else 0)    ll1 = ((t - x) * math.log(1 - phat) if x < t else 0) + (x * math.log(phat) if x else 0)    return -2 * (ll0 - ll1)  def kupiec_power(t: int, p: float, true_p: float, size: float = 0.05) -> float:    crit = stats.chi2.ppf(1 - size, 1)    reject = [x for x in range(t + 1) if kupiec_lr(x, t, p) > crit]    return float(sum(stats.binom.pmf(x, t, true_p) for x in reject))  def weeks_for_power(p: float, true_p: float, power: float = 0.8) -> int:    for t in range(20, 5000):        if kupiec_power(t, p, true_p) >= power:            return t    return -1  def var_es(x: np.ndarray) -> dict:    """Losses are reported as positive dollars for one contract over a week."""    mu, sd = x.mean(), x.std(ddof=1)    s, k = stats.skew(x, bias=False), stats.kurtosis(x, bias=False)    out = {}    for conf in (0.90, 0.95):        a = 1 - conf        z = stats.norm.ppf(a)        zcf = z + (z ** 2 - 1) * s / 6 + (z ** 3 - 3 * z) * k / 24 - (2 * z ** 3 - 5 * z) * s ** 2 / 36        q = np.quantile(x, a)        out[f"{int(conf * 100)}"] = {            "historical_var": -q,            "historical_es": -x[x <= q].mean(),            "normal_var": -(mu + z * sd),            "normal_es": sd * stats.norm.pdf(z) / a - mu,            "cornish_fisher_var": -(mu + zcf * sd),        }     # Out of sample: from week 14 on, each week's 90% VaR from the weeks before it.    start = 13    hist_breach = [x[t] < np.quantile(x[:t], 0.10) for t in range(start, len(x))]    norm_breach = [x[t] < x[:t].mean() + stats.norm.ppf(0.10) * x[:t].std(ddof=1) for t in range(start, len(x))]    t_obs = len(x) - start    out["backtest"] = {        "start_week": start + 1, "weeks": t_obs, "level": 0.90, "expected": 0.10 * t_obs,        "historical": {"breaches": int(sum(hist_breach)), "kupiec_p": float(stats.chi2.sf(kupiec_lr(int(sum(hist_breach)), t_obs, 0.10), 1))},        "normal": {"breaches": int(sum(norm_breach)), "kupiec_p": float(stats.chi2.sf(kupiec_lr(int(sum(norm_breach)), t_obs, 0.10), 1))},        "power_if_true_rate_doubles": kupiec_power(t_obs, 0.10, 0.20),        "weeks_for_80pct_power": {"90": weeks_for_power(0.10, 0.20), "95": weeks_for_power(0.05, 0.10), "99": weeks_for_power(0.01, 0.02)},    }    return out  # ---------------------------------------------------------------------------# 6. Monte Carlo: what a year could look like# --------------------------------------------------------------------------- def max_drawdown(paths: np.ndarray) -> np.ndarray:    eq = np.concatenate([np.zeros((paths.shape[0], 1)), np.cumsum(paths, axis=1)], axis=1)    return (eq - np.maximum.accumulate(eq, axis=1)).min(axis=1)  def stationary_paths(x: np.ndarray, weeks: int, draws: int, block: float, seed: int) -> np.ndarray:    """Politis-Romano stationary bootstrap paths: blocks of random length    (geometric, mean `block`) taken from the log with wrap-around, so runs of    good and bad weeks keep the order they had."""    rng = np.random.default_rng(seed)    n = len(x)    idx = np.empty((draws, weeks), dtype=int)    idx[:, 0] = rng.integers(0, n, draws)    new_block = rng.random((draws, weeks)) < 1 / block    jumps = rng.integers(0, n, (draws, weeks))    for t in range(1, weeks):        idx[:, t] = np.where(new_block[:, t], jumps[:, t], (idx[:, t - 1] + 1) % n)    return x[idx]  def monte_carlo(x: np.ndarray, capital: float, realised_dd: float) -> dict:    paths = stationary_paths(x, YEAR, DRAWS, BLOCK, SEED + 4)    eq = np.cumsum(paths, axis=1)    annual = eq[:, -1]    dd = max_drawdown(paths)    same_len = max_drawdown(stationary_paths(x, len(x), DRAWS, BLOCK, SEED + 5))    no_edge = stationary_paths(x - x.mean(), YEAR, DRAWS, BLOCK, SEED + 6)    dd0 = max_drawdown(no_edge)    eq0 = np.cumsum(no_edge, axis=1)    half = stationary_paths(x - x.mean() / 2, YEAR, DRAWS, BLOCK, SEED + 7)    ddh = max_drawdown(half)    pct = [5, 25, 50, 75, 95]    fan = np.percentile(np.concatenate([np.zeros((DRAWS, 1)), eq], axis=1), pct, axis=0)     # For the path charts: the first SHOW simulated years of each scenario as    # running totals from zero, the 5th/50th/95th percentile at each week from    # all draws, and the year-end and drawdown distributions on shared bins.    scenarios = {"as_traded": paths, "half_edge": half, "no_edge": no_edge}    running = {k: np.concatenate([np.zeros((DRAWS, 1)), np.cumsum(v, axis=1)], axis=1) for k, v in scenarios.items()}    ends = {k: v[:, -1] for k, v in running.items()}    dds = {"as_traded": -dd, "half_edge": -ddh, "no_edge": -dd0}    end_edges = np.linspace(min(e.min() for e in ends.values()), max(e.max() for e in ends.values()), 61)    dd_edges = np.linspace(0, max(np.percentile(d, 99.5) for d in dds.values()), 61)    sample_paths = {        k: {"paths": v[:SHOW].round(0).tolist(),            "bands": {str(q): row.round(0).tolist() for q, row in zip((5, 50, 95), np.percentile(v, (5, 50, 95), axis=0))}}        for k, v in running.items()    }    distributions = {        "year_end": {"edges": end_edges.round(0).tolist(), "counts": {k: np.histogram(v, end_edges)[0].tolist() for k, v in ends.items()}},        "drawdown": {"edges": dd_edges.round(0).tolist(), "counts": {k: np.histogram(np.clip(v, 0, dd_edges[-1]), dd_edges)[0].tolist() for k, v in dds.items()}},    }    # Position sizing: N contracts multiply every week, so every path and    # drawdown scales by N on the same capital.    half_annual = half.sum(axis=1)    sizing = []    for n in (1, 2, 3, 4):        sizing.append({            "contracts": n,            "median_year": float(n * np.median(annual)),            "bad_year": float(n * np.percentile(annual, 5)),            "dd_p95": float(-n * np.percentile(dd, 5)),            "p_dd_half_capital": float((-n * dd > capital / 2).mean()),            "p_dd_capital": float((-n * dd > capital).mean()),            "half_edge": {                "median_year": float(n * np.median(half_annual)),                "dd_p95": float(-n * np.percentile(ddh, 5)),                "p_dd_half_capital": float((-n * ddh > capital / 2).mean()),                "p_dd_capital": float((-n * ddh > capital).mean()),                "p_losing_year": float((half_annual < 0).mean()),            },            "worst_week": float(n * x.min()),        })    sens = {}    for b in (1, 2, 4, 8):        p = stationary_paths(x, YEAR, DRAWS, b, SEED + 10 + b)        sens[str(b)] = {"p_losing_year": float((p.sum(axis=1) < 0).mean()), "dd_p95": float(-np.percentile(max_drawdown(p), 5))}    return {        "draws": DRAWS, "weeks": YEAR, "block": BLOCK,        "annual": dict(zip(map(str, pct), np.percentile(annual, pct).tolist())),        "p_losing_year": float((annual < 0).mean()),        "drawdown": {"median": float(-np.median(dd)), "p95": float(-np.percentile(dd, 5)), "p99": float(-np.percentile(dd, 1)),                     "p_over_half_capital": float((dd < -capital / 2).mean()),                     "p_over_capital": float((dd < -capital).mean())},        "realised_drawdown_percentile": float((same_len <= realised_dd).mean()),        "same_length_median_dd": float(-np.median(same_len)),        "no_edge": {"p_losing_year": float((eq0[:, -1] < 0).mean()),                    "annual_median": float(np.median(eq0[:, -1])), "annual_p5": float(np.percentile(eq0[:, -1], 5)),                    "dd_median": float(-np.median(dd0)), "dd_p95": float(-np.percentile(dd0, 5)),                    "p_dd_over_half_capital": float((dd0 < -capital / 2).mean()),                    "p_down_half_capital": float((eq0.min(axis=1) < -capital / 2).mean())},        "half_edge": {"p_losing_year": float((half.sum(axis=1) < 0).mean()), "annual_median": float(np.median(half.sum(axis=1))),                      "annual_p5": float(np.percentile(half.sum(axis=1), 5)),                      "p_dd_over_half_capital": float((ddh < -capital / 2).mean()),                      "dd_median": float(-np.median(ddh)), "dd_p95": float(-np.percentile(ddh, 5))},        "fan": {str(p): row.round(0).tolist() for p, row in zip(pct, fan)},        "sizing": sizing,        "sample_paths": sample_paths,        "distributions": distributions,        "block_sensitivity": sens,    }  # ---------------------------------------------------------------------------# 7. How many contracts? The Kelly criterion# --------------------------------------------------------------------------- def kelly(x: np.ndarray, capital: float, mean_low: float) -> dict:    """Contracts that maximise the expected log growth of `capital`.     Exact on the log: maximise the mean of log(1 + N x / capital) over the    weeks. The curve uses the usual approximation, growth per week    = N mu / C - N^2 sigma^2 / (2 C^2), with its peak at N* = C mu / sigma^2,    for the measured edge, the bottom of its 95% interval and half of it.    Kelly assumes the edge is known exactly; it is not, which is why    practitioners bet a fraction of it."""    from scipy.optimize import minimize_scalar    sd = x.std(ddof=1)     def exact(sample: np.ndarray) -> float:        cap = capital / -sample.min() * 0.999  # beyond this a repeat of the worst week wipes out the account        res = minimize_scalar(lambda n: -np.mean(np.log1p(n * sample / capital)), bounds=(0, cap), method="bounded")        return float(res.x)     edges = {"measured": float(x.mean()), "low": float(mean_low), "half": float(x.mean() / 2)}    grid = np.round(np.arange(0, 6.01, 0.25), 2)    curves = {k: (100 * (grid * mu / capital - grid ** 2 * sd ** 2 / (2 * capital ** 2))).round(3).tolist() for k, mu in edges.items()}    return {        "capital": capital, "sd": float(sd), "edges": edges,        "kelly_approx": {k: float(capital * mu / sd ** 2) for k, mu in edges.items()},        "kelly_exact": {"measured": exact(x), "half": exact(x - x.mean() / 2)},        "max_before_ruin": float(capital / -x.min()),        "grid": grid.tolist(), "curves": curves,        "growth_one_contract_pct": {k: float(100 * (mu / capital - sd ** 2 / (2 * capital ** 2))) for k, mu in edges.items()},    }  # ---------------------------------------------------------------------------# 8. Monthly results against the market# --------------------------------------------------------------------------- def market_link(monthly: pd.DataFrame) -> dict:    """monthly: columns pnl, spx (return), spx_abs, rv (realised vol), vix (average)."""    n = len(monthly)    out = {"months": n, "rows": monthly.reset_index().to_dict("records")}    for col in ("spx", "spx_abs", "rv", "vix"):        r, p = stats.pearsonr(monthly[col], monthly.pnl)        rho, ps = stats.spearmanr(monthly[col], monthly.pnl)        out[col] = {"pearson": float(r), "p": float(p), "spearman": float(rho), "spearman_p": float(ps)}    X = sm.add_constant(monthly.spx.to_numpy())    fit = sm.OLS(monthly.pnl.to_numpy(), X).fit(cov_type="HAC", cov_kwds={"maxlags": 1})    out["regression"] = {"alpha": float(fit.params[0]), "alpha_p": float(fit.pvalues[0]),                         "beta_per_1pct": float(fit.params[1] / 100), "beta_p": float(fit.pvalues[1]), "r2": float(fit.rsquared)}    return out  def analyse(log_path: Path) -> tuple[dict, pd.DataFrame]:    df, log = load_log(log_path)    x = df.pnl.to_numpy()    eq = np.concatenate([[0], np.cumsum(x)])    realised_dd = float((eq - np.maximum.accumulate(eq)).min())    tests = mean_tests(x)    result = {        "weeks": len(x), "months": [m["month"] for m in log["months"]], "year": log["year"],        "total": float(x.sum()), "realised_drawdown": realised_dd,        "capital": log["capital_per_contract"],        "mean_tests": tests,        "win_rate": win_rate(log),        "sharpe": sharpe(x),        "distribution": distribution(x),        "independence": independence(x),        "stationarity": stationarity(x),        "stability": stability(df),        "var": var_es(x),        "monte_carlo": monte_carlo(x, log["capital_per_contract"], realised_dd),        "kelly": kelly(x, log["capital_per_contract"], tests["bootstrap"]["ci95"][0]),        "nonzero_check": {"weeks": int((x != 0).sum()), "t_hac": float(sm.OLS(x[x != 0], np.ones((x != 0).sum())).fit(cov_type="HAC", cov_kwds={"maxlags": 3}).tvalues[0])},    }    return result, df