5D Library › 高杠杆衍生品清算瀑布、订单簿深度衰竭与协整统计套利 · English

第六章 卡尔曼滤波与动态对冲比率

一个会移动的对冲比率

上一章的协整系数 bb 是一个常数。但两家公司的业务结构、杠杆与市场对它们的定价都会慢慢变化,对冲比率也可能随之漂移。常见的做法有两种。滚动最小二乘:每天用最近 ww 天的数据重新回归。卡尔曼滤波:把对冲比率当作一个看不见的、随时间随机变化的状态,每来一个新观测就按一定的权重更新它。

卡尔曼 1960 年提出的滤波器 (Kalman 1960) 适用于线性高斯的状态空间模型。在配对交易中,状态是 (at,bt)(a_t, b_t),模型为

yt=at+btxt+vt,vt∼N(0,R);(at,bt)=(at−1,bt−1)+wt,wt∼N(0,Q).y_t = a_t + b_t x_t + v_t,\quad v_t \sim N(0, R); \qquad (a_t, b_t) = (a_{t-1}, b_{t-1}) + w_t,\quad w_t \sim N(0, Q).

观测方程说价格之间的关系每天带一点噪声 RR;状态方程说对冲比率每天随机游走一小步,步长的方差由 QQ 决定。滤波每天做两件事:预测——把昨天的估计带到今天,不确定性 PP 增加 QQ;更新——计算新观测与预测的差(「新息」)et=yt−at|t−1−bt|t−1xte_t = y_t – a_{t|t-1} – b_{t|t-1}x_t 及其方差 St=HPH⊤+RS_t = H P H^\top + R(H=(1,xt)H = (1, x_t)),按卡尔曼增益 K=PH⊤/StK = P H^\top / S_t 修正状态,并缩小 PP。系统的讨论见德宾与库普曼的专著 (Durbin and Koopman 2012)。埃利奥特、范德胡克与马尔科姆把配对价差本身写成一个带观测噪声的均值回复隐状态,用同类方法估计 (Elliott et al. 2005)。

QQ 与 RR 之比决定了滤波器的性格:QQ 相对 RR 越大,滤波器越相信「对冲比率变了」,反应越快,也越容易把噪声当成信号;QQ 越小,它越接近一个用全部历史做的固定回归。

追踪对冲比率

两状态卡尔曼滤波用标准库手写(2×2 矩阵展开计算),与 30、60、120、250 天的滚动最小二乘比较。合成数据 1,000 天:一种情形下对冲比率从 1.0 开始随机游走(每天标准差 0.005);另一种情形下它在第 500 天从 1.0 跳到 1.3。每个估计只用到当天为止的数据,从第 250 天起计分;「到达」是跳变后估计第一次进入 1.3 ± 0.05 所需的天数。

推导

# Two-state Kalman filter (a, b random walks) vs rolling OLS on synthetic data:
# b drifts (daily sd 0.005) or jumps 1.0 -> 1.3 on day 500. Scored from day 250.
import math, random
rng = random.Random(1960)

def kalman(xs, ys, qa, qb, R=1.0):
    a, b = 0.0, 0.0
    P = [[100.0, 0.0], [0.0, 100.0]]     # vague start
    out = []
    for x, y in zip(xs, ys):
        P = [[P[0][0] + qa, P[0][1]], [P[1][0], P[1][1] + qb]]          # predict
        e = y - a - b * x
        PH = [P[0][0] + P[0][1] * x, P[1][0] + P[1][1] * x]             # P H'
        S = PH[0] + PH[1] * x + R
        K = [PH[0] / S, PH[1] / S]
        a += K[0] * e; b += K[1] * e
        P = [[P[i][j] - K[i] * PH[j] for j in range(2)] for i in range(2)]
        out.append(b)
    return out

def rolling(xs, ys, w):
    out = []
    for t in range(len(xs)):
        lo = max(0, t - w + 1); X, Y = xs[lo:t + 1], ys[lo:t + 1]; n = len(X)
        if n < 3: out.append(0.0); continue
        mx, my = sum(X) / n, sum(Y) / n
        sxx = sum((u - mx) ** 2 for u in X)
        out.append(sum((u - mx) * (v - my) for u, v in zip(X, Y)) / sxx if sxx else 0.0)
    return out

def data(kind):
    xs, bs, x, b = [], [], 50.0, 1.0
    for t in range(1000):
        x += rng.gauss(0, 1)
        if kind == "drift": b += rng.gauss(0, 0.005)
        else: b = 1.3 if t >= 500 else 1.0
        xs.append(x); bs.append(b)
    ys = [b * x + rng.gauss(0, 1) for x, b in zip(xs, bs)]
    return xs, ys, bs

