(9条消息) Backtrader量化平台教程(八) TimeFrame

AD:(本人录制的backtrader视频课程,大家多多支持哦~ https://edu.csdn.net/course/detail/9040

无意中发现了一个巨牛的人工智能教程,忍不住分享一下给大家。教程不仅是零基础,通俗易懂,而且非常风趣幽默,像看小说一样!觉得太牛了,所以分享给大家。教程链接:https://www.cbedai.net/qtlyx

有时候我们原有的数据和我们想要的数据不是同一个时间框架下的。譬如,我们手上只有分钟级别的数据,而我们想要的是日线级别的数据,或者说手上是日线级别的数据,希望变成周线级别的数据。在backtrader中,有很好的的方法解决这样的问题。总而言之,就是timeframe转换的问题

1.resampling

这个方法,字面意思看起来是“采样”,准确的来说,是上采样,从小的时间点变成大的时间点。

方法很简单,就是在添加数据的时候,不在使用 cerebro.adddata(data),而是使用cerebro.resampledata(data, **kwargs)。
        后面的参数主要有两个,一个是timeframe,也就是你希望变成的timeframe是多少,day还是week;另外一个是compression,就是对bar进行压缩。

2.代码

所有的代码是这样的:

  1. from __future__ import (absolute_import, division, print_function,
  2. unicode_literals)
  3. import datetime # For datetime objects
  4. import backtrader as bt
  5. import backtrader.feeds as btfeeds
  6. import backtrader.indicators as btind
  7. import pandas as pd
  8. import numpy as np
  9. class MyStrategy(bt.Strategy):
  10. params = (
  11. ('ssa_window', 15),
  12. ('maperiod', 15),
  13. )
  14. def log(self, txt, dt=None):
  15. ''' Logging function fot this strategy'''
  16. dt = dt or self.datas[0].datetime.date(0)
  17. print('%s, %s' % (dt.isoformat(), txt))
  18. def __init__(self):
  19. # Keep a reference to the "close" line in the data[0] dataseries
  20. self.dataclose = self.datas[0].close
  21. # To keep track of pending orders and buy price/commission
  22. self.order = None
  23. self.buyprice = None
  24. self.buycomm = None
  25. self.sma = bt.indicators.SimpleMovingAverage(
  26. self.datas[0], period=self.params.maperiod)
  27. def start(self):
  28. print("the world call me!")
  29. def prenext(self):
  30. print("not mature")
  31. def notify_order(self, order):
  32. if order.status in [order.Submitted, order.Accepted]:
  33. # Buy/Sell order submitted/accepted to/by broker - Nothing to do
  34. return
  35. # Check if an order has been completed
  36. # Attention: broker could reject order if not enougth cash
  37. if order.status in [order.Completed]:
  38. if order.isbuy():
  39. self.log(
  40. 'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
  41. (order.executed.price,
  42. order.executed.value,
  43. order.executed.comm))
  44. self.buyprice = order.executed.price
  45. self.buycomm = order.executed.comm
  46. else: # Sell
  47. self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
  48. (order.executed.price,
  49. order.executed.value,
  50. order.executed.comm))
  51. self.bar_executed = len(self)
  52. elif order.status in [order.Canceled, order.Margin, order.Rejected]:
  53. self.log('Order Canceled/Margin/Rejected')
  54. self.order = None
  55. def notify_trade(self, trade):
  56. if not trade.isclosed:
  57. return
  58. self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
  59. (trade.pnl, trade.pnlcomm))
  60. def next(self):
  61. # Simply log the closing price of the series from the reference
  62. self.log('Close, %.2f' % self.dataclose[0])
  63. # Check if an order is pending ... if yes, we cannot send a 2nd one
  64. if self.order:
  65. return
  66. # Check if we are in the market
  67. if not self.position:
  68. # Not yet ... we MIGHT BUY if ...
  69. if self.dataclose[0] > self.sma[0]:
  70. # BUY, BUY, BUY!!! (with all possible default parameters)
  71. self.log('BUY CREATE, %.2f' % self.dataclose[0])
  72. # Keep track of the created order to avoid a 2nd order
  73. self.order = self.buy()
  74. else:
  75. if self.dataclose[0] < self.sma[0]:
  76. # SELL, SELL, SELL!!! (with all possible default parameters)
  77. self.log('SELL CREATE, %.2f' % self.dataclose[0])
  78. # Keep track of the created order to avoid a 2nd order
  79. self.order = self.sell()
  80. def stop(self):
  81. print("death")
  82. if __name__ == '__main__':
  83. # Create a cerebro entity
  84. cerebro = bt.Cerebro(stdstats=False)
  85. # Add a strategy
  86. cerebro.addstrategy(MyStrategy)
  87. dataframe = pd.read_csv('RB.SHF.csv', index_col=0, parse_dates=True)
  88. data0 = bt.feeds.PandasData(dataname=dataframe,
  89. fromdate=datetime.datetime(2014, 5, 13),
  90. todate=datetime.datetime(2014, 6, 20),
  91. timeframe=bt.TimeFrame.Minutes
  92. )
  93. # Add the Data Feed to Cerebro
  94. cerebro.adddata(data0)
  95. data2 = cerebro.resampledata(data0, timeframe=bt.TimeFrame.Days)
  96. cerebro.run()
  97. cerebro.plot(style='bar')


