5D Library › Liquidation Cascades, Order-Book Depth Depletion and Cointegrated Statistical Arbitrage · 中文

Chapter 8 Practice and a Pre-Registered Test

Note

The checklist in this chapter is for understanding and checking risk, not trading advice. The positions, order books and pairs in the examples are fictional, and the thresholds are illustrative values chosen by the author, not industry standards. Highly leveraged derivatives can lose all of the money put in within a very short time; any real decision should rest on your own circumstances and, where needed, the advice of a licensed professional.

Part 1 A four-step checklist

  1. Leverage and distance to liquidation. How far is the liquidation price from the current price? How many daily standard deviations is that at current volatility? Under the optimistic assumption of no gaps, what is the probability of touching it within one day or three days? How far will funding move it? (Chapter 2)
  2. Order-book depth and impact cost. What share of daily volume is the planned order (or a position that might be liquidated)? Estimate impact with the square-root law, taking a range for YY rather than a single number. How large is it compared with the visible depth within 1 % of the price? (Chapters 1 and 3)
  3. Cointegration stability. Test separately in several non-overlapping windows, with residual-based critical values; are the hedge ratio and half-life stable across windows? Remember that one year of data has little power: failing the test means “not shown”, not necessarily “broken”. (Chapters 4 and 5)
  4. Hedge-ratio updates and stops. How much has the hedge ratio changed since entry? Has the position outlived the time stop written down in advance (say, 3 half-lives)? Was the spread stop (say, |z|>4|z| > 4) written down before entry? (Chapters 5 and 6)

Apply the checklist to a fictional account: a perpetual long at 15 times leverage (illustrative annual volatility 70 %), a planned large sell order and a pairs position.

Calculation

# Four-step checklist applied to a FICTIONAL book: one leveraged perpetual long and one
# pairs position. All numbers invented; thresholds are the author's illustrative choices.
import math, random
from statistics import NormalDist
N = NormalDist(); rng = random.Random(39)

print("1. leverage and distance to liquidation (long, isolated, m = 0.5 %)")
L, m, vol = 15, 0.005, 0.70                 # leverage, maintenance rate, annual vol
dist = 1 - (1 - 1 / L) / (1 - m); sd1 = vol / math.sqrt(365)
p1 = 2 * N.cdf(math.log(1 - dist) / sd1)
p3 = 2 * N.cdf(math.log(1 - dist) / (sd1 * 3 ** .5))
print(f"   distance {dist:.2%} = {dist / sd1:.1f} daily sd; P(touch) 1 day {p1:.1%},"
      f" 3 days {p3:.1%}")
print(f"   -> {'FLAG' if dist / sd1 < 3 else 'ok'} (rule: distance >= 3 daily sd)")

print("2. order-book depth and impact cost (square-root rule, Y between 0.5 and 1.5)")
Q, V, depth1 = 4e6, 2e8, 3e6               # order, daily volume, visible depth within 1 %
lo, hi = (Y * sd1 * math.sqrt(Q / V) for Y in (0.5, 1.5))
print(f"   order {Q / V:.1%} of daily volume: impact {lo:.2%} to {hi:.2%}")
print(f"   order / visible depth within 1 % = {Q / depth1:.1f}x"
      f" -> {'FLAG' if Q > depth1 else 'ok'} (rule: order <= depth within 1 %)")

print("3. cointegration stability (fictional pair, three 250-day windows)")
def eg_t(y, x):                             # Engle-Granger, no augmentation lag
    n = len(x); mx, my = sum(x) / n, sum(y) / n
    b = sum((u - mx) * (v - my) for u, v in zip(x, y)) / sum((u - mx) ** 2 for u in x)
    e = [v - (my - b * mx) - b * u for u, v in zip(x, y)]
    d = [e[i] - e[i - 1] for i in range(1, n)]
    g = sum(a * c for a, c in zip(e[:-1], d)) / sum(a * a for a in e[:-1])
    r = [c - g * a for a, c in zip(e[:-1], d)]
    se = math.sqrt(sum(v * v for v in r) / (n - 2) / sum(a * a for a in e[:-1]))
    hl = math.log(2) / -math.log(1 + g) if -1 < g < 0 else float("inf")
    return g / se, b, hl
