suretick 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. suretick/__init__.py +3 -0
  2. suretick/analyze.py +128 -0
  3. suretick/cli.py +117 -0
  4. suretick/conformal.py +101 -0
  5. suretick/data/__init__.py +0 -0
  6. suretick/data/binance.py +80 -0
  7. suretick/data/synthetic.py +157 -0
  8. suretick/demo.py +186 -0
  9. suretick/experiment.py +103 -0
  10. suretick/features.py +127 -0
  11. suretick/live.py +713 -0
  12. suretick/live_models/btcusdt.json.gz +0 -0
  13. suretick/live_models/ethusdt.json.gz +0 -0
  14. suretick/live_models/solusdt.json.gz +0 -0
  15. suretick/metrics.py +148 -0
  16. suretick/models.py +153 -0
  17. suretick/monitors.py +309 -0
  18. suretick/online.py +63 -0
  19. suretick/plots.py +156 -0
  20. suretick/realdata.py +60 -0
  21. suretick/report.py +77 -0
  22. suretick/screen.py +33 -0
  23. suretick/server.py +248 -0
  24. suretick/stream.py +461 -0
  25. suretick/web/app.js +585 -0
  26. suretick/web/data/both_seed0.json +1 -0
  27. suretick/web/data/concept_only_seed0.json +1 -0
  28. suretick/web/data/covariate_only_seed0.json +1 -0
  29. suretick/web/data/index.json +32 -0
  30. suretick/web/data/null_seed0.json +1 -0
  31. suretick/web/data/real_20261202-2300-a-calm-stretch-2-dec-23-00-utc.json +1 -0
  32. suretick/web/data/real_index.json +8 -0
  33. suretick/web/data/recurring_seed0.json +1 -0
  34. suretick/web/index.html +194 -0
  35. suretick/web/social.png +0 -0
  36. suretick/web/style.css +175 -0
  37. suretick-0.3.0.dist-info/METADATA +295 -0
  38. suretick-0.3.0.dist-info/RECORD +42 -0
  39. suretick-0.3.0.dist-info/WHEEL +5 -0
  40. suretick-0.3.0.dist-info/entry_points.txt +2 -0
  41. suretick-0.3.0.dist-info/licenses/LICENSE +21 -0
  42. suretick-0.3.0.dist-info/top_level.txt +1 -0