def rmse(est, bs):
    return math.sqrt(sum((e - b) ** 2 for e, b in zip(est[250:], bs[250:])) / 750)

def first(est):                          # days after the step until first within 0.05
    for t in range(500, 1000):
        if abs(est[t] - 1.3) < 0.05: return t - 500


print("estimator            | drift: RMSE of b | step: RMSE of b | reach (days)")
xs1, ys1, b1 = data("drift"); xs2, ys2, b2 = data("step")
rows = [(f"Kalman, qb = {q}^2", (lambda q: lambda x, y: kalman(x, y, 1e-6, q * q))(q))
        for q in (0.005, 0.02)]
rows += [(f"rolling OLS, w = {w}", (lambda w: lambda x, y: rolling(x, y, w))(w))
         for w in (30, 60, 120, 250)]
low = []
for name, f in rows:
    e1, e2 = f(xs1, ys1), f(xs2, ys2)
    tag = ("KF " if name[0] == "K" else "OLS ") + name.split("= ")[1]
    low.append(f"{tag} {min(e2[500:]):+.2f}")
    print(f"{name:20s} |      {rmse(e1, b1):6.4f}      |     {rmse(e2, b2):6.4f}      |"
          f"      {first(e2):3d}")
print("step: lowest estimate after day 500 (true value 1.3):")
print("   " + "; ".join(low[:3])); print("   " + "; ".join(low[3:]))
# estimator            | drift: RMSE of b | step: RMSE of b | reach (days)
# Kalman, qb = 0.005^2 |      0.0229      |     0.0471      |       81
# Kalman, qb = 0.02^2  |      0.0497      |     0.0479      |        3
# rolling OLS, w = 30  |      0.1996      |     0.3188      |       30
# rolling OLS, w = 60  |      0.1663      |     0.3738      |       59
# rolling OLS, w = 120 |      0.1836      |     0.3288      |      116
# rolling OLS, w = 250 |      0.1914      |     0.5079      |      242
# step: lowest estimate after day 500 (true value 1.3):
#    KF 0.005^2 +1.05; KF 0.02^2 +1.14; OLS 30 -0.74
#    OLS 60 -0.55; OLS 120 +0.17; OLS 250 +0.24
对冲比率在第 500 天从 1.0 跳到 1.3 时各估计量的轨迹。窗口跨越跳变点时,滚动回归的斜率远离新旧两个真实值(60 天窗口一度为负,250 天窗口一度降到 0.24),直到窗口完全移过跳变点;按缓慢漂移设定的卡尔曼滤波很快升到 1.2 左右,再慢慢接近 1.3。

在对冲比率缓慢漂移、而且滤波器的设定恰好正确(QQ 等于真实的漂移方差、截距几乎不变)时,卡尔曼滤波的均方根误差为 0.023,所有滚动回归都在 0.17 到 0.20 之间:滚动窗口短则噪声大,长则跟不上漂移,而且每个窗口都要同时估计截距,在价格变化范围不大的窗口里斜率很不稳定。面对突然的跳变,情况变得微妙:按缓慢漂移设定的滤波器要 81 天才第一次进入 1.3 ± 0.05,QQ 放大 16 倍(标准差 0.02)后只需 3 天,但在漂移情形下误差翻倍(0.050)。滚动回归在跳变处的问题更严重:窗口同时包含跳变前后的数据时,斜率会远离两个真实值,30 天与 60 天窗口的最低估计分别为 −0.74 与 −0.55,250 天窗口为 0.24,直到窗口完全移过跳变点。没有一种设定在两种情形下都最好;而在真实数据中,我们并不知道变化是缓慢漂移还是突然跳变。

注

这个比较对卡尔曼滤波是有利的。 合成数据的生成方式与滤波器的假设完全一致(截距不变、对冲比率随机游走、观测噪声是白噪声),而滚动回归每次都在重新估计截距。真实价差不是白噪声,而是均值回复的——这恰恰是配对交易想要赚的东西。下面的程序显示,这一点会改变结论。

追得最准,不等于交易最好