x, s, xs, ys = 50.0, 0.0, [], []
for t in range(750):
    x += rng.gauss(0, 1)
    s = (s + rng.gauss(0, 0.3)) if t >= 500 else 0.93 * s + rng.gauss(0, 0.37)
    xs.append(x); ys.append(1.2 * x + s)
for k in range(3):
    tt, b, hl = eg_t(ys[250 * k:250 * (k + 1)], xs[250 * k:250 * (k + 1)])
    print(f"   window {k + 1}: EG t = {tt:6.2f} (5 % value -3.36), hedge {b:.2f},"
          f" half-life {hl:5.1f} d -> {'ok' if tt < -3.36 else 'FLAG'}")

print("4. hedge-ratio update and exits")
b_entry, b_now, hl_est, held = 1.20, 1.31, 9.0, 35
print(f"   hedge ratio moved {b_now / b_entry - 1:+.1%} since entry"
      f" -> {'FLAG: re-hedge or close' if abs(b_now / b_entry - 1) > 0.05 else 'ok'}")
print(f"   held {held} days vs time stop 3 x half-life = {3 * hl_est:.0f} days"
      f" -> {'FLAG: close' if held > 3 * hl_est else 'ok'}")
print("   stop at |z| > 4 written down before entry: yes")
# 1. leverage and distance to liquidation (long, isolated, m = 0.5 %)
#    distance 6.20% = 1.7 daily sd; P(touch) 1 day 8.1%, 3 days 31.3%
#    -> FLAG (rule: distance >= 3 daily sd)
# 2. order-book depth and impact cost (square-root rule, Y between 0.5 and 1.5)
#    order 2.0% of daily volume: impact 0.26% to 0.78%
#    order / visible depth within 1 % = 1.3x -> FLAG (rule: order <= depth within 1 %)
# 3. cointegration stability (fictional pair, three 250-day windows)
#    window 1: EG t =  -3.27 (5 % value -3.36), hedge 1.17, half-life   8.0 d -> FLAG
#    window 2: EG t =  -3.42 (5 % value -3.36), hedge 1.25, half-life   7.6 d -> ok
#    window 3: EG t =  -1.42 (5 % value -3.36), hedge 1.50, half-life  41.3 d -> FLAG
# 4. hedge-ratio update and exits
#    hedge ratio moved +9.2% since entry -> FLAG: re-hedge or close
#    held 35 days vs time stop 3 x half-life = 27 days -> FLAG: close
#    stop at |z| > 4 written down before entry: yes

Six items are flagged across the four steps. Step 1: the distance to liquidation at 15 times is 6.20 %, only 1.7 daily standard deviations at the illustrative volatility, with a probability of touching of about 8 % within a day and about 31 % within three. Step 2: an order of 2 % of daily volume has an estimated square-root impact between 0.26 % and 0.78 %, but it is 1.3 times the visible depth within 1 % of the price; the decaying book of Chapter 1 shows that in such a case the square-root figure may badly understate the real impact. Step 3 is the most instructive: this fictional pair was cointegrated for its first 500 days (the program generates it that way), yet the test statistic in the first window, −3.27, misses −3.36, and the second window passes narrowly; in the third window the spread has become a random walk, the statistic is only −1.42, the hedge ratio has drifted from about 1.2 to 1.50 and the “half-life” is 41 days. Step 4: the hedge ratio has moved 9.2 % since entry, and 35 days of holding exceed the time stop of 3 half-lives. The checklist does not tell you what to do; it only puts a few easily ignored numbers on the table.

Part 2 Protocol for a pre-registered out-of-sample test

Question

After realistic trading costs, does pairs trading with a hedge ratio estimated dynamically by a Kalman filter earn a higher out-of-sample annualised net return than the same rule with a hedge ratio from 60-day rolling least squares? The synthetic data of Chapter 6 show that the answer depends on the settings, so the question can only be answered on real data with rules fixed in advance.

Design

