-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_multiday.py
More file actions
708 lines (591 loc) · 28.1 KB
/
Copy pathrun_multiday.py
File metadata and controls
708 lines (591 loc) · 28.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
#!/usr/bin/env python3
"""
Multi-day backtest. Runs all scheduler+tactic combos across days.
In-sample (same-day) or out-of-sample (calibrate D, execute D+1).
Usage:
python run_multiday.py --mode oos --total-qty 20.0
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from hftbacktest import (
BacktestAsset,
ROIVectorMarketDepthBacktest,
BUY_EVENT,
SELL_EVENT,
)
from strategies.schedulers import almgren_chriss_schedule, twap_schedule
from strategies.execution import (
FILL_DTYPE,
exec_market_order,
exec_glft_liquidation,
exec_peg_best,
)
from strategies.liquidation_ode import build_delta_grid
from strategies.calibration import calibrate_from_data, calibrate_gamma
# ── Configuration ──────────────────────────────────────────────────────────
HORIZON_SEC = 3600
N_SLICES = 60
LOT_SIZE = 0.001
MAX_FILLS = 10_000
# ── Plot style ─────────────────────────────────────────────────────────────
plt.rcParams.update({
"font.family": "serif",
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 8.5,
"ytick.labelsize": 8.5,
"legend.fontsize": 8.5,
"figure.dpi": 200,
"savefig.dpi": 300,
"savefig.bbox": "tight",
"savefig.pad_inches": 0.06,
"axes.linewidth": 0.6,
"xtick.major.width": 0.5,
"ytick.major.width": 0.5,
"lines.linewidth": 1.2,
"grid.linewidth": 0.3,
"grid.alpha": 0.4,
"axes.grid": False,
})
COLORS = {
"AC+MktOrder": "#2563eb",
"AC+GLFT": "#059669",
"AC+PegBest": "#d97706",
"TWAP+MktOrder": "#dc2626",
"TWAP+GLFT": "#7c3aed",
}
_LEGEND_KW = dict(frameon=True, fancybox=False, edgecolor="#d1d5db", framealpha=0.95)
def _color(s):
return COLORS.get(s, "#6b7280")
# ── Data discovery ─────────────────────────────────────────────────────────
def discover_dates(data_dir: Path) -> list[tuple[str, str]]:
results = []
pattern = re.compile(r"(\d{8})")
for f in sorted(data_dir.glob("*.npz")):
name_lower = f.name.lower()
if any(x in name_lower for x in ["eod", "sod", "snapshot", "last"]):
continue
m = pattern.search(f.name)
if m:
results.append((m.group(1), str(f)))
return results
def get_mid_from_data(data_path: str) -> float:
data = np.load(data_path)["data"]
bids = data[(data["ev"] & BUY_EVENT) == BUY_EVENT]["px"]
asks = data[(data["ev"] & SELL_EVENT) == SELL_EVENT]["px"]
bid_sample = bids[:min(1000, len(bids))]
ask_sample = asks[:min(1000, len(asks))]
if len(bid_sample) == 0 or len(ask_sample) == 0:
return 0.0
return (np.max(bid_sample) + np.min(ask_sample)) / 2.0
def detect_tick_size(mid_price: float) -> float:
if mid_price > 20_000:
return 0.10
return 0.01
def find_snapshot(date_str: str, data_dir: Path) -> str | None:
candidates = [
data_dir / f"btcusdt_{date_str}_eod.npz",
data_dir / f"BTCUSDT_{date_str}_eod.npz",
data_dir / f"{date_str}_eod.npz",
data_dir / f"btcusdt_{date_str}_last.npz",
]
for c in candidates:
if c.exists():
return str(c)
return None
# ══════════════════════════════════════════════════════════════════════════
# Calibration-only pass (no execution)
# ══════════════════════════════════════════════════════════════════════════
def calibrate_day(
date_str: str,
data_file: str,
data_dir: Path,
total_qty: float,
) -> dict | None:
"""Calibrate on one day's data. Returns param dict, no execution."""
if not Path(data_file).exists():
print(f" [SKIP] {data_file} not found")
return None
mid_price = get_mid_from_data(data_file)
if mid_price <= 0:
print(f" [SKIP] Cannot determine mid-price for {date_str}")
return None
tick_size = detect_tick_size(mid_price)
snapshot_file = find_snapshot(date_str, data_dir)
print(f"\n Calibrating on: {date_str} | Mid: {mid_price:.2f} | "
f"Tick: {tick_size}")
cal = calibrate_from_data(
data_file=data_file,
snapshot_file=snapshot_file,
tick_size=tick_size,
lot_size=LOT_SIZE,
mid_price_approx=mid_price,
window_seconds=600.0,
)
sigma = cal["sigma"]
A_cal = cal["A"]
k_cal = cal["k"]
Q = int(round(total_qty / 0.01))
gamma_cal = calibrate_gamma(
Q=Q, T=float(HORIZON_SEC), sigma=sigma,
A=A_cal, k=k_cal, target_delta_ticks=1.0, tick_size=tick_size,
)
result = {
"date": date_str,
"sigma": sigma,
"A": A_cal,
"k": k_cal,
"gamma": gamma_cal,
"eta_ac": cal["eta_ac"],
"tick_size": tick_size,
"mid_price": mid_price,
"Q": Q,
}
if "lambda_curve" in cal and "ticks" in cal:
result["lambda_curve"] = cal["lambda_curve"]
result["lambda_ticks"] = cal["ticks"]
return result
# ══════════════════════════════════════════════════════════════════════════
# Execution pass (uses pre-computed calibration)
# ══════════════════════════════════════════════════════════════════════════
def execute_day(
date_str: str,
data_file: str,
data_dir: Path,
cal: dict,
total_qty: float,
cal_source: str = "same-day",
) -> tuple[pd.DataFrame | None, dict | None]:
"""Run all strategy combos on one day using provided calibration (can be OOS)."""
if not Path(data_file).exists():
print(f" [SKIP] {data_file} not found")
return None, None
mid_price = get_mid_from_data(data_file)
if mid_price <= 0:
print(f" [SKIP] Cannot determine mid-price for {date_str}")
return None, None
tick_size = detect_tick_size(mid_price)
snapshot_file = find_snapshot(date_str, data_dir)
sigma = cal["sigma"]
A_cal = cal["A"]
k_cal = cal["k"]
gamma_cal = cal["gamma"]
eta_ac = cal["eta_ac"]
Q = cal["Q"]
print(f"\n Executing on: {date_str} | Mid: {mid_price:.2f} | "
f"Params from: {cal_source}")
print(f" sigma={sigma:.4f} A={A_cal:.2f} k={k_cal:.4f} "
f"gamma={gamma_cal:.2e} eta={eta_ac:.4f}")
# ── Build schedules from calibration ───────────────────────────────
dt_slice = HORIZON_SEC / N_SLICES
arg_ac = 1.0 + gamma_cal * sigma**2 / (4.0 * eta_ac) * dt_slice**2
alpha_ac = np.arccosh(arg_ac) / dt_slice if arg_ac > 1.0 else 0.0
kappa_T = alpha_ac * HORIZON_SEC
print(f" AC: alpha={alpha_ac:.6f} alphaT={kappa_T:.3f}")
ac_sched = almgren_chriss_schedule(
total_qty, HORIZON_SEC, N_SLICES, sigma,
gamma=gamma_cal, eta=eta_ac,
)
twap_sched = twap_schedule(total_qty, HORIZON_SEC, N_SLICES)
# ── Liquidation ODE ────────────────────────────────────────────────
delta_grid, t_grid = build_delta_grid(
total_qty=total_qty, unit_size=0.01, T=float(HORIZON_SEC),
sigma=sigma, gamma=gamma_cal, kappa=k_cal, A=A_cal, b=0, dt=1.0,
)
# ── Collect calibration info for plots ─────────────────────────────
cal_info = {
"date": date_str,
"sigma": sigma, "A": A_cal, "k": k_cal, "gamma": gamma_cal,
"delta_grid": delta_grid, "t_grid": t_grid,
"ac_sched": ac_sched, "twap_sched": twap_sched,
"Q": Q, "tick_size": tick_size, "mid_price": mid_price,
}
if "lambda_curve" in cal and "lambda_ticks" in cal:
cal_info["lambda_curve"] = cal["lambda_curve"]
cal_info["lambda_ticks"] = cal["lambda_ticks"]
# ROI bounds for book-walk
roi_lb = mid_price * 0.8
roi_ub = mid_price * 1.2
combos = [
("AC+MktOrder", ac_sched, exec_market_order, {"roi_lb": roi_lb, "roi_ub": roi_ub}),
("AC+GLFT", ac_sched, exec_glft_liquidation, {"delta_grid": delta_grid, "unit_size": 0.01, "order_size": 0.01, "roi_lb": roi_lb, "roi_ub": roi_ub}),
("AC+PegBest", ac_sched, exec_peg_best, {"order_size": 0.01, "roi_lb": roi_lb, "roi_ub": roi_ub}),
("TWAP+MktOrder", twap_sched, exec_market_order, {"roi_lb": roi_lb, "roi_ub": roi_ub}),
("TWAP+GLFT", twap_sched, exec_glft_liquidation, {"delta_grid": delta_grid, "unit_size": 0.01, "order_size": 0.01, "roi_lb": roi_lb, "roi_ub": roi_ub}),
("TWAP+PegBest", twap_sched, exec_peg_best, {"order_size": 0.01, "roi_lb": roi_lb, "roi_ub": roi_ub}),
]
day_results = []
for label, schedule, tactic_fn, kwargs in combos:
asset = (
BacktestAsset()
.data([data_file])
.linear_asset(1.0)
.power_prob_queue_model(2.0)
.no_partial_fill_exchange()
.trading_value_fee_model(-0.00005, 0.0007)
.tick_size(tick_size)
.lot_size(LOT_SIZE)
.roi_lb(roi_lb)
.roi_ub(roi_ub)
.constant_order_latency(10_000_000, 10_000_000)
)
if snapshot_file:
asset = asset.initial_snapshot(snapshot_file)
hbt = ROIVectorMarketDepthBacktest([asset])
fills = np.zeros(MAX_FILLS, dtype=FILL_DTYPE)
horizon_ns = int(HORIZON_SEC * 1e9)
n_fills = tactic_fn(hbt, schedule, total_qty, horizon_ns, fills, **kwargs)
hbt.close()
if n_fills == 0:
print(f" {label:20s} -> 0 fills")
continue
fc = fills[:n_fills]
total_filled = fc["qty"].sum()
avg_px = (fc["price"] * fc["qty"]).sum() / total_filled if total_filled > 0 else 0
arrival = fc["mid_price"][0]
is_bps = (arrival - avg_px) / arrival * 10_000 if arrival > 0 else 0
last_mid = fc["mid_price"][-1]
trend_bps = (last_mid - arrival) / arrival * 10_000 if arrival > 0 else 0
n_limit = int((fc["is_market"] == 0).sum())
completion = total_filled / total_qty * 100
# Book-walk impact stats (market orders only)
mkt_fills = fc[fc["is_market"] == 1]
if len(mkt_fills) > 0:
walk_impact_bps = np.mean(
(mkt_fills["best_bid_at_fill"] - mkt_fills["price"])
/ mkt_fills["mid_price"] * 10_000
)
avg_levels = np.mean(mkt_fills["n_levels"])
else:
walk_impact_bps = 0.0
avg_levels = 0.0
print(f" {label:20s} fills={n_fills:3d} IS={is_bps:+7.2f} bps "
f"limit={n_limit / n_fills * 100:3.0f}% "
f"walk_impact={walk_impact_bps:+.2f} bps "
f"avg_levels={avg_levels:.1f}")
day_results.append({
"date": date_str,
"cal_source": cal_source,
"strategy": label,
"fills": n_fills,
"limit_pct": n_limit / n_fills * 100 if n_fills > 0 else 0,
"qty_sold": total_filled,
"completion": completion,
"is_bps": is_bps,
"trend_bps": trend_bps,
"arrival": arrival,
"walk_impact_bps": walk_impact_bps,
"avg_levels": avg_levels,
})
day_df = pd.DataFrame(day_results) if day_results else None
return day_df, cal_info
# ══════════════════════════════════════════════════════════════════════════
# Legacy wrapper: in-sample (calibrate + execute on same day)
# ══════════════════════════════════════════════════════════════════════════
def run_single_day(
date_str: str,
data_file: str,
data_dir: Path,
total_qty: float,
) -> tuple[pd.DataFrame | None, dict | None]:
"""In-sample: calibrate and execute on the same day."""
cal = calibrate_day(date_str, data_file, data_dir, total_qty)
if cal is None:
return None, None
return execute_day(date_str, data_file, data_dir, cal, total_qty,
cal_source=f"{date_str} (in-sample)")
# ══════════════════════════════════════════════════════════════════════════
# Analytical plots (from calibrated model)
# ══════════════════════════════════════════════════════════════════════════
def plot_analytical(cal_info: dict, output_dir: Path, total_qty: float):
"""Analytical plots from the last day's calibrated parameters."""
output_dir.mkdir(parents=True, exist_ok=True)
sigma = cal_info["sigma"]
A = cal_info["A"]
k = cal_info["k"]
gamma = cal_info["gamma"]
Q = cal_info["Q"]
tick = cal_info["tick_size"]
delta_grid = cal_info["delta_grid"]
t_grid = cal_info["t_grid"]
ac_sched = cal_info["ac_sched"]
twap_sched = cal_info["twap_sched"]
# ── 1. delta*(t, q) surface ───────────────────────────────────────
fig, ax = plt.subplots(figsize=(5.8, 3.8))
step = max(1, len(t_grid) // 360)
t_ds = t_grid[::step] / 60.0
dg_ds = delta_grid[1:, ::step]
dg_clipped = np.clip(dg_ds, -0.5, 2.0)
q_btc = np.arange(1, Q + 1) * (total_qty / Q)
cmap_colors = ["#b91c1c", "#ef4444", "#fca5a5", "#ffffff",
"#93c5fd", "#3b82f6", "#1d4ed8"]
cmap = LinearSegmentedColormap.from_list("delta", cmap_colors, N=256)
im = ax.pcolormesh(t_ds, q_btc, dg_clipped,
cmap=cmap, shading="auto",
vmin=-0.3, vmax=1.5, rasterized=True)
cs = ax.contour(t_ds, q_btc, dg_clipped,
levels=[0.0, 0.25, 0.50, 0.75, 1.0],
colors="k", linewidths=0.4, alpha=0.5)
ax.clabel(cs, fmt="%.2f", fontsize=7, inline_spacing=2)
ax.contour(t_ds, q_btc, dg_clipped,
levels=[0.0], colors="#1a1a2e", linewidths=1.3)
cbar = fig.colorbar(im, ax=ax, pad=0.02, aspect=30)
cbar.set_label(r"$\delta^*$ (\$)", fontsize=9)
cbar.ax.tick_params(labelsize=8)
ax.set_xlabel("Time (minutes)")
ax.set_ylabel("Remaining inventory (BTC)")
ax.set_title(
r"Optimal ask distance $\delta^*(t,\,q)$"
f" -- $\\sigma={sigma:.1f}$, $A={A:.2f}$, $k={k:.2f}$",
fontsize=10, pad=8,
)
ax.annotate("Market orders\n" r"$(\delta^* \leq 0)$",
xy=(55, 0.85 * total_qty), fontsize=7.5, color="#991b1b",
ha="center", style="italic")
ax.annotate("Limit orders\n" r"$(\delta^* > 0)$",
xy=(15, 0.20 * total_qty), fontsize=7.5, color="#1e40af",
ha="center", style="italic")
plt.tight_layout()
plt.savefig(output_dir / "delta_surface.pdf")
plt.savefig(output_dir / "delta_surface.png", dpi=250)
plt.close()
# ── 2. delta* time slices (fixed q) ───────────────────────────────
fig, ax = plt.subplots(figsize=(5.4, 3.6))
q_levels = [Q, int(Q * 0.70), int(Q * 0.40), int(Q * 0.15), max(int(Q * 0.03), 1)]
q_colors = ["#dc2626", "#d97706", "#2563eb", "#059669", "#7c3aed"]
q_styles = ["-", "--", "-", "--", "-"]
t_min = t_grid / 60.0
for q_idx, c, ls in zip(q_levels, q_colors, q_styles):
btc = q_idx * (total_qty / Q)
d = delta_grid[q_idx, :]
ax.plot(t_min, d, color=c, lw=1.4, ls=ls,
label=rf"$q = {btc:.2f}$ BTC")
all_vals = np.concatenate([delta_grid[q, :] for q in q_levels])
all_vals = all_vals[np.isfinite(all_vals)]
y_lo = max(np.percentile(all_vals, 1) - 0.15, -1.0)
y_hi = min(np.percentile(all_vals, 99) + 0.15, 4.0)
ax.axhline(0, color="#1a1a2e", lw=0.7, ls=":", alpha=0.6)
ax.annotate(r"$\delta^* = 0$: switch to market order",
xy=(32, 0), xytext=(20, y_lo + 0.15),
fontsize=7, color="#6b7280", style="italic",
arrowprops=dict(arrowstyle="-", color="#6b7280", lw=0.5))
ax.set_xlabel("Time (minutes)")
ax.set_ylabel(r"$\delta^*$ (\$)")
ax.set_title(r"$\delta^*(t)$ at fixed inventory levels", fontsize=10, pad=8)
ax.legend(**_LEGEND_KW, loc="upper right", fontsize=7.5)
ax.set_xlim(0, 60)
ax.set_ylim(y_lo, y_hi)
ax.grid(True, alpha=0.2)
plt.tight_layout()
plt.savefig(output_dir / "delta_slices.pdf")
plt.savefig(output_dir / "delta_slices.png", dpi=250)
plt.close()
# ── 3. AC vs TWAP schedule ────────────────────────────────────────
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5.8, 2.8),
gridspec_kw={"wspace": 0.35})
t_nodes = np.linspace(0, HORIZON_SEC, N_SLICES + 1) / 60.0
ac_traj = np.concatenate([[total_qty], total_qty - np.cumsum(ac_sched)])
tw_traj = np.concatenate([[total_qty], total_qty - np.cumsum(twap_sched)])
ax1.plot(t_nodes, ac_traj, color="#2563eb", lw=1.6,
label=r"AC ($\kappa T = 2$)")
ax1.plot(t_nodes, tw_traj, color="#dc2626", lw=1.6, ls="--",
label="TWAP")
ax1.fill_between(t_nodes, ac_traj, tw_traj, alpha=0.07, color="#2563eb")
ax1.set_xlabel("Time (minutes)")
ax1.set_ylabel("Inventory (BTC)")
ax1.set_title("Inventory trajectory", fontsize=10, pad=6)
ax1.legend(**_LEGEND_KW, loc="upper right")
ax1.set_xlim(0, 60)
ax1.set_ylim(0, total_qty * 1.05)
ax1.grid(True, alpha=0.2)
slice_mid = (t_nodes[:-1] + t_nodes[1:]) / 2
ax2.bar(slice_mid - 0.25, ac_sched * 1000, width=0.45,
color="#2563eb", alpha=0.75, label="AC",
edgecolor="white", lw=0.3)
ax2.bar(slice_mid + 0.25, twap_sched * 1000, width=0.45,
color="#dc2626", alpha=0.75, label="TWAP",
edgecolor="white", lw=0.3)
ax2.set_xlabel("Time (minutes)")
ax2.set_ylabel("Trade size (mBTC)")
ax2.set_title("Per-slice quantity", fontsize=10, pad=6)
ax2.legend(**_LEGEND_KW)
ax2.set_xlim(0, 60)
ax2.grid(True, axis="y", alpha=0.2)
plt.tight_layout()
plt.savefig(output_dir / "schedule_comparison.pdf")
plt.savefig(output_dir / "schedule_comparison.png", dpi=250)
plt.close()
# ── 4. Fill intensity lambda(delta) ───────────────────────────────
if "lambda_curve" in cal_info:
lambda_curve = cal_info["lambda_curve"]
lambda_ticks = cal_info["lambda_ticks"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5.8, 2.8),
gridspec_kw={"wspace": 0.35})
delta_price = lambda_ticks * tick * 0.5
d_smooth = np.linspace(0, delta_price.max(), 200)
ax1.scatter(delta_price, lambda_curve, s=10, color="#1a1a2e",
alpha=0.45, zorder=3, label=r"Empirical $\hat{\lambda}(\delta)$")
ax1.plot(d_smooth, A * np.exp(-k * d_smooth),
color="#2563eb", lw=1.5,
label=rf"Fit: $A={A:.2f},\; k={k:.2f}$")
ax1.set_xlabel(r"Depth $\delta$ (\$)")
ax1.set_ylabel(r"$\lambda(\delta)$ (trades/s)")
ax1.set_title("Fill intensity", fontsize=10, pad=6)
ax1.legend(**_LEGEND_KW, fontsize=7.5)
ax1.set_xlim(0, delta_price.max())
ax1.grid(True, alpha=0.2)
ax2.scatter(delta_price, lambda_curve, s=10, color="#1a1a2e",
alpha=0.45, zorder=3)
ax2.plot(d_smooth, A * np.exp(-k * d_smooth),
color="#2563eb", lw=1.5)
ax2.set_yscale("log")
ax2.set_xlabel(r"Depth $\delta$ (\$)")
ax2.set_ylabel(r"$\lambda(\delta)$ (trades/s)")
ax2.set_title("Log scale -- exponential fit", fontsize=10, pad=6)
ax2.set_xlim(0, delta_price.max())
ax2.grid(True, alpha=0.2, which="both")
plt.tight_layout()
plt.savefig(output_dir / "intensity_fit.pdf")
plt.savefig(output_dir / "intensity_fit.png", dpi=250)
plt.close()
print(f" Analytical plots saved to {output_dir}")
# ══════════════════════════════════════════════════════════════════════════
# Main
# ══════════════════════════════════════════════════════════════════════════
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--data-dir", type=str, default="data/raw")
parser.add_argument("--output-dir", type=str, default="results/multiday")
parser.add_argument("--mode", type=str, default="insample",
choices=["insample", "oos"],
help="insample = calibrate+execute same day; "
"oos = calibrate D, execute D+1")
parser.add_argument("--total-qty", type=float, default=1.0,
help="Total BTC to liquidate per day")
args = parser.parse_args()
data_dir = Path(args.data_dir)
output_dir = Path(args.output_dir)
total_qty = args.total_qty
if args.mode == "oos":
output_dir = output_dir / "oos"
output_dir.mkdir(parents=True, exist_ok=True)
date_files = discover_dates(data_dir)
if not date_files:
print(f"No .npz data files found in {data_dir}")
print("Expected files like: btcusdt_20241215.npz")
sys.exit(1)
print("=" * 70)
print(f" MULTI-DAY HIERARCHICAL EXECUTION BACKTEST -- hftbacktest L2")
print(f" Mode: {args.mode.upper()}")
print("=" * 70)
print(f" Instrument: BTCUSDT (Binance Futures)")
print(f" Inventory: {total_qty} BTC per day")
print(f" Horizon: {HORIZON_SEC}s ({HORIZON_SEC // 60} min)")
print(f" Days found: {len(date_files)}")
for d, f in date_files:
print(f" {d[:4]}-{d[4:6]}-{d[6:]} ({Path(f).name})")
print("=" * 70)
# ── Run ─────────────────────────────────────────────────────────────
all_results = []
last_cal = None
if args.mode == "insample":
# Original behavior: calibrate and execute on same day
for i, (date_str, filepath) in enumerate(date_files):
print(f"\n{'_'*70}")
print(f" Day {i+1}/{len(date_files)}: {date_str}")
print(f"{'_'*70}")
day_df, cal_info = run_single_day(
date_str, filepath, data_dir, total_qty,
)
if day_df is not None:
all_results.append(day_df)
if cal_info is not None:
last_cal = cal_info
elif args.mode == "oos":
# Out-of-sample: calibrate on day D, execute on day D+1
if len(date_files) < 2:
print("\nNeed at least 2 days for out-of-sample mode.")
sys.exit(1)
prev_cal = None
for i, (date_str, filepath) in enumerate(date_files):
print(f"\n{'_'*70}")
print(f" Day {i+1}/{len(date_files)}: {date_str}")
print(f"{'_'*70}")
# Calibrate on this day (for use tomorrow)
today_cal = calibrate_day(date_str, filepath, data_dir, total_qty)
# Execute on this day using yesterday's calibration
if prev_cal is not None:
print(f"\n >> Executing with D-1 params "
f"(calibrated on {prev_cal['date']})")
day_df, cal_info = execute_day(
date_str, filepath, data_dir,
cal=prev_cal,
total_qty=total_qty,
cal_source=f"{prev_cal['date']} (D-1)",
)
if day_df is not None:
all_results.append(day_df)
if cal_info is not None:
last_cal = cal_info
else:
print(f" >> First day: calibration only (no D-1 params yet)")
prev_cal = today_cal
if not all_results:
print("\nNo results.")
sys.exit(1)
agg = pd.concat(all_results, ignore_index=True)
# ── Aggregate stats ────────────────────────────────────────────────
n_days = agg["date"].nunique()
print(f"\n{'='*70}")
print(f" AGGREGATE RESULTS ACROSS {n_days} DAYS ({args.mode.upper()})")
print(f"{'='*70}")
summary_rows = []
for s in agg["strategy"].unique():
sub = agg[agg["strategy"] == s]
summary_rows.append({
"strategy": s,
"Days": len(sub),
"IS (bps)": f"{sub['is_bps'].mean():+.2f} +/- {sub['is_bps'].std():.2f}",
"Walk Impact": f"{sub['walk_impact_bps'].mean():+.2f} bps",
"Avg Fills": f"{sub['fills'].mean():.0f}",
"Limit%": f"{sub['limit_pct'].mean():.0f}%",
"Completion": f"{sub['completion'].mean():.1f}%",
})
summary = pd.DataFrame(summary_rows).set_index("strategy")
print(summary.to_string())
print(f"{'='*70}")
# ── Effect decomposition ───────────────────────────────────────────
print(f"\n{'='*70}")
print(f" EFFECT DECOMPOSITION")
print(f"{'='*70}")
for sched in ["AC", "TWAP"]:
mkt = agg[agg["strategy"] == f"{sched}+MktOrder"].set_index("date")["is_bps"]
glft = agg[agg["strategy"] == f"{sched}+GLFT"].set_index("date")["is_bps"]
common = mkt.index.intersection(glft.index)
if len(common) > 0:
diff = glft.loc[common] - mkt.loc[common]
print(f" {sched}: GLFT - MktOrder = {diff.mean():+.2f} +/- {diff.std():.2f} bps")
ac_mkt = agg[agg["strategy"] == "AC+MktOrder"].set_index("date")["is_bps"]
tw_mkt = agg[agg["strategy"] == "TWAP+MktOrder"].set_index("date")["is_bps"]
common = ac_mkt.index.intersection(tw_mkt.index)
if len(common) > 0:
diff = ac_mkt.loc[common] - tw_mkt.loc[common]
print(f" Scheduler (MktOrder): AC - TWAP = {diff.mean():+.2f} +/- {diff.std():.2f} bps")
print(f"{'='*70}")
# ── Save ───────────────────────────────────────────────────────────
agg.to_csv(output_dir / "multiday_results.csv", index=False)
summary.to_csv(output_dir / "multiday_summary.csv")
# ── Generate plots ─────────────────────────────────────────────────
print(f"\nGenerating plots...")
if last_cal is not None:
plot_analytical(last_cal, output_dir, total_qty)
if __name__ == "__main__":
main()