经典量化交易策略系列——线性回归的趋势跟踪系统
本篇通过各个收盘的波峰波谷做简单线性回归拟合出类似的趋势线,然后结合股价以及预测值来跟踪趋势。思路:上升趋势线用波谷拟合,用波峰的值和拟合预测值做比较;下降趋势线用波峰拟合,用波谷的值和拟合预测值做比较。注:这种拟合的方式也许信号发出的不一定准确,后续可以加上拟合度置信区间来提高信号的准确性。
#源码:
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
from sklearn import datasets, linear_model
# 定义一个全局变量, 保存要操作的证券
security = '510180.XSHG'
# 初始化此策略
# 设置我们要操作的股票池, 这里我们只操作一支股票
set_universe()
arraySplitNum = 5
def initialize(context):
g.fixedStartDate = datetime(2000,1,1)
g.peakPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])
g.throughPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])
g.priceBuy = 0.0
# 每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次
def handle_data(context, data):
hData = history(3, '1d', 'close', )
hData.columns = ['close']
pLen = len(g.peakPrice)
tLen = len(g.throughPrice)
# 计算相对时间变量
xDays = (context.current_dt - g.fixedStartDate).days - 1
if hData.iloc[-2].close >= hData.iloc[-3].close \
and hData.iloc[-1].close <= hData.iloc[-2].close:
# 这是波峰
g.peakPrice.loc = .close, context.current_dt + timedelta(days=-1)]
elif hData.iloc[-2].close <= hData.iloc[-3].close \
and hData.iloc[-1].close >= hData.iloc[-2].close:
# 这是波谷
g.throughPrice.loc = .close, context.current_dt + timedelta(days=-1)]
pricePredictP = data.pre_close
pricePredictT = data.pre_close
lastPePrice = pricePredictP
lastThPrice = pricePredictT
pLen = len(g.peakPrice)
tLen = len(g.throughPrice)
ifpLen > 1 :
# Create linear regression object
regrP = linear_model.LinearRegression()
# Train the model using the training sets
regrP.fit(np.reshape(g.peakPrice.xDays.values, pLen).reshape(pLen,1), g.peakPrice.yPrice.values)
pricePredictP = regrP.predict(xDays)
lastPePrice = g.peakPrice.ix.yPrice
iftLen > 1 :
# Create linear regression object
regrT = linear_model.LinearRegression()
# Train the model using the training sets
regrT.fit(np.reshape(g.throughPrice.xDays.values, tLen).reshape(tLen,1), g.throughPrice.yPrice.values)
pricePredictT = regrT.predict(xDays)
lastThPrice = g.throughPrice.ix.yPrice
bsFlag = ''
lastClosePrice = data.pre_close
if lastClosePrice > pricePredictP or lastThPrice > pricePredictP:
bsFlag = '+'
elif lastClosePrice < pricePredictT or lastPePrice < pricePredictT:
bsFlag = '-'
# 取得当前价格
current_price = data.open
# 取得当前的现金
cash = context.portfolio.cash
if bsFlag == '+' and g.priceBuy == 0 :
# 全仓买入
# 计算可以买多少只股票
number_of_shares = int(cash/current_price)
# 购买量大于0时,下单
if number_of_shares > 0:
# 买入股票
order(security, +number_of_shares)
g.priceBuy = current_price
# 记录这次买入
log.info(str(context.current_dt) + " Buying %s" % (security))
#g.peakPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])
elif bsFlag == '-' and g.priceBuy > 0 :
# 清仓卖出
# 卖出所有股票,使这只股票的最终持有量为0
order_target(security, 0)
g.priceBuy = 0.0
g.throughPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])
# 记录这次卖出
log.info(str(context.current_dt) + " Selling %s" % (security))
#record(closeP=data.close)
record(peakP=pricePredictP)
record(throughP=pricePredictT)
#record(lastThP=lastThPrice)
#record(peakP=pricePredictP)
线性回归的趋势跟踪系统,牛逼
页:
[1]