布林带回归、配对价差与两腿记账
在合成行情中区分回归信号、实际成交、价差变化及扣费结果。
学完这一章,你能够
- 在合成行情中区分回归信号、实际成交、价差变化及扣费结果。
先明确回归假设
趋势跟踪等待方向延续,均值回归则需要偏离能在持仓期间收敛。区间与持续单边只是用于测试机制的路径。两种策略可能同亏,组合互补仍需检验相关性、成本和样本外收益。
本站依次用一个标的的收盘带宽和两个标的的相对价格做离线实验。真实行情应按相同会话、价格口径、币种和时区对齐,区分缺失与停牌。
布林带入场与中轨退出
用此前 20 个已知收盘估计中轨与样本标准差,下轨取中轨减两倍标准差。历史示例也可在收盘后计算含当期收盘的带宽,那是另一组信号阈值。本站固定使用 shift(1) 的先前窗口,前 20 条无完整基线。
空仓且收盘低于下轨时发入场信号,持仓且收盘回到或越过中轨时发退出信号。次期开盘成交并计手续费。反弹样本按 94 和 102 成交。持续下跌样本发出入场后始终未回中轨,期末按价估值出现亏损。
图示上半幅标记的是收盘时刻,不是成交时刻。净值比较使用相同评估窗的买入持有,区分累计收益、复合年化、同频夏普和相对净值峰值的回撤。历史股价图与数值分别留待核验。
从训练价差到样本外信号
拟合 A=a+βB+ε,β 是训练期的价格回归斜率,本例约为 1.5。回归残差用 A−βB−a,截距只定义中心。以训练期估计后冻结 β 和 a,只在样本外启用规则。回看此前 60 条残差的均值和样本标准差,基线不足或标准差为零时 Z 分数留空。
只有空仓时 Z 严格低于 −2 才发做多价差信号,含义是买 A、按比率借券卖 B。持仓时 |Z| 严格小于 0.5 才发退出信号。恰等阈值不触发。滚动中心会改变,本例 Z 回到退出带时,原残差已从约 −5 进一步落至约 −8。
图示下半幅画的是合成样本的滚动 Z 分数。虚线为入场门槛,色带为退出区。两幅图使用各自观察序号,原股票配对图和具体日期另行登记。
用两腿盈亏解释为何回归仍可能亏损
用 A 的价格变动乘多头数量,减去 B 的价格变动乘空头数量,再扣两腿手续费和持仓期间借券费。实验以 1 单位初始资本和入场总名义值确定数量。价差可以过零,以价差自身作收益分母会产生反号或爆值,不能替代可核查的资本账。
即使滚动 Z 分数满足退出条件,本例原价差继续下移,两腿合计未扣费用就亏损。加入费用后终值更低。无券可借时实验拒绝整个入场,现金保持为 1。实际双腿可能不能同时成交,还需核对保证金、价差跳空、借券召回和流动性。
历史示例 p=0.0617 在 5% 水平未拒绝无协整,不能据此证明永不协整,也不能把某次亏损归因给单个检验。配对的市场 Beta、净敞口和总敞口应分别衡量。价格回归斜率不自动消除市场风险。
合成实验图
上图对照收盘、前 20 点中轨和下轨,下图对照样本外进出点及 60 点滚动 Z 分数。两处三角均表示收盘信号。成交、费用和期末估值见实验输出。

