[关闭]
@Channelchan 2018-01-06T14:06:51.000000Z 字数 3280 阅读 85914

线性回归策略

用线性回归交易

目录

什么是线性回归?

在统计学中,线性回归(Linear Regression)是利用称为线性回归方程的最小平方函数对一个或多个自变量和因变量之间关系进行建模的一种回归分析。

Slope和intercept是什么?

其中k是slope,而b是intercept

Confidence Band是怎么算的?

一般是Y加减两个标准差的值

如何用线性回归做策略?

  1. Buy: 价格大于预测值
  2. Buy: 价格大于上方边界
  3. Buy: Slope>0
  4. Buy: 残差变化率的均线上涨
  1. from jaqs.data import DataView
  2. from jaqs.data import RemoteDataService
  3. import os
  4. import numpy as np
  5. import talib as ta
  6. import pandas as pd
  7. from datetime import datetime
  8. import matplotlib.pyplot as plt
  9. import warnings
  10. warnings.filterwarnings("ignore")
  11. dataview_folder = 'JAQS_Data/hs300'
  12. dv = DataView()
  13. dv.load_dataview(dataview_folder)
Dataview loaded successfully.
  1. def change_index(df):
  2. df.index = pd.Index(map(lambda x: datetime.strptime(str(x),"%Y%m%d") , df.index))
  3. return df
  4. data = change_index(dv.get_ts('close_adj').loc[20170105:])
  1. slope = ta.abstract.LINEARREG_SLOPE(data, 60, price='000001.SZ')
  2. intercept = ta.abstract.LINEARREG_INTERCEPT(data, 60, price='000001.SZ')
  3. prediction = slope*data['000001.SZ']+intercept
  4. band = 2*ta.abstract.STDDEV(data, 60, price='000001.SZ')
  5. plt.figure(figsize=(15,9))
  6. plt.subplot(2,1,1)
  7. plt.plot(data['000001.SZ'])
  8. plt.plot(prediction)
  9. plt.plot(prediction+band)
  10. plt.plot(prediction-band)
  11. plt.subplot(2,1,2)
  12. plt.hlines(y=0,xmax=slope.index[-1],xmin=slope.index[0])
  13. plt.plot(slope)
  14. plt.show()

output_8_0.png-49.7kB

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

output_9_0.png-44.7kB

  1. #价格大于预测值
  2. import rqalpha
  3. from rqalpha.api import *
  4. import talib
  5. def init(context):
  6. context.s1 = "000001.XSHE"
  7. context.PERIOD = 10
  8. def handle_bar(context, bar_dict):
  9. price = history_bars(context.s1, context.PERIOD+1, '1d', 'close')
  10. slope = talib.LINEARREG_SLOPE(price, context.PERIOD)
  11. intercept = talib.LINEARREG_INTERCEPT(price, context.PERIOD)
  12. prediction = slope*price+intercept
  13. cur_position = context.portfolio.positions[context.s1].quantity
  14. shares = context.portfolio.cash/bar_dict[context.s1].close
  15. if price[-1] < prediction[-1] and cur_position > 0:
  16. order_target_value(context.s1, 0)
  17. if price[-1] > prediction[-1] :
  18. order_shares(context.s1, shares)
  19. config = {
  20. "base": {
  21. "start_date": "2015-06-01",
  22. "end_date": "2017-12-30",
  23. "accounts": {'stock':1000000},
  24. "benchmark": "000001.XSHE"
  25. },
  26. "extra": {
  27. "log_level": "error",
  28. },
  29. "mod": {
  30. "sys_analyser": {
  31. "enabled": True,
  32. "plot": True
  33. }
  34. }
  35. }
  36. rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

output_10_0.png-74.2kB

  1. # 残差变化率的均线上涨
  2. import rqalpha
  3. from rqalpha.api import *
  4. import talib
  5. def init(context):
  6. context.s1 = "000001.XSHE"
  7. context.PERIOD = 10
  8. def handle_bar(context, bar_dict):
  9. price = history_bars(context.s1, context.PERIOD*3, '1d', 'close')
  10. slope = talib.LINEARREG_SLOPE(price, context.PERIOD)
  11. intercept = talib.LINEARREG_INTERCEPT(price, context.PERIOD)
  12. prediction = slope*price+intercept
  13. residual = (price-prediction)/price
  14. residual_MA = ta.MA(residual, 20)
  15. cur_position = context.portfolio.positions[context.s1].quantity
  16. shares = context.portfolio.cash/bar_dict[context.s1].close
  17. if residual[-1] < residual_MA[-1] and cur_position > 0:
  18. order_target_value(context.s1, 0)
  19. if residual[-1] > residual_MA[-1]:
  20. order_shares(context.s1, shares)
  21. config = {
  22. "base": {
  23. "start_date": "2015-06-01",
  24. "end_date": "2017-12-30",
  25. "accounts": {'stock':1000000},
  26. "benchmark": "000001.XSHE"
  27. },
  28. "extra": {
  29. "log_level": "error",
  30. },
  31. "mod": {
  32. "sys_analyser": {
  33. "enabled": True,
  34. "plot": True
  35. }
  36. }
  37. }
  38. rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

output_11_0.png-72.1kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注