200 对合成配对,每对 750 天:对冲比率缓慢漂移(每天标准差 0.002),价差是半衰期 10 天、标准差 1 的 OU 过程。第 tt 天的信号所用的截距与对冲比率只用第 t−1t-1 天为止的数据估计,再代入第 tt 天的价格:卡尔曼滤波用新息除以其标准差 et/Ste_t/\sqrt{S_t},滚动回归用前 ww 天回归的残差除以残差标准差。规则与第五章相同(|z|>2|z| > 2 开仓,回到 0 平仓),成本为每条腿每次交易 0.1 个价格单位(每条腿的名义价值约 50,相当于约 20 个基点;收益以两条腿合计约 100 的总敞口的百分比计);第 250—749 天计分。滤波器的 QQ 取真实漂移方差的 0.01、1、100、10,000 倍,R=1R = 1。

推导

# 200 synthetic pairs (b drifts, spread OU with half-life 10 d). Fitted to t-1, applied
# to day-t prices; |z| > 2 open, 0 close; cost 0.10 per leg per trade (each leg ~50,
# so ~20 bp of a leg); days 250-749 scored. Illustrative.
import math, random
rng = random.Random(2010)
QB, B_OU = 0.002 ** 2, 0.5 ** (1 / 10)

def pair():
    xs, ys, bs, x, b, s = [], [], [], 50.0, 1.0, rng.gauss(0, 1)
    for _ in range(750):
        x += rng.gauss(0, 1); b += rng.gauss(0, 0.002)
        s = B_OU * s + rng.gauss(0, math.sqrt(1 - B_OU ** 2))
        xs.append(x); ys.append(b * x + s); bs.append(b)
    return xs, ys, bs

def kalman_signals(xs, ys, qa, qb, R=1.0):
    a, b, P, out = 0.0, 0.0, [[100.0, 0.0], [0.0, 100.0]], []
    for x, y in zip(xs, ys):
        P = [[P[0][0] + qa, P[0][1]], [P[1][0], P[1][1] + qb]]
        e = y - a - b * x
        PH = [P[0][0] + P[0][1] * x, P[1][0] + P[1][1] * x]; S = PH[0] + PH[1] * x + R
        out.append((b, e / math.sqrt(S)))  # prediction made before seeing y
        K = [PH[0] / S, PH[1] / S]; a += K[0] * e; b += K[1] * e
        P = [[P[i][j] - K[i] * PH[j] for j in range(2)] for i in range(2)]
    return out

def ols_signals(xs, ys, w):
    out = [(0.0, 0.0)]
    for t in range(1, len(xs)):
        X, Y = xs[max(0, t - w):t], ys[max(0, t - w):t]; n = len(X)
        mx, my = sum(X) / n, sum(Y) / n; sxx = sum((u - mx) ** 2 for u in X)
        b = sum((u - mx) * (v - my) for u, v in zip(X, Y)) / sxx if sxx > 0 else 0.0
        a = my - b * mx
        sd = math.sqrt(sum((v - a - b * u) ** 2 for u, v in zip(X, Y)) / max(n - 2, 1))
        out.append((b, (ys[t] - a - b * xs[t]) / sd if sd > 0 else 0.0))
    return out

def trade(xs, ys, sig, cost=0.10):
    pos, pnl = 0, 0.0
    for t in range(250, 749):
        b, z = sig[t]
        if pos == 0 and abs(z) > 2: pos = -1 if z > 0 else 1; pnl -= 2 * cost
        elif pos and z * pos >= 0: pos = 0; pnl -= 2 * cost
        pnl += pos * ((ys[t + 1] - ys[t]) - b * (xs[t + 1] - xs[t]))
    return (pnl - 2 * cost * (pos != 0)) / 2     # per year, % of ~100 gross

pairs = [pair() for _ in range(200)]
def kf(k): return lambda x, y: kalman_signals(x, y, 1e-6 * k, QB * k)
def ols(w): return lambda x, y: ols_signals(x, y, w)
cfg = [(f"Kalman, q x {k:g}", kf(k)) for k in (0.01, 1, 100, 10000)]
cfg += [(f"rolling OLS, w = {w}", ols(w)) for w in (60, 120)]
res = {}
print("method               | RMSE of b | net P&L % per year: mean (SE) | pairs > 0")
for name, f in cfg:
    pn, err = [], []
    for xs, ys, bs in pairs:
        sig = f(xs, ys)
        err += [(sig[t][0] - bs[t]) ** 2 for t in range(250, 750)]
        pn.append(trade(xs, ys, sig))
    res[name] = pn
    m = sum(pn) / 200; se = math.sqrt(sum((p - m) ** 2 for p in pn) / 199 / 200)
    pos = sum(p > 0 for p in pn) / 200
    print(f"{name:20s} |  {math.sqrt(sum(err) / len(err)):6.3f}   |"
          f"         {m:5.2f} ({se:4.2f})          |  {pos:5.1%}")