Element Specification
Unit of study A “pair-window”: a pair chosen by a fixed rule on one formation date, together with its following 6-month trading period
Data and period Daily data on US-listed common stocks. The primary analysis uses CRSP daily stock data with delisting returns, and only the 31 monthly formation dates that occur after the protocol is registered (a prospective test: the data do not yet exist at registration); CRSP data from before registration are used only for a secondary replication; free Yahoo Finance data are used only for a public approximate replication (see “Data sources” below)
Pair-selection rule (fixed in advance) Formation period of the previous 250 trading days; exclude stocks priced under 5 dollars or in the bottom 20 % by average daily traded value; pair only within the same industry; Engle–Granger statistic below MacKinnon’s 5 % critical value (−3.36 for 250 observations); among those passing, take the 20 pairs closest in normalised price distance; each stock enters at most one pair per formation date
Method A Kalman filter: intercept and hedge ratio as random-walk states; QQ and RR estimated only on formation-period data by maximising the innovation likelihood, and not changed during the trading period
Method B (comparator) 60-day rolling least squares (with intercept)
Common trading rule Signals use information up to the previous day only; open at |z|>2|z| > 2, close when zz returns to 0, stop at |z|>4|z| > 4, close at the end of the trading period; the rule code is identical for both methods, differing only in how the hedge ratio and zz are computed
Cost model Per leg per transaction: 10 basis points for commission and half the bid–ask spread, plus square-root-law impact (Y=1Y = 1), plus short-borrowing fees at 1 % a year; 5 and 20 basis points as sensitivity analyses
Randomisation and blinding Both methods act on the same pair-windows (a paired comparison, removing differences in pair selection); an independent data manager randomly codes the method labels as “X” and “Y”, and analysts do not know which is the Kalman filter until the decision-rule code is locked and the results computed
Primary outcome DD: the pair-window-by-pair-window difference in annualised net return (method A minus method B, % of gross exposure), averaged over all pair-windows
Secondary outcomes Difference in Sharpe ratios (tested by the robust method of Ledoit and Wolf (Ledoit and Wolf 2008); see Lo on the statistical properties of Sharpe ratios (Lo 2002)), turnover, maximum drawdown, DD at 5 and 20 basis-point costs, the historical replication
Analysis Robust standard errors clustered by formation date, two-sided α=0.05\alpha = 0.05; all code publicly registered before the first formation date (Nosek et al. 2018)

Data sources

So that others can reproduce the work, the data sources are named below. They are named for reproducibility only; this is not a recommendation of any exchange, data vendor or product (see the risk warning in the Preface). The content, formats and terms of use of every source can change, so a replication should record download dates and versions.

  • Primary analysis: CRSP daily stock data. The US stock database of the Center for Research in Security Prices (CRSP) at the University of Chicago is not free public data: it is normally obtained by institutional subscription through channels such as WRDS, its use is governed by a licence, and the raw data cannot be published with the study. It is chosen for the primary analysis because it includes delisted securities and provides delisting returns: one leg of a pair may be delisted during the trading period through a merger, bankruptcy or failure to meet listing requirements, and leaving out delisting returns biases results towards survivors. Even in CRSP, correct delisting returns were once missing for many stocks delisted for negative reasons (Shumway 1997), so the analysis plan must state in advance how missing delisting returns are handled.
  • Public approximate replication: Yahoo Finance. It is free, but delisted securities are generally not available, so a historical sample rebuilt from it has survivorship bias: pairs can only be drawn from stocks still trading today. Its “adjusted close” is adjusted with split and dividend multipliers (according to its help page, following CRSP standards), and every new dividend or split changes the whole history retroactively, so the replication must state which price column was used, how it was adjusted and when it was downloaded. Its terms of service restrict automated collection, commercial use and redistribution. Yahoo Finance is therefore used only for a public approximate replication and robustness check, never in the decision rule, and the report must explain that differences from the primary analysis may come from survivorship bias and the adjustment method.
  • Descriptive part: Binance Futures public historical data. This part is separate from the stock-pairs test above; it only describes funding rates and liquidation events in perpetual contracts, as background to the models of Chapters 2 and 3, and does not enter the decision rule. The exchange’s public data portal (data.binance.vision) offers daily or monthly files for USD-margined and coin-margined contracts: candlesticks (klines), individual and aggregated trades, mark-price and index-price klines, monthly funding-rate files, and daily order-book depth summaries and metrics such as open interest and long/short ratios. Its futures business only began in the second half of 2019, start dates differ by contract and data type, and some days’ metrics files lack fields, so each item must be checked before replication. Liquidation data need particular care: the portal used to offer daily liquidation snapshots, but their coverage has not been stable: according to user reports on the data project’s GitHub page, no new snapshot files for USD-margined contracts appeared after 31 March 2024, and another user reported that their historical files had been removed from the portal listing; the documentation of third-party download tools now lists daily snapshots only for coin-margined contracts. We found no formal statement from the exchange, so a replication must rely on what the portal actually lists. Moreover, according to a third-party data vendor’s documentation, since 27 April 2021 the exchange’s public liquidation feed has reported only the latest liquidation per contract in each 1,000-millisecond window, so public liquidation data are not a complete record of all liquidations, and the snapshots should not be treated as one either. This book therefore does not use them to estimate total liquidations or to test the effective branching ratio of Chapter 3; any description using liquidation data must state its coverage and gaps.

