@Channelchan
2018-01-06T06:06:51.000000Z
字数 3280
阅读 86130
用线性回归交易
在统计学中,线性回归(Linear Regression)是利用称为线性回归方程的最小平方函数对一个或多个自变量和因变量之间关系进行建模的一种回归分析。
其中k是slope,而b是intercept
一般是Y加减两个标准差的值
from jaqs.data import DataViewfrom jaqs.data import RemoteDataServiceimport osimport numpy as npimport talib as taimport pandas as pdfrom datetime import datetimeimport matplotlib.pyplot as pltimport warningswarnings.filterwarnings("ignore")dataview_folder = 'JAQS_Data/hs300'dv = DataView()dv.load_dataview(dataview_folder)
Dataview loaded successfully.
def change_index(df):df.index = pd.Index(map(lambda x: datetime.strptime(str(x),"%Y%m%d") , df.index))return dfdata = change_index(dv.get_ts('close_adj').loc[20170105:])
slope = ta.abstract.LINEARREG_SLOPE(data, 60, price='000001.SZ')intercept = ta.abstract.LINEARREG_INTERCEPT(data, 60, price='000001.SZ')prediction = slope*data['000001.SZ']+interceptband = 2*ta.abstract.STDDEV(data, 60, price='000001.SZ')plt.figure(figsize=(15,9))plt.subplot(2,1,1)plt.plot(data['000001.SZ'])plt.plot(prediction)plt.plot(prediction+band)plt.plot(prediction-band)plt.subplot(2,1,2)plt.hlines(y=0,xmax=slope.index[-1],xmin=slope.index[0])plt.plot(slope)plt.show()

# 残差residual = (data['000001.SZ']-prediction)/data['000001.SZ']MA_R = pd.Series(ta.MA(residual.values, 30),index=residual.index)f,(a1,a2)=plt.subplots(2,1,sharex=True,figsize=(15,9))a1.plot(data['000001.SZ'])a2.plot(MA_R)a2.plot(residual)plt.show()

#价格大于预测值import rqalphafrom rqalpha.api import *import talibdef init(context):context.s1 = "000001.XSHE"context.PERIOD = 10def handle_bar(context, bar_dict):price = history_bars(context.s1, context.PERIOD+1, '1d', 'close')slope = talib.LINEARREG_SLOPE(price, context.PERIOD)intercept = talib.LINEARREG_INTERCEPT(price, context.PERIOD)prediction = slope*price+interceptcur_position = context.portfolio.positions[context.s1].quantityshares = context.portfolio.cash/bar_dict[context.s1].closeif price[-1] < prediction[-1] and cur_position > 0:order_target_value(context.s1, 0)if price[-1] > prediction[-1] :order_shares(context.s1, shares)config = {"base": {"start_date": "2015-06-01","end_date": "2017-12-30","accounts": {'stock':1000000},"benchmark": "000001.XSHE"},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

# 残差变化率的均线上涨import rqalphafrom rqalpha.api import *import talibdef init(context):context.s1 = "000001.XSHE"context.PERIOD = 10def handle_bar(context, bar_dict):price = history_bars(context.s1, context.PERIOD*3, '1d', 'close')slope = talib.LINEARREG_SLOPE(price, context.PERIOD)intercept = talib.LINEARREG_INTERCEPT(price, context.PERIOD)prediction = slope*price+interceptresidual = (price-prediction)/priceresidual_MA = ta.MA(residual, 20)cur_position = context.portfolio.positions[context.s1].quantityshares = context.portfolio.cash/bar_dict[context.s1].closeif residual[-1] < residual_MA[-1] and cur_position > 0:order_target_value(context.s1, 0)if residual[-1] > residual_MA[-1]:order_shares(context.s1, shares)config = {"base": {"start_date": "2015-06-01","end_date": "2017-12-30","accounts": {'stock':1000000},"benchmark": "000001.XSHE"},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