suretick/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Calibrated, shift-aware limit order book forecasting."""
2
+
3
+ __version__ = "0.3.0"
suretick/analyze.py ADDED
@@ -0,0 +1,128 @@
1
+ """Analyse your own order book: read a CSV, run the four policies, return the app's JSON.
2
+
3
+ CSV format (one row per snapshot, evenly spaced in time, oldest first):
4
+
5
+ ts,bid_px_1,bid_sz_1,ask_px_1,ask_sz_1,bid_px_2,bid_sz_2,ask_px_2,ask_sz_2,...
6
+
7
+ * ``bid_px_i, bid_sz_i, ask_px_i, ask_sz_i`` for levels i = 1..L (L >= 1, best level first).
8
+ * Optional time column: ``ts`` (seconds, any origin) or ``time`` (a date-time). It is
9
+ only used to work out the spacing between rows; otherwise ``step_seconds`` is used.
10
+
11
+ The first 30% of rows train the model (at most 20,000), the next 10% calibrate it (at
12
+ most 6,000), and every policy is replayed over the rest. We do not know when your market
13
+ changed, so there are no shift markers; alarms and reactions show what each policy saw.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import io
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import pandas as pd
23
+
24
+ MIN_ROWS = 12_000
25
+ MAX_ROWS = 500_000
26
+ MAX_BYTES = 150 * 2**20
27
+
28
+
29
+ class BookError(ValueError):
30
+ """The uploaded data cannot be analysed; the message says why, in plain words."""
31
+
32
+
33
+ def read_book_csv(source: bytes | str | Path) -> tuple[pd.DataFrame, float | None]:
34
+ """Parse and check a CSV order book. Returns (book, seconds between rows or None)."""
35
+ if isinstance(source, bytes):
36
+ if len(source) > MAX_BYTES:
37
+ raise BookError(f"the file is larger than {MAX_BYTES // 2**20} MB")
38
+ source = io.BytesIO(source)
39
+ try:
40
+ raw = pd.read_csv(source, nrows=MAX_ROWS + 1)
41
+ except (pd.errors.ParserError, UnicodeDecodeError, ValueError) as e:
42
+ raise BookError(f"could not read the CSV ({e})") from None
43
+ raw.columns = [str(c).strip().lower() for c in raw.columns]
44
+ levels = 0
45
+ while all(f"{side}_{k}_{levels + 1}" in raw.columns for side in ("bid", "ask") for k in ("px", "sz")):
46
+ levels += 1
47
+ if levels == 0:
48
+ raise BookError("missing columns: need at least bid_px_1, bid_sz_1, ask_px_1, ask_sz_1")
49
+ if len(raw) > MAX_ROWS:
50
+ raise BookError(f"too many rows: the limit is {MAX_ROWS:,}")
51
+ cols = [f"{side}_{k}_{i}" for i in range(1, levels + 1) for side in ("bid", "ask") for k in ("px", "sz")]
52
+ book = raw[cols].apply(pd.to_numeric, errors="coerce")
53
+ ok = book.notna().all(axis=1) & (book["ask_px_1"] > book["bid_px_1"])
54
+ ok &= (book[[c for c in cols if "_sz_" in c]] > 0).all(axis=1)
55
+ if ok.mean() < 0.99:
56
+ raise BookError(
57
+ f"{(~ok).sum():,} rows are empty, non-numeric, crossed (ask <= bid) or have zero size; "
58
+ "clean them first"
59
+ )
60
+ keep = ok.to_numpy()
61
+ book = book[keep].reset_index(drop=True)
62
+ if len(book) < MIN_ROWS:
63
+ raise BookError(
64
+ f"too few rows: {len(book):,} (need at least {MIN_ROWS:,}, e.g. 20 minutes at 100 ms)"
65
+ )
66
+ return book, _step_seconds(raw[keep])
67
+
68
+
69
+ def _step_seconds(raw: pd.DataFrame) -> float | None:
70
+ if "ts" in raw.columns:
71
+ t = pd.to_numeric(raw["ts"], errors="coerce").to_numpy(dtype=float)
72
+ elif "time" in raw.columns:
73
+ t = pd.to_datetime(raw["time"], errors="coerce", utc=True).astype("int64").to_numpy() / 1e9
74
+ else:
75
+ return None
76
+ d = np.diff(t[np.isfinite(t)])
77
+ d = d[d > 0]
78
+ return float(np.median(d)) if len(d) else None
79
+
80
+
81
+ def analyze_book(book: pd.DataFrame, step_seconds: float = 0.1, title: str = "Your order book") -> dict:
82
+ """Run the four policies on ``book`` and package the result for the app."""
83
+ from .demo import payload_from_prepared
84
+ from .experiment import prepare
85
+ from .features import infer_tick
86
+ from .stream import StreamConfig
87
+
88
+ if not 0 < step_seconds <= 3600:
89
+ raise BookError("the spacing between rows must be between 0 and 3600 seconds")
90
+ cfg = StreamConfig()
91
+ n = len(book)
92
+ n_train = int(np.clip(0.3 * n, 3000, 20_000))
93
+ n_cal = int(np.clip(0.1 * n, 1000, 6_000))
94
+ try:
95
+ tick = infer_tick(book)
96
+ except ValueError as e:
97
+ raise BookError(str(e)) from None
98
+ spread = (book["ask_px_1"] - book["bid_px_1"]).iloc[:n_train] / tick
99
+ # A book whose spread is almost always one tick (e.g. BTCUSDT) needs balanced classes;
100
+ # half a spread would make nearly every move "up" or "down".
101
+ rule = "balanced" if float(np.median(spread)) <= 1.5 else "spread"
102
+ P = prepare(book, cfg, n_train, n_cal, step_seconds=step_seconds, theta_rule=rule)
103
+ if len(P.y) - cfg.h - P.start < cfg.refit_delay:
104
+ raise BookError("not enough rows after training and calibration to replay the policies")
105
+ if len(np.unique(P.y[P.train])) < 3:
106
+ raise BookError("the price never moves both up and down in the training rows")
107
+ horizon = cfg.h * step_seconds
108
+ story = (
109
+ f"{n:,} snapshots, {book.columns.str.startswith('bid_px_').sum()} levels, "
110
+ f"{step_seconds:g} s apart. Trained on the first {n_train:,} rows, calibrated on the next "
111
+ f"{n_cal:,}, then replayed. Forecast: the mid price {horizon:g} s ahead "
112
+ f"(dead-band {P.theta:.2f} ticks)."
113
+ )
114
+ return payload_from_prepared(P, title, story, {"scenario": "upload"})
115
+
116
+
117
+ def analyze_csv(source: bytes | str | Path, step_seconds: float | None = None) -> dict:
118
+ """Read and analyse a CSV. ``step_seconds`` overrides the spacing found in the file."""
119
+ book, found = read_book_csv(source)
120
+ return analyze_book(book, step_seconds or found or 0.1)
121
+
122
+
123
+ def sample_csv() -> str:
124
+ """An example CSV (simulated: a harmless shift, then a harmful one) to try the upload."""
125
+ from .data.synthetic import generate, make_scenario
126
+
127
+ book = generate(make_scenario("both"), seed=7).drop(columns=["regime"])
128
+ return book.to_csv(index=False, float_format="%.6g")
suretick/cli.py ADDED
@@ -0,0 +1,117 @@
1
+ """Command line.
2
+
3
+ suretick serve open the app (simulations, real market, live, your data)
4
+ suretick live --symbol btcusdt open the app on the live page for one market
5
+ suretick analyze book.csv analyse your own order book in the terminal
6
+ suretick sample-data book.csv write an example order book CSV
7
+ suretick build-demo regenerate the simulation data shipped with the app
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from . import __version__
18
+
19
+
20
+ def _add_server_options(p: argparse.ArgumentParser) -> None:
21
+ p.add_argument("--host", default="127.0.0.1", help="default 127.0.0.1 (this computer only)")
22
+ p.add_argument("--port", type=int, default=8000)
23
+ p.add_argument("--no-browser", action="store_true", help="do not open a browser tab")
24
+
25
+
26
+ def _print_scoreboard(payload: dict) -> None:
27
+ rows = [
28
+ ("Coverage (promise 90%)", "all.coverage", "{:.1%}"),
29
+ ("Accuracy of the top guess", "all.accuracy", "{:.1%}"),
30
+ ("Accuracy when it commits", "all.nonabstained_accuracy", "{:.1%}"),
31
+ ("Says 'not sure'", "all.abstention", "{:.1%}"),
32
+ ("Market-maker value (ticks/step)", "all.value", "{:+.3f}"),
33
+ ("Retrains", "refits", "{:.0f}"),
34
+ ("Switches to a stored model", "head_switches", "{:.0f}"),
35
+ ]
36
+ pols = payload["policies"]
37
+ names = list(pols)
38
+ print(payload["story"], "\n")
39
+ print(f"{'':34s}" + "".join(f"{n:>16s}" for n in names))
40
+ for label, key, fmt in rows:
41
+ cells = []
42
+ for n in names:
43
+ v = pols[n]["summary"].get(key)
44
+ cells.append(f"{(fmt.format(v) if v is not None else 'n/a'):>16s}")
45
+ print(f"{label:34s}" + "".join(cells))
46
+ print("\nregime_bank and shift_aware are ours; ks_retrain and static are baselines.")
47
+
48
+
49
+ def main(argv: list[str] | None = None) -> int:
50
+ ap = argparse.ArgumentParser(
51
+ prog="suretick",
52
+ description="Calibrated order book forecasting under regime shifts.",
53
+ )
54
+ ap.add_argument("--version", action="version", version=f"suretick {__version__}")
55
+ sub = ap.add_subparsers(dest="cmd")
56
+ _add_server_options(sub.add_parser("serve", help="start the app on localhost (default command)"))
57
+ lv = sub.add_parser("live", help="start the app on the live page (streams public Binance data)")
58
+ lv.add_argument("--symbol", default="btcusdt")
59
+ _add_server_options(lv)
60
+ an = sub.add_parser("analyze", help="analyse an order book CSV (see `suretick sample-data`)")
61
+ an.add_argument("csv", type=Path)
62
+ an.add_argument("--step", type=float, default=None, help="seconds between rows (default: from the file)")
63
+ an.add_argument("--out", type=Path, default=None, help="also save the full result as JSON")
64
+ sd = sub.add_parser("sample-data", help="write an example order book CSV")
65
+ sd.add_argument("out", type=Path, nargs="?", default=Path("suretick-sample-book.csv"))
66
+ b = sub.add_parser("build-demo", help="regenerate the simulation data shipped with the app")
67
+ b.add_argument("--seed", type=int, default=0)
68
+ b.add_argument("--jobs", type=int, default=5, help="parallel processes")
69
+ args = ap.parse_args(argv)
70
+
71
+ if args.cmd == "build-demo":
72
+ from .demo import build_demo
73
+
74
+ for path in build_demo(seed=args.seed, jobs=args.jobs):
75
+ print("wrote", path)
76
+ return 0
77
+ if args.cmd == "sample-data":
78
+ from .analyze import sample_csv
79
+
80
+ args.out.write_text(sample_csv())
81
+ print(f"wrote {args.out} (simulated: a harmless shift, then a harmful one)")
82
+ return 0
83
+ if args.cmd == "analyze":
84
+ from .analyze import BookError, analyze_csv
85
+
86
+ print("Analysing (about a minute for 30,000 rows)...", flush=True)
87
+ try:
88
+ payload = analyze_csv(args.csv, args.step)
89
+ except (BookError, FileNotFoundError) as e:
90
+ print(f"error: {e}", file=sys.stderr)
91
+ return 2
92
+ _print_scoreboard(payload)
93
+ if args.out:
94
+ args.out.write_text(json.dumps(payload))
95
+ print(f"full result: {args.out}")
96
+ return 0
97
+ from .server import serve
98
+
99
+ page = ""
100
+ if args.cmd == "live":
101
+ from .live import SYMBOLS
102
+
103
+ if args.symbol.lower() not in SYMBOLS:
104
+ print(f"error: --symbol must be one of {', '.join(SYMBOLS)}", file=sys.stderr)
105
+ return 2
106
+ page = f"#live/{args.symbol.lower()}"
107
+ serve(
108
+ host=getattr(args, "host", "127.0.0.1"),
109
+ port=getattr(args, "port", 8000),
110
+ open_browser=not getattr(args, "no_browser", False),
111
+ page=page,
112
+ )
113
+ return 0
114
+
115
+
116
+ if __name__ == "__main__":
117
+ sys.exit(main())
suretick/conformal.py ADDED
@@ -0,0 +1,101 @@
1
+ """Conformal prediction sets: split, weighted (covariate shift) and adaptive (ACI).
2
+
3
+ Score: s(x, y) = 1 - p_hat(y | x). A class y enters the prediction set when
4
+ s(x, y) <= q_hat, i.e. when p_hat(y | x) >= 1 - q_hat.
5
+
6
+ * Split conformal: q_hat is the ceil((n + 1)(1 - alpha))-th smallest calibration score.
7
+ With exchangeable data the set contains the truth with probability >= 1 - alpha.
8
+ * Weighted conformal (Tibshirani, Barber, Candes & Ramdas 2019): under covariate shift,
9
+ each calibration score gets weight w(x_i) = p_now(x_i) / p_cal(x_i) and the test point
10
+ gets w(x). Same formula, weighted counts.
11
+ * ACI (Gibbs & Candes 2021): the alpha used for q_hat moves after each matured label,
12
+ alpha_{t+1} = alpha_t + gamma * (alpha - err_t). Misses shrink alpha (bigger sets),
13
+ hits grow it. Long-run miss rate -> alpha even if the data shift.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import numpy as np
19
+ from sklearn.linear_model import LogisticRegression
20
+ from sklearn.pipeline import make_pipeline
21
+ from sklearn.preprocessing import StandardScaler
22
+
23
+
24
+ def lac_scores(probs: np.ndarray, y: np.ndarray) -> np.ndarray:
25
+ """Nonconformity of the true label: 1 - predicted probability of what happened."""
26
+ return 1.0 - probs[np.arange(len(y)), y]
27
+
28
+
29
+ def prediction_sets(probs: np.ndarray, q_hat: float | np.ndarray) -> np.ndarray:
30
+ """Boolean (n, 3) array: class c is in the set iff 1 - p_c <= q_hat."""
31
+ q = np.asarray(q_hat, dtype=float)
32
+ if q.ndim:
33
+ q = q[:, None]
34
+ return (1.0 - probs) <= q
35
+
36
+
37
+ class Calibrator:
38
+ """Holds calibration scores (optionally weighted) and returns q_hat for any alpha."""
39
+
40
+ def __init__(self, scores: np.ndarray, weights: np.ndarray | None = None):
41
+ scores = np.asarray(scores, dtype=float)
42
+ order = np.argsort(scores, kind="stable")
43
+ self.sorted_scores = scores[order]
44
+ w = np.ones(len(scores)) if weights is None else np.asarray(weights, dtype=float)[order]
45
+ self.cum_w = np.cumsum(w)
46
+ self.total_w = float(self.cum_w[-1]) if len(w) else 0.0
47
+ self.ess = float(w.sum() ** 2 / np.sum(w**2)) if len(w) else 0.0
48
+
49
+ def __len__(self) -> int:
50
+ return len(self.sorted_scores)
51
+
52
+ def q_hat(self, alpha: float, w_test: float = 1.0) -> float:
53
+ """Smallest score s with weighted share >= 1 - alpha, with the test point's
54
+ weight placed at +infinity. Returns +inf (full set) or -inf (empty set) at the
55
+ edges, which is what keeps ACI's guarantee valid."""
56
+ if alpha <= 0.0 or len(self) == 0:
57
+ return np.inf
58
+ if alpha >= 1.0:
59
+ return -np.inf
60
+ target = (1.0 - alpha) * (self.total_w + w_test)
61
+ j = int(np.searchsorted(self.cum_w, target - 1e-9, side="left"))
62
+ return np.inf if j >= len(self) else float(self.sorted_scores[j])
63
+
64
+
65
+ class DensityRatio:
66
+ """w(x) = p_now(x) / p_cal(x), estimated with a domain classifier (logistic regression).
67
+
68
+ The classifier learns to tell calibration rows (label 0) from recent rows (label 1);
69
+ its odds, corrected for the two sample sizes, estimate the density ratio. Weights are
70
+ clipped to [lo, hi] so one odd row cannot dominate.
71
+ """
72
+
73
+ def __init__(self, lo: float = 0.05, hi: float = 20.0):
74
+ self.lo, self.hi = lo, hi
75
+
76
+ def fit(self, X_cal: np.ndarray, X_now: np.ndarray) -> DensityRatio:
77
+ X = np.vstack([X_cal, X_now])
78
+ z = np.r_[np.zeros(len(X_cal)), np.ones(len(X_now))]
79
+ self.clf_ = make_pipeline(StandardScaler(), LogisticRegression(max_iter=500))
80
+ self.clf_.fit(X, z)
81
+ self.prior_ = len(X_cal) / len(X_now)
82
+ return self
83
+
84
+ def __call__(self, X: np.ndarray) -> np.ndarray:
85
+ p = np.clip(self.clf_.predict_proba(X)[:, 1], 1e-6, 1 - 1e-6)
86
+ return np.clip(p / (1 - p) * self.prior_, self.lo, self.hi)
87
+
88
+
89
+ class ACI:
90
+ """Adaptive conformal inference: one running alpha_t, updated on matured labels."""
91
+
92
+ def __init__(self, alpha: float = 0.1, gamma: float = 0.005):
93
+ self.alpha, self.gamma = alpha, gamma
94
+ self.alpha_t = alpha
95
+
96
+ def update(self, miss: bool) -> float:
97
+ self.alpha_t += self.gamma * (self.alpha - float(miss))
98
+ return self.alpha_t
99
+
100
+ def reset(self) -> None:
101
+ self.alpha_t = self.alpha
File without changes
@@ -0,0 +1,80 @@
1
+ """Load recordings from ``scripts/collect_binance.py`` into the common book format.
2
+
3
+ Output rows are on a regular 100 ms grid (the last snapshot seen at each grid time), so
4
+ "h steps" always means the same wall-clock horizon. Grid points after a feed gap longer
5
+ than ``max_gap_s`` are marked ``gap = True``; evaluation drops windows that touch them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import gzip
11
+ import json
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+
17
+ STEP_MS = 100
18
+
19
+
20
+ def _read_files(paths: list[Path], levels: int) -> pd.DataFrame:
21
+ rows = []
22
+ for p in paths:
23
+ lines = []
24
+ with gzip.open(p, "rt") as f:
25
+ try:
26
+ for line in f:
27
+ lines.append(line)
28
+ except (EOFError, gzip.BadGzipFile): # still being written, or cut by a crash
29
+ pass
30
+ for line in lines:
31
+ try:
32
+ d = json.loads(line)
33
+ except json.JSONDecodeError: # last line cut by a crash or a live writer
34
+ continue
35
+ if len(d["b"]) < levels or len(d["a"]) < levels:
36
+ continue
37
+ rows.append(
38
+ [d["r"], d["u"]]
39
+ + [float(x) for lv in d["b"][:levels] for x in lv]
40
+ + [float(x) for lv in d["a"][:levels] for x in lv]
41
+ )
42
+ cols = ["r", "u"]
43
+ cols += [f"bid_{k}_{i}" for i in range(1, levels + 1) for k in ("px", "sz")]
44
+ cols += [f"ask_{k}_{i}" for i in range(1, levels + 1) for k in ("px", "sz")]
45
+ return pd.DataFrame(rows, columns=cols)
46
+
47
+
48
+ def load_book(
49
+ root: Path,
50
+ symbol: str,
51
+ start: pd.Timestamp,
52
+ end: pd.Timestamp,
53
+ levels: int = 5,
54
+ max_gap_s: float = 2.0,
55
+ ) -> pd.DataFrame:
56
+ """Merge every collector under ``root`` for one symbol and time range (UTC)."""
57
+ start, end = (pd.Timestamp(t) for t in (start, end))
58
+ start = start.tz_localize("UTC") if start.tzinfo is None else start.tz_convert("UTC")
59
+ end = end.tz_localize("UTC") if end.tzinfo is None else end.tz_convert("UTC")
60
+ hours = pd.date_range(start.floor("h"), end, freq="h")
61
+ names = {f"{h:%Y%m%d_%H}" for h in hours}
62
+ paths = sorted(p for p in Path(root).glob(f"*/{symbol}/*.jsonl.gz") if p.name[:11] in names)
63
+ if not paths:
64
+ raise FileNotFoundError(f"no recordings for {symbol} in {root} between {start} and {end}")
65
+ raw = _read_files(paths, levels)
66
+ if raw.empty:
67
+ raise FileNotFoundError(f"recordings for {symbol} contain no complete snapshots yet")
68
+ # Two collectors see the same updates: keep the earliest arrival of each update id.
69
+ raw = raw.sort_values("r", kind="stable").drop_duplicates("u", keep="first")
70
+ t0, t1 = int(start.value // 1_000_000), int(end.value // 1_000_000)
71
+ grid = np.arange(t0, t1, STEP_MS)
72
+ pos = np.searchsorted(raw["r"].to_numpy(), grid, side="right") - 1
73
+ ok = pos >= 0
74
+ book = raw.iloc[np.clip(pos, 0, None)].reset_index(drop=True)
75
+ age = grid - book["r"].to_numpy()
76
+ out = book.drop(columns=["r", "u"])
77
+ out.insert(0, "ts", (grid - t0) / 1000.0)
78
+ out["time"] = pd.to_datetime(grid, unit="ms", utc=True)
79
+ out["gap"] = ~ok | (age > max_gap_s * 1000)
80
+ return out
@@ -0,0 +1,157 @@
1
+ """Synthetic limit order book (LOB) stream with regime shifts injected at known steps.
2
+
3
+ Why synthetic data: public LOB data carries no labels saying *when* the market changed,
4
+ so detection delay cannot be measured on it. Here we choose the shift times ourselves.
5
+
6
+ The generator is deliberately simple and its rules are explicit:
7
+
8
+ * A hidden "buy pressure" ``f`` follows an AR(1) process (it is autocorrelated, like real
9
+ order flow). ``tanh(f)`` in (-1, 1) is the true book imbalance.
10
+ * Queue sizes on each side reflect that imbalance, times random noise, times ``depth_scale``.
11
+ * The fair price moves by ``impact * a * tanh(f) + noise`` ticks per step.
12
+ * The quoted best bid/ask sit on a tick grid around the fair price, ``spread`` ticks apart.
13
+
14
+ Regime types (what each shift changes):
15
+
16
+ * ``covariate``: depth and spread change, so P(x) moves, but the price rule is untouched,
17
+ so P(y | x) is (nearly) the same. A good monitor should *not* force a refit here.
18
+ * ``concept``: ``impact`` flips sign (imbalance becomes contrarian, as with spoofing),
19
+ so P(y | x) breaks. This is the harmful shift that must trigger a refit.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from dataclasses import dataclass
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ STEP_SECONDS = 0.1 # one snapshot every 100 ms, like a 100 ms exchange depth stream
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Regime:
34
+ """Parameters that a shift is allowed to change."""
35
+
36
+ name: str = "calm"
37
+ depth_scale: float = 1.0 # multiplies every queue size
38
+ spread_extra: float = 0.3 # spread = 1 + Poisson(spread_extra) ticks
39
+ impact: float = 1.0 # sign and strength of imbalance -> price
40
+
41
+
42
+ CALM = Regime()
43
+ # Thin, wide book (e.g. around a news release); the price rule is unchanged.
44
+ COVARIATE = Regime("covariate", depth_scale=0.35, spread_extra=1.5, impact=1.0)
45
+ # Same thin book, but imbalance now predicts the opposite move.
46
+ CONCEPT = Regime("concept", depth_scale=0.35, spread_extra=1.5, impact=-0.7)
47
+ CONCEPT_FROM_CALM = Regime("concept", impact=-0.7)
48
+ # The market goes back to normal: same parameters as CALM, but named so it counts as a shift.
49
+ RETURN_TO_CALM = Regime("return")
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Scenario:
54
+ """A stream: ``segments`` is a list of (start_step, regime), first start must be 0."""
55
+
56
+ name: str
57
+ n_steps: int
58
+ segments: tuple[tuple[int, Regime], ...]
59
+
60
+ def shifts(self) -> list[tuple[int, str]]:
61
+ """Ground truth: (step, label) for every change after the start. A repeated regime
62
+ name gets a number (concept, concept2) so every shift has a unique label."""
63
+ seen: dict[str, int] = {}
64
+ out = []
65
+ for s, r in self.segments[1:]:
66
+ seen[r.name] = seen.get(r.name, 0) + 1
67
+ out.append((s, r.name if seen[r.name] == 1 else f"{r.name}{seen[r.name]}"))
68
+ return out
69
+
70
+
71
+ def make_scenario(kind: str, n_steps: int | None = None) -> Scenario:
72
+ """Named scenarios used in the benchmark. Train/calibrate on the first 8000 steps.
73
+ ``recurring``: the harmful regime comes, goes, and comes back (needs a longer stream)."""
74
+ cov_at, con_at = 12_000, 18_000
75
+ n_steps = n_steps or (34_000 if kind == "recurring" else 26_000)
76
+ table = {
77
+ "null": ((0, CALM),),
78
+ "covariate_only": ((0, CALM), (cov_at, COVARIATE)),
79
+ "concept_only": ((0, CALM), (cov_at, CONCEPT_FROM_CALM)),
80
+ "both": ((0, CALM), (cov_at, COVARIATE), (con_at, CONCEPT)),
81
+ "recurring": (
82
+ (0, CALM),
83
+ (12_000, CONCEPT_FROM_CALM),
84
+ (20_000, RETURN_TO_CALM),
85
+ (25_000, CONCEPT_FROM_CALM),
86
+ ),
87
+ }
88
+ if kind not in table:
89
+ raise ValueError(f"unknown scenario {kind!r}; choose from {sorted(table)}")
90
+ return Scenario(kind, n_steps, table[kind])
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class GeneratorParams:
95
+ n_levels: int = 5
96
+ tick: float = 0.01
97
+ start_price: float = 100.0
98
+ phi: float = 0.97 # AR(1) persistence of hidden pressure
99
+ sigma_f: float = 0.2 # AR(1) innovation size
100
+ drift_ticks: float = 0.3 # price drift per step at full imbalance
101
+ noise_ticks: float = 0.5 # random price noise per step
102
+ base_size: float = 50.0 # mean level-1 queue size
103
+ size_noise: float = 0.25 # log-normal noise on sizes
104
+
105
+
106
+ def generate(scenario: Scenario, seed: int, params: GeneratorParams | None = None) -> pd.DataFrame:
107
+ """Simulate the stream. Returns one row per step with book levels and ground truth.
108
+
109
+ Columns: ``ts`` (seconds), ``regime``, ``bid_px_i``, ``bid_sz_i``, ``ask_px_i``,
110
+ ``ask_sz_i`` for i = 1..n_levels.
111
+ """
112
+ p = params or GeneratorParams()
113
+ rng = np.random.default_rng(seed)
114
+ n, L = scenario.n_steps, p.n_levels
115
+
116
+ # Per-step regime parameters as arrays.
117
+ starts = [s for s, _ in scenario.segments]
118
+ if starts[0] != 0 or starts != sorted(starts):
119
+ raise ValueError("segments must start at 0 and be sorted")
120
+ seg_idx = np.searchsorted(starts, np.arange(n), side="right") - 1
121
+ regimes = [r for _, r in scenario.segments]
122
+ depth = np.array([r.depth_scale for r in regimes])[seg_idx]
123
+ spread_extra = np.array([r.spread_extra for r in regimes])[seg_idx]
124
+ impact = np.array([r.impact for r in regimes])[seg_idx]
125
+ names = np.array([r.name for r in regimes], dtype=object)[seg_idx]
126
+
127
+ # Hidden pressure (AR(1)) and true imbalance.
128
+ eps = rng.normal(0.0, p.sigma_f, n)
129
+ f = np.empty(n)
130
+ f[0] = eps[0] / np.sqrt(1 - p.phi**2)
131
+ for t in range(1, n):
132
+ f[t] = p.phi * f[t - 1] + eps[t]
133
+ imb = np.tanh(f)
134
+
135
+ # Fair price in ticks: moves with today's imbalance times the regime's impact.
136
+ steps = impact * p.drift_ticks * imb + rng.normal(0.0, p.noise_ticks, n)
137
+ fair = p.start_price / p.tick + np.concatenate([[0.0], np.cumsum(steps[:-1])])
138
+
139
+ spread = 1 + rng.poisson(spread_extra) # integer ticks
140
+ best_bid = np.floor(fair - spread / 2.0)
141
+ best_ask = best_bid + spread
142
+
143
+ out = {"ts": np.arange(n) * STEP_SECONDS, "regime": names}
144
+ lvl = np.arange(L)
145
+ size_shape = 1.0 + 0.3 * lvl # deeper levels hold more volume
146
+ # Imbalance shows up strongly at level 1 and fades with depth.
147
+ tilt = np.outer(imb, 1.0 / (1.0 + lvl))
148
+ noise_b = rng.lognormal(0.0, p.size_noise, (n, L))
149
+ noise_a = rng.lognormal(0.0, p.size_noise, (n, L))
150
+ bid_sz = p.base_size * depth[:, None] * size_shape * (1 + tilt) * noise_b
151
+ ask_sz = p.base_size * depth[:, None] * size_shape * (1 - tilt) * noise_a
152
+ for i in range(L):
153
+ out[f"bid_px_{i + 1}"] = (best_bid - i) * p.tick
154
+ out[f"ask_px_{i + 1}"] = (best_ask + i) * p.tick
155
+ out[f"bid_sz_{i + 1}"] = np.maximum(bid_sz[:, i], 1.0).round()
156
+ out[f"ask_sz_{i + 1}"] = np.maximum(ask_sz[:, i], 1.0).round()
157
+ return pd.DataFrame(out)