Sample size

Calculation

# Pair-windows needed for the Chapter 8 test; paired difference D (% per year), design
# effect 1 + (m - 1) icc. ASSUMED, not from any study: SD of D 5 % per year.
import math
from statistics import NormalDist
N = NormalDist()

def pair_windows(sd, sesoi, icc, m=20, alpha=0.05, power=0.90):
    z = N.inv_cdf(1 - alpha / 2) + N.inv_cdf(power)
    return math.ceil(z ** 2 * sd ** 2 / sesoi ** 2 * (1 + (m - 1) * icc))

print("analysable pair-windows, 90 % power, two-sided alpha 0.05, 20 pairs per window")
print("   SD of D | icc  | SESOI 0.5 | 1.0 | 1.5 % per year")
for sd in (4.0, 5.0, 6.0):
    for icc in (0.02, 0.05, 0.10):
        c = [pair_windows(sd, d, icc) for d in (0.5, 1.0, 1.5)]
        print(f"    {sd:3.0f} %  | {icc:.2f} |   {c[0]:5d}   | {c[1]:4d} | {c[2]:4d}")
n = pair_windows(5.0, 1.0, 0.05)
windows = math.ceil(n / (20 * 0.85))
print(f"chosen: SD 5 %, SESOI 1.0 % per year, icc 0.05 -> {n} analysable pair-windows")
print(f"allowing 15 % unusable pair-windows (delisting, missing prices):")
print(f"   {windows} monthly formation dates x 20 pairs = {windows * 20} pair-windows")
# analysable pair-windows, 90 % power, two-sided alpha 0.05, 20 pairs per window
#    SD of D | icc  | SESOI 0.5 | 1.0 | 1.5 % per year
#       4 %  | 0.02 |     929   |  233 |  104
#       4 %  | 0.05 |    1312   |  328 |  146
#       4 %  | 0.10 |    1951   |  488 |  217
#       5 %  | 0.02 |    1451   |  363 |  162
#       5 %  | 0.05 |    2049   |  513 |  228
#       5 %  | 0.10 |    3048   |  762 |  339
#       6 %  | 0.02 |    2089   |  523 |  233
#       6 %  | 0.05 |    2951   |  738 |  328
#       6 %  | 0.10 |    4388   | 1097 |  488
# chosen: SD 5 %, SESOI 1.0 % per year, icc 0.05 -> 513 analysable pair-windows
# allowing 15 % unusable pair-windows (delisting, missing prices):
#    31 monthly formation dates x 20 pairs = 620 pair-windows

There is no published value to borrow for the standard deviation of the difference in annualised net return across pair-windows. The synthetic pairs of Chapter 6 give about 1.9 percentage points (over a two-year trading period); a 6-month trading period and the heterogeneity of real data will both make it larger, so it is assumed to be 5 percentage points a year. The smallest effect of interest is 1.0 percentage point a year, about a quarter to a third of the after-cost monthly return of pairs trading reported by Do and Faff (about 30 basis points, or roughly 3.6 % a year) (Do and Faff 2012); an intra-window correlation of 0.05 is assumed among the 20 pairs from the same formation date. At 90 % power this requires 513 analysable pair-windows; allowing about 15 % unusable through delisting or missing data, 31 monthly formation dates and 620 pair-windows in all. If the standard deviation were 6 percentage points and the intra-window correlation 0.10, the requirement would rise to 1,097.

