经典量化交易策略系列——线性回归的趋势跟踪系统

1
回复
4394
查看
[复制链接]

294

主题

20

回帖

1380

积分

专栏作家

积分
1380
来源: 2019-7-17 22:20:49 显示全部楼层 |阅读模式
本篇通过各个收盘的波峰波谷做简单线性回归拟合出类似的趋势线,然后结合股价以及预测值来跟踪趋势。思路:上升趋势线用波谷拟合,用波峰的值和拟合预测值做比较;下降趋势线用波峰拟合,用波谷的值和拟合预测值做比较。


    注:这种拟合的方式也许信号发出的不一定准确,后续可以加上拟合度置信区间来提高信号的准确性。



  1. #源码:

  2. from datetime import datetime, timedelta
  3. import numpy as np
  4. import pandas as pd
  5. from sklearn import datasets, linear_model

  6. # 定义一个全局变量, 保存要操作的证券
  7. security = '510180.XSHG'
  8. # 初始化此策略
  9. # 设置我们要操作的股票池, 这里我们只操作一支股票
  10. set_universe([security])

  11. arraySplitNum = 5

  12. def initialize(context):
  13.     g.fixedStartDate = datetime(2000,1,1)
  14.     g.peakPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])
  15.     g.throughPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])
  16.     g.priceBuy = 0.0
  17.    
  18. # 每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次
  19. def handle_data(context, data):
  20.     hData = history(3, '1d', 'close', [security])
  21.     hData.columns = ['close']
  22.    
  23.     pLen = len(g.peakPrice)
  24.     tLen = len(g.throughPrice)
  25.    
  26.     # 计算相对时间变量
  27.     xDays = (context.current_dt - g.fixedStartDate).days - 1
  28.    
  29.     if hData.iloc[-2].close >= hData.iloc[-3].close \
  30.     and hData.iloc[-1].close <= hData.iloc[-2].close:
  31.         # 这是波峰
  32.         g.peakPrice.loc[pLen] = [xDays, hData.iloc[-2].close, context.current_dt + timedelta(days=-1)]
  33.     elif hData.iloc[-2].close <= hData.iloc[-3].close \
  34.     and hData.iloc[-1].close >= hData.iloc[-2].close:
  35.         # 这是波谷
  36.         g.throughPrice.loc[tLen] = [xDays, hData.iloc[-2].close, context.current_dt + timedelta(days=-1)]

  37.     pricePredictP = data[security].pre_close
  38.    
  39.     pricePredictT = data[security].pre_close
  40.    
  41.     lastPePrice = pricePredictP
  42.     lastThPrice = pricePredictT
  43.    
  44.     pLen = len(g.peakPrice)
  45.     tLen = len(g.throughPrice)
  46.     if  pLen > 1 :
  47.         # Create linear regression object
  48.         regrP = linear_model.LinearRegression()
  49.         
  50.         # Train the model using the training sets
  51.         regrP.fit(np.reshape(g.peakPrice.xDays.values, pLen).reshape(pLen,1), g.peakPrice.yPrice.values)
  52.         
  53.         pricePredictP = regrP.predict(xDays)
  54.         
  55.         lastPePrice = g.peakPrice.ix[pLen - 1].yPrice
  56.         
  57.     if  tLen > 1 :
  58.         # Create linear regression object
  59.         regrT = linear_model.LinearRegression()
  60.         
  61.         # Train the model using the training sets
  62.         regrT.fit(np.reshape(g.throughPrice.xDays.values, tLen).reshape(tLen,1), g.throughPrice.yPrice.values)
  63.         
  64.         pricePredictT = regrT.predict(xDays)
  65.         lastThPrice = g.throughPrice.ix[tLen - 1].yPrice

  66.     bsFlag = ''
  67.     lastClosePrice = data[security].pre_close
  68.     if lastClosePrice > pricePredictP or lastThPrice > pricePredictP:
  69.         bsFlag = '+'
  70.     elif lastClosePrice < pricePredictT or lastPePrice < pricePredictT:
  71.         bsFlag = '-'
  72.    
  73.     # 取得当前价格
  74.     current_price = data[security].open
  75.     # 取得当前的现金
  76.     cash = context.portfolio.cash
  77.    
  78.     if bsFlag == '+' and g.priceBuy == 0 :
  79.         # 全仓买入
  80.         # 计算可以买多少只股票
  81.         number_of_shares = int(cash/current_price)
  82.         # 购买量大于0时,下单
  83.         if number_of_shares > 0:
  84.             # 买入股票
  85.             order(security, +number_of_shares)
  86.             g.priceBuy = current_price
  87.             # 记录这次买入
  88.             log.info(str(context.current_dt) + " Buying %s" % (security))
  89.         #g.peakPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])
  90.     elif bsFlag == '-' and g.priceBuy > 0 :
  91.         # 清仓卖出
  92.         # 卖出所有股票,使这只股票的最终持有量为0
  93.         order_target(security, 0)
  94.         g.priceBuy = 0.0
  95.         g.throughPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])
  96.         # 记录这次卖出
  97.         log.info(str(context.current_dt) + " Selling %s" % (security))
  98.    
  99.     #record(closeP=data[security].close)
  100.     record(peakP=pricePredictP)
  101.     record(throughP=pricePredictT)
  102.     #record(lastThP=lastThPrice)
  103.     #record(peakP=pricePredictP)


复制代码
外币.jpg


回复

使用道具 举报

196

主题

140

回帖

1444

积分

管理员

积分
1444
2019-7-17 23:31:56 显示全部楼层
线性回归的趋势跟踪系统,牛逼
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 免费注册
关注微信