How to skip some data bars when starting back testing using BackTrader
Daily Tasks last edited by
I am trying to calculate gap up or gap down by comparing highs and lows of two previous bars.
if d.low[-1] > d.high: print(d.params.name, d.datetime.date(-1), "yesterday's low : ", d.low[-1], d.datetime.date(0), "today's high : ", d.high, "gap down") self.gap[d.params.name] = -1 elif d.high[-1] < d.low: print(d.params.name, d.datetime.date(-1), "yesterday's high : ", d.high[-1], d.datetime.date(0), "today's low : ", d.low, "gap up") self.gap[d.params.name] = 1 else: self.gap[d.params.name] = 0
However bar -2 is a bar from the future, that is today's bar.
ADANIPORTS 2022-01-31 720.8499755859375 #bar -2 ADANIPORTS 2020-04-07 248.10000610351562 # bar -1 ADANIPORTS 2020-04-08 250.85000610351562 # bar 0 gap down : ADANIPORTS 2020-04-08 day before's low : 714.5499877929688 should be higher than yesterday's high : 255.85000610351562
ASIANPAINT 2022-01-31 yesterday's low : 3140.0 2020-04-07 today's high : 1635.0 gap down
I would like to know how what is the best way to start backtesting so that -2 bars refer to historical bar instead of a bar in the future.
@daily-tasks -2 refer to historical bar, not a bar in the future.
You may want to read the basic concepts of Backtrader :
The platform consider the last set item (before the current live get/set point) to be -1. As such comparing the current close to the previous close is a 0 vs -1 thing. In a strategy, for example:
I may be wrong, but I have, according to the previous questions you had, the feeling that you have not had a look at the documentation. My apologies if it is not the case.
If it is the case, I strongly encourage you to read the documentation. It will take a bit of time, but it will be quicker that discovering how to use the software by going from problem to problem, and far less expensive than basing an investment decision on backtesting results based on a wrong usage of the software.
Daily Tasks last edited by
@emr thank you for your prompt response.
I have read the documentation.
Unfortunately I was indeed getting a bar from the future date as shown in log 1 and log 2. The first line is close price of
[-2]then the next line prints the close price of
2020-04-07referenced by index
Since then, I have been able to fix this issue by adding the following to the beginning of the
if len(self) < 3: return
This way when at least three bars have been processed, I am able to access previous bars using index [-2] and [-1].
If you have the time could you also look at the other issue i have raised regarding stop order closing at the close of the candle instead of the specified stop price in the order.
This is causing my back test to lose more money than expected.
Thank you for taking the time to help me.
run-out last edited by
@daily-tasks Check your data sorting and eroneous entries. Backtrader expects sorted data.