Source code · Python

benchmark.py

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

"""Against simple intraday rules: could a mechanical rule or luck have done as well? Every rule trades one contract from the S&P 500 open to its close (indexpoints stand in for ES points; $50 each) on the same sessions as the log,before commissions and slippage, which flatters the rules, not the log:    long every session    long every session except FOMC days (the trader's calendar filter alone)    short every session    a random trader: as many sessions as the log has trades, picked at random,        each long or short at random, 20,000 times Profit alone is a weak comparison: a rule that holds the whole session takesfar more risk than short intraday trades with stops. So each is also judgedon profit per dollar of maximum drawdown. The log's drawdown is measured weekto week and the rules' day to day, which flatters the log a little."""import numpy as npimport pandas as pd POINT = 50DRAWS = 20000SEED = 20261106  def _drawdown(cum: np.ndarray) -> float:    eq = np.concatenate([[0.0], cum])    return float((eq - np.maximum.accumulate(eq)).min())  def intraday_benchmarks(spx: pd.DataFrame, fomc: pd.Series, log: dict) -> dict:    year = log["year"]    months = [m["month"] for m in log["months"]]    s = spx.loc[f"{year}-01-01": pd.Timestamp(year, len(months), 1) + pd.offsets.MonthEnd(0)]    oc = ((s.close - s.open) * POINT).rename("usd")    is_fomc = s.index.isin(pd.DatetimeIndex(fomc))    trades = sum(p["trades"] for p in log["trade_counts"])    mine_monthly = np.array([sum(m["weeks"]) for m in log["months"]], dtype=float)    mine_total = float(mine_monthly.sum())     rules = {        "Long every session": oc,        "Long, skipping FOMC days": oc.where(~is_fomc, 0.0),        "Short every session": -oc,    }    rows, monthly = [], {"My trading": mine_monthly.tolist()}    for name, pnl in rules.items():        by_month = pnl.groupby(pnl.index.month).sum().reindex(range(1, len(months) + 1), fill_value=0.0)        traded = pnl[pnl != 0]        dd = _drawdown(pnl.cumsum().to_numpy())        rows.append({            "rule": name, "total": float(pnl.sum()), "sessions": int((pnl != 0).sum()),            "win_rate": float((traded > 0).mean()), "worst_day": float(pnl.min()),            "max_drawdown": dd,            "profit_to_drawdown": float(pnl.sum() / -dd) if dd < 0 else None,            "corr_with_mine": float(np.corrcoef(by_month.to_numpy(), mine_monthly)[0, 1]),        })        monthly[name] = by_month.round(0).tolist()     # The random trader: `trades` sessions without replacement, random sides.    rng = np.random.default_rng(SEED)    values = oc.to_numpy()    picks = np.argsort(rng.random((DRAWS, len(values))), axis=1)[:, :trades]    sides = rng.choice([-1.0, 1.0], size=(DRAWS, trades))    random_totals = (values[picks] * sides).sum(axis=1)    random_long = values[picks].sum(axis=1)    # Drawdowns need the trades in date order.    order = np.argsort(picks, axis=1)    ordered = np.take_along_axis(picks, order, axis=1)    order_sides = np.take_along_axis(sides, order, axis=1)    paths = np.cumsum(values[ordered] * order_sides, axis=1)    eq = np.concatenate([np.zeros((DRAWS, 1)), paths], axis=1)    random_dd = (eq - np.maximum.accumulate(eq, axis=1)).min(axis=1)    mine_dd = _drawdown(np.cumsum([w for m in log["months"] for w in m["weeks"]]))    mine_ratio = mine_total / -mine_dd    random_ratio = np.where(random_dd < 0, paths[:, -1] / np.maximum(-random_dd, 1e-9), np.inf)    edges = np.linspace(min(random_totals.min(), random_long.min()), max(random_totals.max(), random_long.max(), mine_total * 1.05), 61)     return {        "year": year, "sessions": len(oc), "trades": trades, "first": s.index[0].date().isoformat(), "last": s.index[-1].date().isoformat(),        "fomc_sessions": int(is_fomc.sum()),        "mine": {"total": mine_total, "worst_month": float(mine_monthly.min()), "max_drawdown": mine_dd, "profit_to_drawdown": mine_ratio},        "rules": rows,        "monthly": monthly,        "cumulative": {k: np.cumsum(v).round(0).tolist() for k, v in monthly.items()},        "random": {            "draws": DRAWS,            "median": float(np.median(random_totals)), "p95": float(np.percentile(random_totals, 95)), "p99": float(np.percentile(random_totals, 99)),            "best": float(random_totals.max()), "share_beating_mine": float((random_totals >= mine_total).mean()),            "median_drawdown": float(np.median(random_dd)),            "share_profit_and_drawdown": float(((paths[:, -1] >= mine_total) & (random_dd >= mine_dd)).mean()),            "share_ratio_beating_mine": float((random_ratio >= mine_ratio).mean()),            "best_ratio": float(np.max(random_ratio[np.isfinite(random_ratio)])),            "long_median": float(np.median(random_long)), "long_best": float(random_long.max()),            "long_share_beating_mine": float((random_long >= mine_total).mean()),            "edges": edges.round(0).tolist(),            "counts": {"random_side": np.histogram(random_totals, edges)[0].tolist(), "random_long": np.histogram(random_long, edges)[0].tolist()},        },        "avg_abs_session_usd": float(np.abs(values).mean()),    }