The meaning of “90 % power” needs stating (consistent with Book 33): it is the probability, when the true difference exactly equals the smallest effect of interest, of reaching some verdict that “the Kalman filter is better”; the strongest verdict in the decision rule, “better by at least 1 percentage point”, then has only about a 2.5 % chance. The program below computes all these probabilities.

Decision rule

Calculation

# Decision rule fixed in advance. D = Kalman minus rolling OLS (60 d), net, % per year;
# 95 % CI clustered by formation date. Gates -> NOT INTERPRETABLE.
from statistics import NormalDist
N = NormalDist()
SESOI = 1.0

def verdict(d, lo, hi, usable=0.92, audit_ok=True, code_ok=True):
    if not (audit_ok and code_ok):
        return f"D = {d:+.2f}: NOT INTERPRETABLE - audit or registered-code check failed"
    if usable < 0.85:
        return (f"D = {d:+.2f}: NOT INTERPRETABLE - only {usable:.0%}"
                " of pair-windows usable")
    if lo >= SESOI:   v = "Kalman better by at least 1.0 % per year"
    elif lo > 0:      v = "Kalman better; size not shown to reach 1.0 % per year"
    elif hi < 0:      v = "Kalman WORSE than rolling OLS"
    elif lo >= -SESOI and hi <= SESOI: v = "no difference worth acting on"
    else:             v = "unclear: the interval is too wide to decide"
    return f"D = {d:+.2f} ({lo:+.2f} to {hi:+.2f}): {v}"

for case in ((1.9, 1.2, 2.6), (0.8, 0.1, 1.5), (-0.9, -1.6, -0.2), (0.1, -0.6, 0.8),
             (0.5, -0.9, 1.9), (2.0, 1.3, 2.7, 0.78), (1.5, 0.8, 2.2, 0.95, False)):
    print(verdict(*case))
# What the planned design delivers (normal approximation; SE = SESOI / 3.24 by design).
se = SESOI / (N.inv_cdf(0.975) + N.inv_cdf(0.90)); z = N.inv_cdf(0.975)
print("true D | P(at least SESOI) | P(better, size open) | P(no difference) | P(worse)")
for true in (0.0, 0.5, 1.0, 2.0):
    p_strong = 1 - N.cdf((SESOI + z * se - true) / se)
    p_better = 1 - N.cdf((z * se - true) / se) - p_strong
    p_worse = N.cdf((-z * se - true) / se)
    lo_ok = N.cdf((SESOI - z * se - true) / se) - N.cdf((-SESOI + z * se - true) / se)
    print(f"  {true:3.1f}  |      {p_strong:6.1%}       |       {p_better:6.1%}"
          f"         |      {max(lo_ok, 0):6.1%}      | {p_worse:6.1%}")
print("secondary outcomes (Sharpe-ratio difference, turnover, maximum drawdown, results")
print("  at 5 and 20 bp costs) are reported with intervals and never decide the verdict")
# D = +1.90 (+1.20 to +2.60): Kalman better by at least 1.0 % per year
# D = +0.80 (+0.10 to +1.50): Kalman better; size not shown to reach 1.0 % per year
# D = -0.90 (-1.60 to -0.20): Kalman WORSE than rolling OLS
# D = +0.10 (-0.60 to +0.80): no difference worth acting on
# D = +0.50 (-0.90 to +1.90): unclear: the interval is too wide to decide
# D = +2.00: NOT INTERPRETABLE - only 78% of pair-windows usable
# D = +1.50: NOT INTERPRETABLE - audit or registered-code check failed
# true D | P(at least SESOI) | P(better, size open) | P(no difference) | P(worse)
#   0.0  |        0.0%       |         2.5%         |       80.0%      |   2.5%
#   0.5  |        0.0%       |        36.7%         |       36.5%      |   0.0%
#   1.0  |        2.5%       |        87.5%         |        2.5%      |   0.0%
#   2.0  |       90.0%       |        10.0%         |        0.0%      |   0.0%
# secondary outcomes (Sharpe-ratio difference, turnover, maximum drawdown, results
#   at 5 and 20 bp costs) are reported with intervals and never decide the verdict