d = [k - o for k, o in zip(res["Kalman, q x 1"], res["rolling OLS, w = 60"])]
md = sum(d) / 200; sd = math.sqrt(sum((v - md) ** 2 for v in d) / 199)
print(f"paired difference, Kalman (q x 1) minus OLS w = 60: {md:+.2f} % per year")
print(f"   SD across pairs {sd:.2f}, SE {sd / math.sqrt(200):.2f}")
# method               | RMSE of b | net P&L % per year: mean (SE) | pairs > 0
# Kalman, q x 0.01     |   0.059   |          3.21 (0.11)          |  99.0%
# Kalman, q x 1        |   0.042   |          0.58 (0.06)          |  58.0%
# Kalman, q x 100      |   0.039   |          0.02 (0.01)          |   2.5%
# Kalman, q x 10000    |   0.045   |          0.00 (0.00)          |   0.5%
# rolling OLS, w = 60  |   0.148   |          2.49 (0.13)          |  91.5%
# rolling OLS, w = 120 |   0.112   |          3.31 (0.12)          |  96.0%
# paired difference, Kalman (q x 1) minus OLS w = 60: -1.91 % per year
#    SD across pairs 1.93, SE 0.14

结果和直觉相反。QQ 等于真实值时,滤波器追踪对冲比率的误差(0.042)远小于 60 天滚动回归(0.148),但交易收益只有每年 0.58%,60 天滚动回归是 2.49%,两者逐对相减的平均差为 −1.91 个百分点(标准误 0.14)。QQ 再放大,追踪误差几乎不变,交易收益却降到零。原因是:均值回复的价差在滤波器看来有一部分像是「对冲比率变了」,QQ 越大,滤波器越会把价差的偏离吸收进 ata_t 与 btb_t,新息越小,交易信号也就越少。QQ 只取真实值的百分之一时,滤波器几乎不动,交易收益(3.21%)与 120 天滚动回归(3.31%)相当。

这说明三件事。第一,「卡尔曼滤波优于滚动回归」不是一个可以泛泛而谈的命题,它取决于 QQ、RR 的设定、真实对冲比率怎样变化,以及评价标准是追踪误差还是扣除成本后的交易收益。第二,QQ 与 RR 不能在同一份数据上一边调、一边评价:在多种设定里挑出回测最好的一个,正是贝利等人所说的回测过拟合 (Bailey et al. 2014)。第三,这些都是合成数据的结果,参数是示意值;它们说明了为什么需要检验,但不能代替真实数据上的检验。

假说 · 尚未验证

卡尔曼滤波对冲在真实数据上优于滚动回归(尚未确立)。 框架提出的命题是:用卡尔曼滤波动态估计对冲比率的配对交易,扣除现实成本后的样本外收益高于 60 天滚动最小二乘。作者把它作为假说,而不是结论。可证伪的预测:在第八章预先登记的样本外检验中,逐对的年化净收益差的置信区间若完全落在 ±1\pm 1 个百分点以内,或整体低于零,假说就被否定或不值得采用。

本章小结

卡尔曼滤波把对冲比率当作随机游走的隐状态,每天用新息按增益修正;Q/RQ/R 决定它的反应速度。在设定恰好正确、观测噪声为白噪声的合成数据上,它追踪对冲比率比滚动回归准得多;但面对突然的跳变,没有一种设定处处最好。更重要的是,当价差本身是均值回复的,追踪得最准的设定反而会吸收掉交易信号,在合成配对上的净收益低于 60 天滚动回归。卡尔曼滤波是否在真实数据上更好,必须用预先登记、样本外、扣除现实成本的检验来回答——这是第八章的试验方案。下一章先回到约一千年前的四川,看一种由「本钱」支撑的纸币如何在滥发中失去信用。

参考文献

Bailey, David H., Jonathan M. Borwein, Marcos López de Prado, and Qiji Jim Zhu. 2014. “Pseudo-Mathematics and Financial Charlatanism: The Effects of Backtest Overfitting on Out-of-Sample Performance.” Notices of the American Mathematical Society 61 (5): 458–71.
Durbin, James, and Siem Jan Koopman. 2012. Time Series Analysis by State Space Methods. 2nd ed. Oxford University Press.
Elliott, Robert J., John van der Hoek, and William P. Malcolm. 2005. “Pairs Trading.” Quantitative Finance 5 (3): 271–76. https://doi.org/10.1080/14697680500149370.
Kalman, Rudolph E. 1960. “A New Approach to Linear Filtering and Prediction Problems.” Journal of Basic Engineering 82 (1): 35–45. https://doi.org/10.1115/1.3662552.

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).