老样子,我们来看一下比较核心的代码。

 

读取数据,数据为分钟级别的数据,如下:

 

 
2014-05-13 08:59:00.005004,3198.0,3198.0,3198.0,3198.0,2148.0,0 2014-05-13 09:00:00.005000,3198.0,3202.0,3195.0,3195.0,37426.0,0 2014-05-13 09:01:00.004997,3195.0,3199.0,3194.0,3198.0,19704.0,0 2014-05-13 09:02:00.005003,3198.0,3199.0,3193.0,3193.0,22682.0,0 2014-05-13 09:03:00.005000,3193.0,3195.0,3192.0,3193.0,23064.0,0 2014-05-13 09:04:00.004996,3193.0,3194.0,3190.0,3190.0,29058.0,0 2014-05-13 09:05:00.005002,3191.0,3191.0,3186.0,3188.0,25044.0,0 2014-05-13 09:06:00.004999,3188.0,3189.0,3186.0,3189.0,16020.0,0 2014-05-13 09:07:00.004995,3189.0,3189.0,3187.0,3188.0,12336.0,0 2014-05-13 09:08:00.005002,3188.0,3188.0,3185.0,3186.0,20484.0,0 2014-05-13 09:09:00.004998,3186.0,3187.0,3184.0,3186.0,19234.0,0
 
dataframe = pd.read_csv('RB.SHF.csv', index_col=0, parse_dates=True)dataframe = pd.read_csv('RB.SHF.csv', index_col=0, parse_dates=True)
  1. data0 = bt.feeds.PandasData(dataname=dataframe,
  2. fromdate=datetime.datetime(2014, 5, 13),
  3. todate=datetime.datetime(2014, 6, 20),
  4. timeframe=bt.TimeFrame.Minutes
  5. )
  1. #timeframe=bt.TimeFrame.Minutes用来指明datafeed的timeframe,默认是days
  2. # Add the Data Feed to Cerebro,就像平常一样
  3. cerebro.adddata(data0)
  4. data2 = cerebro.resampledata(data0, timeframe=bt.TimeFrame.Days)#加入另外一个新的timeframe的datafeed的时候,就不能是adddata了,而是之前说的resampling
  5. cerebro.run()
  6. cerebro.plot(style='bar')
timeframe=bt.TimeFrame.Minutes用来指明datafeed的timeframe,默认是days    # Add the Data Feed to Cerebro,就像平常一样    cerebro.adddata(data0)    data2 = cerebro.resampledata(data0, timeframe=bt.TimeFrame.Days)#加入另外一个新的timeframe的datafeed的时候,就不能是adddata了,而是之前说的resampling    cerebro.run()    cerebro.plot(style='bar')

最后,画出来的plot是这样的:

 

(0)

相关推荐