The example results are invented. If the audit of the prospective data finds “look-ahead” (for example, information from after the day’s close being used), or the code run differs from the registered code, or fewer than 85 % of the planned pair-windows are usable, the report says “not interpretable” whatever the result. When the true difference is zero, the decision rule has an 80 % chance of “no difference worth acting on” and a 2.5 % chance each of a false “better” or “worse”; when the true difference is 1 percentage point, verdicts of the “better” kind total about 90 %, but only 2.5 % are the strongest verdict; only when the true difference reaches 2 percentage points does the strongest verdict reach 90 %.

What this test cannot show

First, it compares only the relative performance of two ways of estimating the hedge ratio under one pair rule fixed in advance, in one market, over one period; even if the verdict is “the Kalman filter is better”, both methods may lose money. Second, the sample size rests on an assumed standard deviation and intra-window correlation; if the real dispersion is larger, the test will more often end in “unclear”. Third, the cost model is approximate: impact grows with the amount of capital, so conclusions valid at small scale do not carry over to large scale, and the availability and cost of borrowing shares change over time. Fourth, a 31-month prospective period covers one or a few market regimes; the evidence of Chapter 5 shows that pairs trading behaves very differently in turbulent and calm periods, and crowding in similar strategies can make them fail together in a given month. Fifth, it has nothing to do with the highly leveraged perpetual contracts of Chapters 1 to 3 and says nothing about trading crypto-assets or derivatives; the accompanying description of funding rates and liquidations is only a description and tests no hypothesis. Sixth, whatever its result, it is not investment advice.

Ethics and conflicts of interest

The test involves no human participants, but it does involve data licensing and research integrity: CRSP data are used under a subscription licence and are not published with the study, and Yahoo Finance and Binance data are used under their own terms. The protocol, selection rules, cost model and all code must be publicly registered before the first formation date. Because the author (as disclosed below) may hold related positions and provides related consulting services, the test must be run by independent analysts with no financial relationship with the author, following the pre-registered code and using no trading account or funds of the author or any related party; results are published whether positive or negative, together with the code and whatever data can be made public.

Disclosure

The author uses the works of 5D Library, including this book, as the methodological basis of his community courses, the 5D Ascension Cards (Dimensional Shift Card Decks) and the Yafu AI knowledge base, and therefore has a commercial interest in the subject of this book. The book promotes no course, card deck or service; the Chapter 8 trial is designed to be run and analysed by researchers independent of the author’s business and does not recruit from the author’s community, students or customers; all the code and the study protocol are published openly for anyone to check. The author develops and maintains software tools for a priori analysis and quantitative research scripts based on the symbolic system of the sexagenary (ganzhi) calendar, and provides related open-source research and independent consulting services; while writing this book he may have held routine observation positions in US equity index funds (such as SPY) or related derivatives. All models in this book are offered solely for mathematical and historical-statistical discussion; they constitute no investment advice, trading signal or promise of divinatory prediction, and the book recommends no specific trade or asset. To limit the influence of this interest, the test code will be published before the first formation date, and the results and code will be published whatever the outcome.

References

Do, Binh, and Robert Faff. 2012. “Are Pairs Trading Profits Robust to Trading Costs?” Journal of Financial Research 35 (2): 261–87. https://doi.org/10.1111/j.1475-6803.2012.01317.x.
Ledoit, Oliver, and Michael Wolf. 2008. “Robust Performance Hypothesis Testing with the Sharpe Ratio.” Journal of Empirical Finance 15 (5): 850–59.
Lo, Andrew W. 2002. “The Statistics of Sharpe Ratios.” Financial Analysts Journal 58 (4): 36–52.
Nosek, Brian A., Charles R. Ebersole, Alexander C. DeHaven, and David T. Mellor. 2018. “The Preregistration Revolution.” Proceedings of the National Academy of Sciences 115 (11): 2600–2606.
Shumway, Tyler. 1997. “The Delisting Bias in CRSP Data.” Journal of Finance 52 (1): 327–40. https://doi.org/10.1111/j.1540-6261.1997.tb03818.x.

Fan, Y. (2026). Liquidation Cascades, Order-Book Depth Depletion and Cointegrated Statistical Arbitrage: Ornstein-Uhlenbeck Processes and Kalman-Filter Dynamic Hedging [高杠杆衍生品清算瀑布、订单簿深度衰竭与协整统计套利] (Version 1.0.0). 5D Library. https://doi.org/10.5281/zenodo.23796776 · Licensed under Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0).