两种规则各自依赖的条件
| 流派 | 实验假设及失败条件 |
|---|---|
| 趋势跟踪 | 前期通道突破后若价格不延续,可能反复出入并付出成本 |
| 均值回归 | 偏离后要能回到有效基线,持续下跌或中心漂移可继续亏损 |
运行布林带信号、价差与两腿记账
"""Run Bollinger reversion and paired-spread accounting on fixed inputs."""
import json
from pathlib import Path
from platform import python_version
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def bands(close):
window=close.shift(1).rolling(20,min_periods=20)
middle=window.mean()
return middle,middle-2*window.std(ddof=1)
def state_events(values,entry,exit):
held=False
events={}
for day,value in enumerate(values):
if not np.isfinite(value):
continue
if not held and entry(day,value):
events[day]="enter"
held=True
elif held and exit(day,value):
events[day]="exit"
held=False
return events
def single_asset(close,events,fee=.001):
opening=np.r_[close.iloc[0],close.to_numpy()[:-1]]
cash,shares=1.,0.
equity=[1.]
fills=[]
for day in range(21,len(close)):
action=events.get(day-1)
price=float(opening[day])
if action=="enter":
shares=cash/(price*(1+fee))
cash=0.
fills.append(dict(signal=day-1,day=day,side="buy",price=price))
elif action=="exit":
cash=shares*price*(1-fee)
shares=0.
fills.append(dict(signal=day-1,day=day,side="sell",price=price))
equity.append(float(cash+shares*close.iloc[day]))
return np.array(equity),fills
def performance(equity):
assert np.all(equity>0) and len(equity)>2
returns=equity[1:]/equity[:-1]-1
volatility=float(returns.std(ddof=1))
risk_free=(1.03**(1/252))-1
return dict(cumulative=float(equity[-1]/equity[0]-1),
annualized=float((equity[-1]/equity[0])**(252/len(returns))-1),
annual_volatility=volatility*np.sqrt(252),
max_drawdown=float((1-equity/np.maximum.accumulate(equity)).max()),
sharpe=float((returns.mean()-risk_free)*np.sqrt(252)/volatility) if volatility>0 else None)
def bollinger_case():
close=pd.Series([100.]*20+[94,93,94,102,103,101,100,98,100,101],dtype="float64")
middle,lower=bands(close)
events=state_events(close,lambda i,v:v<lower.iloc[i],lambda i,v:v>=middle.iloc[i])
assert middle.iloc[:20].isna().all() and lower.iloc[20]==100
assert events=={20:"enter",23:"exit"}
equity,fills=single_asset(close,events)
baseline,_=single_asset(close,{20:"enter"})
assert [trade["day"] for trade in fills]==[21,24]
assert [trade["price"] for trade in fills]==[94,102]
assert equity[-1]>1 and equity[-1]>baseline[-1]
falling=pd.Series([100.]*20+list(range(95,70,-1)),dtype="float64")
m,l=bands(falling)
downward=state_events(falling,lambda i,v:v<l.iloc[i],lambda i,v:v>=m.iloc[i])
stress,_=single_asset(falling,downward)
assert downward=={20:"enter"} and stress[-1]<1
return (close,middle,lower,events),dict(signal_events=events,fills=fills,
strategy=performance(equity),buy_and_hold=performance(baseline),
no_recovery_stress=performance(stress))
def z_score(spread):
window=spread.shift().rolling(60,min_periods=60)
return (spread-window.mean())/window.std(ddof=1).where(lambda value:value>0)
def pair_input():
base=100+np.arange(182)*.25
residue=np.r_[np.tile([1.,-1.,-1.,1.],20),-5.,-8.+np.resize([-.15,.15,.15,-.15],101)]
return pd.DataFrame({"A":4+1.5*base+residue,"B":base})
def pair_ledger(close,beta,events,*,trade_fee=.001,borrow=.00035,borrow_allowed=True,start=81):
opening=close.shift()
nav=[1.]
capital=1.
size=0.
fees=borrow_total=gross=0.
fills=[]
refused=[]
for day in range(start,len(close)):
prev_a,prev_b=close.iloc[day-1]
open_a,open_b=opening.iloc[day]
close_a,close_b=close.iloc[day]
overnight=size*((open_a-prev_a)-beta*(open_b-prev_b))
capital+=overnight
gross+=overnight
action=events.get(day-1)
if action=="enter" and not borrow_allowed:
refused.append(day)
elif action=="enter":
size=capital/(open_a+beta*open_b)
cost=size*(open_a+beta*open_b)*trade_fee
capital-=cost
fees+=cost
fills.append(dict(day=day,signal=day-1,side="enter",a=float(open_a),b=float(open_b),
long_units=float(size),short_units=float(beta*size)))
elif action=="exit" and size:
cost=size*(open_a+beta*open_b)*trade_fee
capital-=cost
fees+=cost
fills.append(dict(day=day,signal=day-1,side="exit",a=float(open_a),b=float(open_b)))
size=0.
change=size*((close_a-open_a)-beta*(close_b-open_b))
carry=size*beta*close_b*borrow
capital+=change-carry
gross+=change
borrow_total+=carry
nav.append(float(capital))
assert np.isclose(nav[-1],1+gross-fees-borrow_total)
return dict(equity=np.asarray(nav),fills=fills,refused=refused,fees=float(fees),
borrow=float(borrow_total),gross_pnl=float(gross),end_open=bool(size))
def pair_case():
prices=pair_input()
train=prices.iloc[:80]
beta,intercept=np.polyfit(train.B,train.A,1)
assert np.isclose(beta,1.5) and np.isclose(intercept,4.)
changed=prices.copy()
changed.loc[80:,"A"]+=30
assert np.array_equal(np.polyfit(changed.B.iloc[:80],changed.A.iloc[:80],1),[beta,intercept])
spread=prices.A-beta*prices.B-intercept
z=z_score(spread)
assert z.iloc[:60].isna().all() and z_score(pd.Series([2.]*80)).isna().all()
assert z.iloc[80]<-2
trading=z.where(z.index>=80)
events=state_events(trading,lambda i,v:v< -2,lambda i,v:abs(v)<.5)
boundary=state_events(np.array([-2.,-2.1,.5,.49]),lambda i,v:v< -2,lambda i,v:abs(v)<.5)
assert boundary=={1:"enter",3:"exit"}
assert list(events.values())==["enter","exit"],events
assert abs(z.loc[next(i for i,value in events.items() if value=="exit")])<.5
result=pair_ledger(prices,beta,events)
free=pair_ledger(prices,beta,events,trade_fee=0,borrow=0)
denied=pair_ledger(prices,beta,events,borrow_allowed=False)
assert not result["end_open"] and len(result["fills"])==2
assert [trade["day"] for trade in result["fills"]]==[i+1 for i in events]
assert result["equity"][-1]<free["equity"][-1]<1
assert result["fees"]>0 and result["borrow"]>0 and denied["refused"]==[81]
assert not denied["fills"] and denied["equity"][-1]==1
buy,sell=result["fills"]
leg_pnl=buy["long_units"]*(sell["a"]-buy["a"])-buy["short_units"]*(sell["b"]-buy["b"])
assert np.isclose(result["gross_pnl"],leg_pnl)
pct=pd.Series([-.01,.01,.02]).pct_change(fill_method=None).dropna()
assert pct.tolist()==[-2.,1.]
return (z,events),dict(beta=float(beta),intercept=float(intercept),train_rows=len(train),
events={index:dict(action=action,z=float(z.loc[index]),residual=float(spread.loc[index]))
for index,action in events.items()},
fills=result["fills"],gross_pnl=result["gross_pnl"],fees=result["fees"],borrow=result["borrow"],
net_performance=performance(result["equity"]),zero_cost_performance=performance(free["equity"]),
refused_without_borrow=denied["refused"],near_zero_spread_pct_change=pct.tolist())
def draw(boll,pair,output):
close,middle,lower,events=boll
z,pair_events=pair
fig,axes=plt.subplots(2,1,figsize=(8,6),layout="constrained")
a,b=axes
a.plot(close,label="Synthetic close",color="#243a4e")
a.plot(middle,label="Prior 20 mean",color="#86632d")
a.plot(lower,"--",label="Lower band",color="#008270")
b.plot(z,color="#243a4e",label="Prior 60 z-score")
b.axhline(-2,color="#a85438",linestyle="--",label="Entry below -2")
b.axhspan(-.5,.5,color="#41a189",alpha=.18,label="Exit within ±0.5")
for axis,values,points in ((a,close,events),(b,z,pair_events)):
for action,marker,color in (("enter","^","#008270"),("exit","v","#b05238")):
idx=[i for i,action_at in points.items() if action_at==action]
axis.scatter(idx,values.loc[idx],marker=marker,color=color,label=action.title(),zorder=3)
axis.grid(alpha=.2)
axis.legend(ncols=3,loc="best",fontsize=8)
a.set(title="Single-asset mean reversion",ylabel="Price")
b.set(title="Pair residual can drift while its adaptive z-score normalizes",ylabel="Z-score",xlabel="Observation")
fig.savefig(output,dpi=120)
plt.close(fig)
if __name__=="__main__":
boll,single=bollinger_case()
z,pair=pair_case()
draw(boll,z,Path("reversion-signals.png"))
print(json.dumps(dict(bollinger=single,pair=pair,
versions=dict(python=python_version(),numpy=np.__version__,pandas=pd.__version__,
matplotlib=matplotlib.__version__)),indent=2,allow_nan=False))
- 布林带合成样本以 94 买入、102 卖出。配对固定训练 β 后,滚动 Z 分数回到退出区,两腿仍录得负毛盈亏;借券关闭时入场被拒。
所需环境:隔离 CPython 3.12.14、NumPy 2.5.4、Pandas 3.1.0、Matplotlib 3.11.2
当前源码 SHA256:200ec53b5fcfa9f6fc3e95f798fbe5378b1058be99399df8868b86fe35f7cecf
离线回归实验
解压后安装 README 所列依赖并运行 Python。终端显示信号与两腿明细,目录中生成两幅面板。
所需环境:隔离 CPython 3.12.14、NumPy 2.5.4、Pandas 3.1.0、Matplotlib 3.11.2
ZIP SHA256:2f341652cd73bdc61ee9cad4460e7113972581a7ebe52194679e69aac136f202
常见错误与边界
- 归一化信号和现金盈亏需要分开核对。固定回归斜率后再评估样本外,保留借券失败。
练习与解答
为什么 Z 分数回到退出区,配对也可能亏损?
展开参考解答
滚动中心可以向下移动。相对新中心的距离变小,并不保证原价差高于入场。两腿差额和成本才决定资本变化。