From 8ac8ef227ced6c4880718276216ced29cde342a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:03:40 +0000 Subject: [PATCH] Cut the US overnight auction book; add a weekly review of the sheet book - config/sheet_book.json: auction_overnight_weight 0. From Monday the auction sleeve opens no overnight book (Friday's book still settles at Monday's open); the ADR book keeps the sleeve's capital. - qtrade/intraday/weekly_review.py + weekly-review.yml (Saturdays): each sleeve's live Sharpe vs its backtest (config/review.json), z = (S - B) * sqrt(n/252); no verdict before 40 live days, then cut at z <= -2, halve at z <= -1. Results go to a 'Weekly review' tab; changes go in by PR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NsPrq53XXinQsUZsWqeKht --- .github/workflows/weekly-review.yml | 34 +++++ config/review.json | 12 ++ config/sheet_book.json | 5 +- qtrade/intraday/auction_sheet.py | 13 +- qtrade/intraday/weekly_review.py | 202 ++++++++++++++++++++++++++++ tests/test_weekly_review.py | 63 +++++++++ 6 files changed, 324 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/weekly-review.yml create mode 100644 config/review.json create mode 100644 qtrade/intraday/weekly_review.py create mode 100644 tests/test_weekly_review.py diff --git a/.github/workflows/weekly-review.yml b/.github/workflows/weekly-review.yml new file mode 100644 index 000000000..479131a7b --- /dev/null +++ b/.github/workflows/weekly-review.yml @@ -0,0 +1,34 @@ +name: weekly-review + +# The weekly review of the $10,000 sheet book (qtrade/intraday/weekly_review.py): every Saturday each +# sleeve's live record is compared with its backtest under the fixed rule in config/review.json, and the +# result goes to the sheet's "Weekly review" tab. It only proposes; changes to config/sheet_book.json go +# in by pull request. + +on: + schedule: + - cron: "17 14 * * 6" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: weekly-review + cancel-in-progress: false + +jobs: + review: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + GOOGLE_SERVICE_ACCOUNT_JSON: ${{ secrets.GOOGLE_SERVICE_ACCOUNT_JSON }} + HFT_SHEET_ID: ${{ secrets.HFT_SHEET_ID }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + - run: pip install -r requirements.txt + - run: python -m qtrade.intraday.weekly_review diff --git a/config/review.json b/config/review.json new file mode 100644 index 000000000..d968dcaea --- /dev/null +++ b/config/review.json @@ -0,0 +1,12 @@ +{ + "_comment": "The weekly review's fixed rule (qtrade/intraday/weekly_review.py). Backtest Sharpes are annualised, 0 bp fees like the sheet, from the most recent test period of each rule's study (results branch): momentum_flip = flip_check.md gross 2021-26 (0.33); auction_overnight = intraday_strategies.csv, second half, last30 fade (+1.74) and overnight persistence (+0.59) blended (~1.2); adr = asia_adr_strategy.csv, FX lagged a day, 0 bp, 2015-26 (2.91); foreign = foreign_strategies.csv, overnight persistence 2021-26 across the 8 markets, conservatively 1.5. A null backtest Sharpe marks a $0 tracker (information only). Change the rule only before a review, never because of one.", + "rule": {"min_days": 40, "cut_z": -2.0, "halve_z": -1.0}, + "backtest_sharpe": { + "momentum_flip": 0.33, + "auction_overnight": 1.2, + "adr": 2.91, + "foreign": 1.5, + "foreign_hft_tracker": null, + "crm_tracker": null + } +} diff --git a/config/sheet_book.json b/config/sheet_book.json index 703cb6283..6ddf3c255 100644 --- a/config/sheet_book.json +++ b/config/sheet_book.json @@ -1,7 +1,8 @@ { - "_comment": "The simulated $10,000 Google Sheet book, split between sleeves (dollars of capital). momentum_flip = Nico's momentum flip (qtrade/intraday/flip_sleeve.py); auction = the US auction strategies (qtrade/intraday/auction_sheet.py); foreign = overnight persistence on Asian exchanges (qtrade/intraday/foreign_sheet.py); hft = the shadow HFT (off). History: $5,000 HFT / $5,000 flip on 2026-10-22; the HFT lost $273.73 and was switched off; the remaining $9,726.27 split flip / auction on 2026-10-23, then three ways with the foreign sleeve.", + "_comment": "The simulated $10,000 Google Sheet book, split between sleeves (dollars of capital). momentum_flip = Nico's momentum flip (qtrade/intraday/flip_sleeve.py); auction = the US auction strategies (qtrade/intraday/auction_sheet.py); foreign = overnight persistence on Asian exchanges (qtrade/intraday/foreign_sheet.py); hft = the shadow HFT (off). History: $5,000 HFT / $5,000 flip on 2026-10-22; the HFT lost $273.73 and was switched off; the remaining $9,726.27 split flip / auction on 2026-10-23, then three ways with the foreign sleeve. 2026-11-28: the US overnight auction book was cut (auction_overnight_weight 0) after it lost $100 in 26 days (Sharpe -1.9); the auction sleeve's capital stays with the ADR book. The weekly review (qtrade/intraday/weekly_review.py) proposes later changes.", "hft": 0, "momentum_flip": 3242.09, "auction": 3242.09, - "foreign": 3242.09 + "foreign": 3242.09, + "auction_overnight_weight": 0.0 } diff --git a/qtrade/intraday/auction_sheet.py b/qtrade/intraday/auction_sheet.py index ba111788c..4352fb543 100644 --- a/qtrade/intraday/auction_sheet.py +++ b/qtrade/intraday/auction_sheet.py @@ -207,7 +207,8 @@ def settle_day(day: str, inputs: dict, prev_hold: pd.DataFrame, equity: float, d "adr_names": len(adr)} -def run(sleeve_usd: float, cfg, tickers: list[str], signs: dict, dry_run: bool = False) -> dict: +def run(sleeve_usd: float, cfg, tickers: list[str], signs: dict, dry_run: bool = False, + overnight_weight: float = 1.0) -> dict: now = pd.Timestamp.now(tz=NY) day = now.tz_localize(None).normalize() sheet = None if dry_run else AuctionSheet(os.environ["HFT_SHEET_ID"], os.environ["GOOGLE_SERVICE_ACCOUNT_JSON"]) @@ -217,6 +218,9 @@ def run(sleeve_usd: float, cfg, tickers: list[str], signs: dict, dry_run: bool = inputs = day_inputs(cfg, tickers, signs, day) if len(inputs["close"]) < 0.5 * len(tickers): return {"skipped": f"only {len(inputs['close'])} official closes today - market closed or data late"} + # the weekly review can scale the overnight book down (config/sheet_book.json "auction_overnight_weight"); + # last night's book still settles at today's open, only tonight's is scaled + inputs["weights"] = {t: w * overnight_weight for t, w in inputs["weights"].items() if w * overnight_weight} if len(log): hold.attrs["date"] = str(log["Date"].iloc[-1]) equity = float(pd.to_numeric(log["Equity $"], errors="coerce").dropna().iloc[-1]) if len(log) else 0.0 @@ -232,7 +236,9 @@ def run(sleeve_usd: float, cfg, tickers: list[str], signs: dict, dry_run: bool = status = (f"Updated {now:%Y-%m-%d %H:%M} New York - capital ${sleeve_usd:,.2f} -> equity ${res['equity']:,.2f} " f"(P&L ${total:+,.2f}). Today: overnight book ${res['pnl_overnight']:+,.2f}, ADR book " f"${res['pnl_adr']:+,.2f}. Tonight: {row[6]} long / {row[7]} short, ${row[8]:,.0f} gross " - f"(strategies: {', '.join(inputs['strategies']) or 'none'}).") + + (f"(strategies: {', '.join(inputs['strategies']) or 'none'})." if overnight_weight > 0 else + "(overnight book off since the 2026-11-28 review; the ADR book trades on).") + + (f" Overnight book at {overnight_weight:.0%} weight." if 0 < overnight_weight < 1 else "")) if sheet: sheet.write(status, row, len(log), h, res["trades"]) LOG.info("auction sleeve: %s", status) @@ -265,7 +271,8 @@ def main(argv=None): return cfg = Config.load(args.config) tickers, signs = load_inputs(args.tickers, args.signs if Path(args.signs).exists() else None) - print(run(sleeve, cfg, tickers, signs, dry_run=args.dry_run)) + print(run(sleeve, cfg, tickers, signs, dry_run=args.dry_run, + overnight_weight=book_split().get("auction_overnight_weight", 1.0))) if __name__ == "__main__": diff --git a/qtrade/intraday/weekly_review.py b/qtrade/intraday/weekly_review.py new file mode 100644 index 000000000..742a4be77 --- /dev/null +++ b/qtrade/intraday/weekly_review.py @@ -0,0 +1,202 @@ +"""Weekly review of the $10,000 sheet book: each sleeve's live record against its backtest. + +Every Saturday (``.github/workflows/weekly-review.yml``) this reads the daily logs in the sheet, +computes each sleeve's live statistics and writes them to the "Weekly review" tab, with a verdict +from a rule fixed in advance (``config/review.json``), so the sleeves are not retuned on noise: + +* the live annualised Sharpe ``S`` over ``n`` trading days is compared with the backtest Sharpe + ``B`` of the same rule (0 bp fees, like the sheet). A Sharpe estimated from ``n`` days has a + standard error of about ``sqrt(252 / n)``, so ``z = (S - B) * sqrt(n / 252)``; +* before ``min_days`` live days there is no verdict ("too early"), whatever the numbers; +* ``z <= cut_z`` (-2): **cut** - the live record is clearly worse than the backtest; + ``z <= halve_z`` (-1): **halve**; otherwise **keep**. A sleeve already cut is reported as "off"; + the review does not re-enable it - that needs its backtest re-run on newer data first. + +The review only proposes; the change itself (``config/sheet_book.json``) goes in by pull request. +The two $0 trackers (foreign HFT, CRM satellite) are listed for information - neither is in the book. +""" +from __future__ import annotations + +import json +import os +from pathlib import Path + +import numpy as np +import pandas as pd + +from ..utils import LOG + +TAB = "Weekly review" +REVIEW_FILE = Path(__file__).resolve().parents[2] / "config" / "review.json" +HEADER = ["Sleeve", "In book", "Live days", "P&L $", "Live Sharpe", "Backtest Sharpe", "z", "Days up", + "Max drawdown $", "Verdict", "Why"] + + +# --- pure statistics ----------------------------------------------------------------------------- +def stats(daily: pd.DataFrame) -> dict: + """``daily``: one row per trading day with ``pnl`` (dollars) and ``ret`` (fraction of capital).""" + n = len(daily) + if n == 0: + return {"days": 0, "pnl": 0.0, "sharpe": np.nan, "hit": np.nan, "max_dd": 0.0} + r = daily["ret"].astype(float) + sd = r.std(ddof=1) if n > 1 else np.nan + cum = daily["pnl"].astype(float).cumsum() + return {"days": n, "pnl": float(daily["pnl"].sum()), + "sharpe": float(r.mean() / sd * np.sqrt(252)) if sd and np.isfinite(sd) and sd > 0 else np.nan, + "hit": float((daily["pnl"] > 0).mean()), "max_dd": float((cum - cum.cummax().clip(lower=0)).min())} + + +def verdict(st: dict, backtest_sharpe: float | None, rule: dict, in_book: bool) -> tuple[str, float, str]: + """(verdict, z, why) from the fixed rule.""" + if not in_book: + return "off", np.nan, "already out of the book" + if backtest_sharpe is None: + return "info", np.nan, "$0 tracker, not in the book" + n, s = st["days"], st["sharpe"] + if not np.isfinite(s): + return "too early", np.nan, f"{n} live days" + z = (s - backtest_sharpe) * np.sqrt(n / 252) + if n < rule["min_days"]: + return "too early", z, f"{n} of {rule['min_days']} live days needed" + if z <= rule["cut_z"]: + return "cut", z, f"live Sharpe {s:.2f} vs backtest {backtest_sharpe:.2f}: z {z:.2f} <= {rule['cut_z']}" + if z <= rule["halve_z"]: + return "halve", z, f"live Sharpe {s:.2f} vs backtest {backtest_sharpe:.2f}: z {z:.2f} <= {rule['halve_z']}" + return "keep", z, f"live Sharpe {s:.2f} vs backtest {backtest_sharpe:.2f}: z {z:.2f}" + + +# --- daily series from each tab's log ------------------------------------------------------------ +def _num(x) -> pd.Series: + return pd.to_numeric(pd.Series(x), errors="coerce") + + +def _frame(rows: list[list], width: int) -> pd.DataFrame: + rows = [r + [""] * (width - len(r)) for r in rows if r and str(r[0])[:2] == "20"] + return pd.DataFrame(rows, columns=range(width)) if rows else pd.DataFrame(columns=range(width)) + + +def daily_flip(rows) -> pd.DataFrame: + f = _frame(rows, 10) # Date, VIX, Regime, Longs, Shorts, Gross, Day P&L $, Day %, Equity, Turnover + return pd.DataFrame({"date": f[0], "pnl": _num(f[6]).values, "ret": _num(f[7]).values / 100}).dropna() + + +def daily_auction(rows, col: int) -> pd.DataFrame: + """col 1 = the overnight book, 2 = the ADR book; returns as a fraction of the sleeve's capital.""" + f = _frame(rows, 11) # Date, Overnight $, ADR $, Day $, Day %, Equity $, ..., Capital $ + pnl, eq, cap = _num(f[col]).values, _num(f[5]).values, _num(f[10]).values + base = np.where(np.isfinite(eq), eq - _num(f[3]).values, cap) + return pd.DataFrame({"date": f[0], "pnl": pnl, "ret": pnl / base}).dropna() + + +def daily_by_date(rows, pnl_col: int, base: float | pd.Series, width: int) -> pd.DataFrame: + """Logs with several rows per day (foreign book passes, tracker trades): summed per date.""" + f = _frame(rows, width) + d = pd.DataFrame({"date": f[0].astype(str).str[:10], "pnl": _num(f[pnl_col]).values}).dropna() + d = d.groupby("date", as_index=False)["pnl"].sum() + d["ret"] = d["pnl"] / base + return d + + +# --- the sheet ----------------------------------------------------------------------------------- +class Sheet: + def __init__(self, sheet_id: str, creds_json: str): + from google.auth.transport.requests import AuthorizedSession + from google.oauth2 import service_account + + creds = service_account.Credentials.from_service_account_info( + json.loads(creds_json), scopes=["https://www.googleapis.com/auth/spreadsheets"]) + self.s = AuthorizedSession(creds) + self.base = f"https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}" + + def get(self, tab: str, rng: str) -> list[list]: + r = self.s.get(f"{self.base}/values/'{tab}'!{rng}", params={"valueRenderOption": "UNFORMATTED_VALUE"}, + timeout=60) + if r.status_code == 400: # the tab doesn't exist + return [] + r.raise_for_status() + return r.json().get("values", []) + + def write(self, rows: list[list], status: str) -> None: + meta = self.s.get(self.base, params={"fields": "sheets.properties.title"}, timeout=30).json() + if TAB not in [x["properties"]["title"] for x in meta.get("sheets", [])]: + self.s.post(f"{self.base}:batchUpdate", json={"requests": [{"addSheet": {"properties": {"title": TAB}}}]}, + timeout=30).raise_for_status() + history = [r for r in self.get(TAB, "A20:L5000") if r and r[0]] + self.s.post(f"{self.base}/values:batchClear", json={"ranges": [f"'{TAB}'!A1:L19"]}, + timeout=30).raise_for_status() + title = ("Weekly review of the $10,000 book - each sleeve's live record against its backtest, with a verdict " + "from a rule fixed in advance (config/review.json): no verdict before the minimum number of live " + "days; then cut when the live Sharpe is more than 2 standard errors below the backtest, halve " + "between 1 and 2. Changes go in by pull request.") + day = rows[0][0] if rows else "" + data = [{"range": f"'{TAB}'!A1", "values": [[title]]}, {"range": f"'{TAB}'!A3", "values": [[status]]}, + {"range": f"'{TAB}'!A5:K5", "values": [HEADER]}, + {"range": f"'{TAB}'!A6:K{5 + len(rows)}", "values": [r[1:] for r in rows]}, + {"range": f"'{TAB}'!A19:L19", "values": [["Week of"] + HEADER]}] + hist_rows = [] if any(str(h[0])[:10] == day for h in history) else [[day] + r[1:] for r in rows] + if hist_rows: + data.append({"range": f"'{TAB}'!A{20 + len(history)}:L{19 + len(history) + len(hist_rows)}", + "values": hist_rows}) + self.s.post(f"{self.base}/values:batchUpdate", json={"valueInputOption": "RAW", "data": data}, + timeout=30).raise_for_status() + + +def review(sheet, book: dict, cfg: dict, today: str) -> list[list]: + rule, bt = cfg["rule"], cfg["backtest_sharpe"] + series = { + "momentum_flip": daily_flip(sheet.get("Momentum flip", "A6:J5000")), + "auction_overnight": daily_auction(auction := sheet.get("Auction book", "A6:K5000"), 1), + "adr": daily_auction(auction, 2), + "foreign": daily_by_date(sheet.get("Foreign book", "A6:H5000"), 1, book.get("foreign", 1.0) or 1.0, 8), + "foreign_hft_tracker": daily_by_date(sheet.get("Foreign HFT tracker", "A6:K100000"), 10, 10_000.0, 11), + "crm_tracker": daily_by_date(sheet.get("CRM tracker", "A6:G5000"), 1, 10_000.0, 7), + } + in_book = {"momentum_flip": book.get("momentum_flip", 0) > 0, + "auction_overnight": book.get("auction", 0) > 0 and book.get("auction_overnight_weight", 1.0) > 0, + "adr": book.get("auction", 0) > 0, "foreign": book.get("foreign", 0) > 0, + "foreign_hft_tracker": True, "crm_tracker": True} + rows = [] + for name, d in series.items(): + if name.endswith("_tracker"): + d = d[d["pnl"] != 0] if name == "foreign_hft_tracker" else d # days with trades only + st = stats(d) + v, z, why = verdict(st, bt.get(name), rule, in_book[name]) + rows.append([today, name, "yes" if bt.get(name) is not None and in_book[name] else "no", st["days"], + round(st["pnl"], 2), None if not np.isfinite(st["sharpe"]) else round(st["sharpe"], 2), + bt.get(name), None if not np.isfinite(z) else round(z, 2), + None if not np.isfinite(st["hit"]) else round(st["hit"], 2), round(st["max_dd"], 2), v, why]) + return [[x if x is not None else "" for x in r] for r in rows] + + +def run(dry_run: bool = False) -> list[list]: + from .hft_shadow import book_split + + cfg = json.loads(REVIEW_FILE.read_text()) + today = f"{pd.Timestamp.now(tz='America/New_York'):%Y-%m-%d}" + sheet = Sheet(os.environ["HFT_SHEET_ID"], os.environ["GOOGLE_SERVICE_ACCOUNT_JSON"]) + rows = review(sheet, book_split(), cfg, today) + action = [f"{r[1]}: {r[10]}" for r in rows if r[10] in ("cut", "halve")] + status = (f"Reviewed {today} - " + ("; ".join(action) + " (proposed; goes in by pull request)." if action + else "no change: every sleeve in the book is 'keep' or 'too early'.")) + if not dry_run: + sheet.write(rows, status) + LOG.info("weekly review: %s", status) + for r in rows: + LOG.info(" %s", r[1:]) + return rows + + +def main(argv=None): + import argparse + + from ..utils import setup_logging + + ap = argparse.ArgumentParser() + ap.add_argument("--dry-run", action="store_true") + args = ap.parse_args(argv) + setup_logging() + run(dry_run=args.dry_run) + + +if __name__ == "__main__": + main() diff --git a/tests/test_weekly_review.py b/tests/test_weekly_review.py new file mode 100644 index 000000000..da8a7606c --- /dev/null +++ b/tests/test_weekly_review.py @@ -0,0 +1,63 @@ +"""The weekly review: live stats, the fixed verdict rule, reading the sheet logs.""" +import numpy as np +import pandas as pd + +from qtrade.intraday import weekly_review as W + +RULE = {"min_days": 40, "cut_z": -2.0, "halve_z": -1.0} + + +def _daily(rets, cap=1000.0): + r = np.asarray(rets, float) + return pd.DataFrame({"date": pd.bdate_range("2026-01-01", periods=len(r)).strftime("%Y-%m-%d"), + "pnl": r * cap, "ret": r}) + + +def test_stats(): + st = W.stats(_daily([0.01, -0.005, 0.002, -0.01])) + assert st["days"] == 4 and round(st["pnl"], 2) == -3.0 + assert st["hit"] == 0.5 and round(st["max_dd"], 2) == -13.0 + + +def test_verdict_rule(): + rng = np.random.default_rng(0) + bad = W.stats(_daily(rng.normal(-0.003, 0.01, 120))) # Sharpe around -5 over 120 days + assert W.verdict(bad, 1.2, RULE, True)[0] == "cut" + early = W.stats(_daily(rng.normal(-0.003, 0.01, 20))) + assert W.verdict(early, 1.2, RULE, True)[0] == "too early" + ok = W.stats(_daily(rng.normal(0.0008, 0.01, 120))) # Sharpe around 1.3 + assert W.verdict(ok, 1.2, RULE, True)[0] == "keep" + assert W.verdict(ok, 1.2, RULE, False)[0] == "off" + assert W.verdict(ok, None, RULE, True)[0] == "info" + + +class FakeSheet: + def __init__(self, tabs): + self.tabs = tabs + + def get(self, tab, rng): + return self.tabs.get(tab, []) + + +def test_review_reads_the_logs(): + tabs = { + "Momentum flip": [["2026-11-19", 24.5, "SHORT", 1, 1, 1, 2.27, 0.0709, 3210.1, 1], + ["2026-11-20", 28.4, "SHORT", 1, 1, 1, 3.23, 0.1005, 3213.33, 1]], + "Auction book": [["2026-11-19", -4.35, 23.78, 19.43, 0.6, 3100.0, 1, 1, 1, 9, 3242.09], + ["2026-11-20", 17.43, 34.97, 52.4, 1.7, 3152.4, 1, 1, 1, 9, 3242.09]], + "Foreign book": [["2026-11-20", 2.97, 0.09, 3244.25, "UK", 60, 1, 3242.09], + ["2026-11-20", 2.2, 0.07, 3246.45, "HK", 34, 1, 3242.09]], + "Foreign HFT tracker": [["2026-11-20", "Japan", "m", "9", "10", "a", "b", 1, 4, -3, -0.5], + ["2026-11-20", "Korea", "m", "9", "10", "a", "b", 1, 4, -3, -1.5]], + "CRM tracker": [["2026-11-20", 0, 0, 10000, 9, "yes"], ["2026-11-23", -110.32, -1.1, 9889.68, 9, "no"]], + } + book = {"momentum_flip": 3242.09, "auction": 3242.09, "foreign": 3242.09, "auction_overnight_weight": 0.0} + cfg = {"rule": RULE, "backtest_sharpe": {"momentum_flip": 0.33, "auction_overnight": 1.2, "adr": 2.91, + "foreign": 1.5, "foreign_hft_tracker": None, "crm_tracker": None}} + rows = {r[1]: r for r in W.review(FakeSheet(tabs), book, cfg, "2026-11-28")} + assert rows["momentum_flip"][3] == 2 and rows["momentum_flip"][4] == 5.5 + assert rows["auction_overnight"][10] == "off" and rows["auction_overnight"][4] == 13.08 + assert rows["adr"][4] == 58.75 and rows["adr"][10] == "too early" + assert rows["foreign"][3] == 1 and rows["foreign"][4] == 5.17 + assert rows["foreign_hft_tracker"][4] == -2.0 and rows["foreign_hft_tracker"][10] == "info" + assert rows["crm_tracker"][3] == 2 and rows["crm_tracker"][2] == "no"