【量化】相关系数进行配对交易

根据统计数据,对价差进行买卖,而不去做股票本身趋势的预测,是否能做到旱涝保收呢。下面是利用股票对之间的相关系数来进行配对交易的研究。

1,首先想到利用统计套利,可能会想到两只股票的相关系数是否会让两只股票的走势有一种特定关系。

import numpy as np
start = '2014-01-01'#此处时间一定要与回测的时间相对应,因为不同时间可能相关性不一致
end = '2016-11-01'
stock1='601618.XSHG'
stock2='600026.XSHG'
a1 = get_price(stock1,fields='close', start_date=start, end_date=end)
a2 = get_price(stock2,fields='close', start_date=start, end_date=end)
#上图
plt.scatter(a1,a2)
plt.xlabel(stock1)
plt.ylabel(stock2)
plt.title('Stock prices from ' + start + ' to ' + end)
print (stock1+"与"+stock2+"之间的相关系数: ", np.corrcoef(a1["close"],a2["close"]))

同样数据大多都集中在一条直线上

找到相关性高的股票对,我们要来研究它们之间的价差,因为这是我们策略套利的关键

从图中看出,所以相关系数高,两者之间的价差不一定会围绕一个常数波动,价差会具有一定的变异性,即价差序列是非平稳的。
我们来检验下价差的平稳性。

进一步的我们来看看以均值加减一倍标准差是否包含了大部分的差价区间

import pandas as pd
mean=np.mean(a3)
std=np.std(a3)
up=mean+std
down=mean-std
time=a3.index
mean_line=pd.Series(mean,index=time)
up_line=pd.Series(up,index=time)
down_line=pd.Series(down,index=time)
set=pd.concat([a3,mean_line,up_line,down_line],axis=1)
set.columns=['spreadprice','mean','upper','down']
set.plot(figsize=(14,7))

可以看到虽然包含了大部分价差区间,但是开仓次数太少,并且在2014年股票的差价都是在上开仓线附近小幅波动,会造成频繁开仓使得成本十分高。
同时观察2015年价差出现极端值,此时如果开仓,价差不收敛,如果没做到好的平仓条件此时会造成大量亏损。
尽管看图像上通过相关系数来做配对交易不太理想,我们还是通过回测来看看具体结果。

ricequant回测代码

import numpy as np
def init(context):
    #选取研究后相关系数较高的股票对,如果用户想试试其他的配对交易只需改动股票代码即可
    context.s1 = '601618.XSHG'
    context.s2 = '600026.XSHG'

def before_trading(context):
    pass

def handle_bar(context, bar_dict):
    # 取得选取的两只股票1年的收盘价并算出差价
    price_stock1=history_bars(context.s1, 250, '1d', 'close')
    price_stock2=history_bars(context.s2, 250, '1d', 'close')
    diff=price_stock1-price_stock2
    #以均值加一倍标准差作为上开仓线
    up=np.mean(diff)+np.std(diff)
    #以均值减一倍标准差作为下开仓线
    down=np.mean(diff)-np.std(diff)
    #取得进行交易前一天股票的收盘价并计算差价
    yesterday_price1=history_bars(context.s1, 1, '1d', 'close')
    yesterday_price2=history_bars(context.s2, 1, '1d', 'close')
    yesterday_diff=yesterday_price1-yesterday_price2
    #前一天差价达到上开仓线即卖出股票s1,做多s2
    if yesterday_diff>up:
        order_target_percent(context.s1,0)
        order_target_percent(context.s2,1)
    #前一天的差价达到下开仓线即卖出股票s2,做多s1
    if yesterday_diff<down:
        order_target_percent(context.s2,0)
        order_target_percent(context.s1,1)

 回测结果图

根结果显示,统计相关系数配对交易,在强相关的证券,可以获得更高超过市场收益的a回报 

猜你喜欢

转载自blog.csdn.net/u013177138/article/details/125359896