Source code · Python
run.py
"""Run the study end to end and write the figures the website shows. edge.py the trader's own weekly P&L: is the edge real, what can go wrong, position sizing and the Kelly criterion benchmark.py the log against simple intraday rules and a random trader market_risk.py S&P 500 / ES daily risk: tests, GARCH, VaR backtests, FOMC, gaps pricing.py a one-week put on ES, priced several ways market_data.py downloads (Yahoo daily bars, Federal Reserve FOMC calendars) Usage: python3 run.py [cache_dir]Reads app/lib/futuresLog.json and writes app/lib/esEdge.json in the websiteproject. The market window ends on the last trading day of the last month inthe log, so adding November and December to the log moves everything forward."""import jsonimport sysfrom pathlib import Path import numpy as npimport pandas as pd import benchmarkimport edgeimport market_data as mdimport market_risk as mrimport pricing HERE = Path(__file__).resolve().parentSITE = HERE.parents[1] / "app" / "lib"LOG = SITE / "futuresLog.json"OUT = SITE / "esEdge.json" def tidy(o): """Round floats for the website and turn numpy and pandas values into JSON.""" if isinstance(o, dict): return {str(k): tidy(v) for k, v in o.items()} if isinstance(o, (list, tuple)): return [tidy(v) for v in o] if isinstance(o, (np.floating, float)): v = float(o) if not np.isfinite(v): return None return round(v, 6) if abs(v) < 1 else round(v, 4) if isinstance(o, (np.integer,)): return int(o) if isinstance(o, (np.bool_,)): return bool(o) if isinstance(o, pd.Timestamp): return o.date().isoformat() return o def main() -> None: cache = Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / ".cache" / "es-trading-edge" own, weeks = edge.analyse(LOG) log = json.loads(LOG.read_text()) year, months = log["year"], [m["month"] for m in log["months"]] end = pd.Timestamp(year, len(months), 1) + pd.offsets.MonthEnd(0) spx = md.daily_bars("^GSPC", cache).loc[:end] es = md.daily_bars("ES=F", cache).loc[:end] vix = md.daily_bars("^VIX", cache).loc[:end] fomc = md.fomc_dates(cache) md.write_fomc_csv(fomc) last_day = spx.index[-1] r = mr.log_returns(spx.close) print("tracking and pre-tests") track = mr.tracking(es, spx) pre = mr.pretests(r, spx.close) print("GARCH family") family, fits = mr.fit_family(r) resid = {"skewt": mr.residual_checks(fits["GJR-GARCH(1,1), skewed t"]), "t": mr.residual_checks(fits["GJR-GARCH(1,1), Student t"])} print("VaR backtest (refits every", mr.REFIT, "days)") backtest = mr.var_backtest(r, spx.close) print("FOMC study") fomc_in = fomc.date[fomc.date <= last_day] fstudy = mr.fomc_study(spx, fomc_in, year) gaps = mr.overnight(spx, year, log["capital_per_contract"], log["largest_trade_loss"]) bench = benchmark.intraday_benchmarks(spx, fomc_in, log) monthly = mr.monthly_market(spx, vix, year, months) monthly["pnl"] = [sum(m["weeks"]) for m in log["months"]] link = edge.market_link(monthly) print("option prices") inputs = json.loads((HERE / "data" / "inputs.json").read_text()) put = pricing.price_put(r, float(es.close.iloc[-1]), float(vix.close.iloc[-1]), inputs["risk_free"]["value"], last_day.date().isoformat()) result = { "meta": { "year": year, "months": months, "first_month": months[0], "last_month": months[-1], "market_end": last_day.date().isoformat(), "market_start": r.index[0].date().isoformat(), "fomc_meetings": len(fomc_in), "fomc_in_year": int((fomc_in.dt.year == year).sum()), "risk_free": inputs["risk_free"], "sources": { "log": "Live trading, one ES contract per trade, the trader's own log, net of fees, unaudited", "index": "S&P 500 (^GSPC), ES=F and VIX (^VIX) daily bars: Yahoo Finance chart data", "fomc": "FOMC meeting calendars, Board of Governors of the Federal Reserve System", }, }, "own": own, "weeks": weeks[["label", "month", "pnl"]].to_dict("records"), "market_link": link, "benchmark": bench, "market": {"tracking": track, "pretests": pre, "garch": family, "residuals": resid, "backtest": backtest}, "fomc": fstudy, "overnight": gaps, "pricing": put, } OUT.write_text(json.dumps(tidy(result), indent=1) + "\n") print(f"wrote {OUT}") if __name__ == "__main__": main()