Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Intraday Resample Issue

    General Code/Help
    1
    1
    304
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • D
      dzz007 last edited by

      Before I dive into my question, I need to clarify that tradingview.com displays its timestamp using the leftedge while backtrader uses the right edge, so the timestamp for the first period in tradingview will be displayed as 9:30am est, and backtrader will be timestamped as the time that the desired timeframe has completed. Foe example, the first 4h period of the day in bt, the timestamp reads 12pm est. Now, on to my question.

      If I want to get the closing price of the first 4 hour period of a specific trading day I should receive the closing price of the first 4h period along with the time that the 4h period was completed. When I do this, I find that the first 4 hour period that is being returned to me is not a complete 240 mins(4h period), instead, it is actually a 2.5h period and the second 4h period of the day is a complete 4h bar. This is not the way that live data is output during normal market trading hours from my experience and so when formulating a backtest that uses these time periods, it throws off the accuracy of the back test a great deal. Below (first 2 pictures) I have printed out a screenshot of the data from tradingview showing how the intraday day data normally outputs during normal market trading hours. You can see that the second 4h period starts at 13:30/1:30pm est(second image). This is unlike backtrader, which starts at 12pm est, as see in the third image. My question is, is there a way to reconfigure the resample to output the data the same way tradingview.com does?

      tradingview.com timestamp for the 1st 4h
      period of the day (timestamped as 9:30am est)
      0_1558904716031_Inked1.jpg

      tradingview.com timestamp for the 2nd 4h
      period of the day (timestamped as 13:30/1:30pm est)
      0_1558904725968_Inked2.jpg

      Backtrader timestamp for the 4h period (1st period timestamped as 12pm est and the 2nd period timestamped as 16/4pm est)
      0_1558902182053_3.PNG

      I am new here so I might not be resampling properly. Below is the code I've used to resample 1min data into 4h. Any help would be appreciated. If I am not clear on anything, please let me know so I can try and explain further.

      # Import the backtrader platform
      import backtrader as bt
      import pandas
      
      import matplotlib
      
      # matplotlib.use('WXAgg')
      
      # Create a Stratey
      class TestStrategy(bt.Strategy):
          def __init__(self):
              self.p.tickers = dict()
              self.p.tickers['4H'] = -1
              pass
      
          def logic4Hour(self):
              print(f"Time: {self.datas[1].datetime.datetime(0)}")
              pass
      
          def next(self):
              if self.datas[1].close.idx != self.p.tickers['4H']:
                  # new 4H bar
                  self.p.tickers['4H'] = self.datas[1].close.idx
                  self.logic4Hour()
              return
      
      
      if __name__ == '__main__':
          # Create a cerebro entity
      
          cerebro = bt.Cerebro()
      
          # Add a strategy
          cerebro.addstrategy(TestStrategy)
      
          # Load CBoe data from disk
          dataframe = pandas.read_csv('C:\\Users\\dengz\\Desktop\\cboedata\\filtered_2018_Aug_Nov.csv',
                                      usecols=['quote_datetime', 'open', 'high', 'low', 'close', 'trade_volume'],
                                      index_col=0, engine='c', parse_dates=True, low_memory=True)
      
      
          # Convert pandas' data into backtrader format
          # Organizing the columns OLCHV
          data = bt.feeds.PandasDirectData(
              dataname = dataframe,
              open = 1,
              close = 4,
              high = 2,
              low = 3,
              volume = 5,
              openinterest = -1,
              timeframe=bt.TimeFrame.Minutes
          )
      
          # Feed the converted data to cerebro & execute resample
          cerebro.adddata(data, name='1min').plotinfo.plot = False #0
          cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=240, name='4H').plotinfo.plot = True #4 (new)
      
          # Set our desired cash start
          cerebro.broker.setcash(10000000000)
      
          # Execute cerebro.addstrategy(TestStrategy)
          cerebro.run()
          cerebro.plot(style='candlestick', barup='green')
      
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors