For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

Intraday resample issue

  • Before I dive into my question, I need to clarify that 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 does? timestamp for the 1st 4h
    period of the day (timestamped as 9:30am est)
    0_1558904716031_Inked1.jpg timestamp for the 2nd 4h
    period of the day (timestamped as 13:30/1:30pm est)

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

    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
        def logic4Hour(self):
            print(f"Time: {self.datas[1].datetime.datetime(0)}")
        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
    if __name__ == '__main__':
        # Create a cerebro entity
        cerebro = bt.Cerebro()
        # Add a strategy
        # 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,
        # 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
        # Execute cerebro.addstrategy(TestStrategy)
        cerebro.plot(style='candlestick', barup='green')

Log in to reply