Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Look Ahead Bias question #1161

alexmulo started this conversation in General
Jul 21, 2024 · 1 comments · 1 reply
Discussion options

Dear all,
I am testing several strategies using the backtesting library. Basically, if I would do a backtest using pandas I would shift the signal of 1 day to avoid the look ahead bias issue. Does the backtesting library do it from its own or should I introduce it like in this example?

class BollingerBandsStrategy(Strategy):
 n = 40 # Period for Bollinger Bands
 k = 2 # Number of standard deviations
 def init(self):
 # Compute Bollinger Bands using talib
 self.upper_band, self.middle_band, self.lower_band = self.I(
 tb.BBANDS, self.data['Adj Close'], timeperiod=self.n, nbdevup=self.k, nbdevdn=self.k
 )
 
 def next(self):
 if len(self.data) < self.n:
 return # Not enough data to make a decision
 close = self.data['Adj Close'][-1]
 prev_close = self.data['Adj Close'][-2]
 upper = self.upper_band[-2]
 lower = self.lower_band[-2]
 if not self.position:
 # Buy signal: previous close crosses above the previous lower Bollinger Band
 if prev_close < lower and close > lower:
 self.buy()
 else:
 # Sell signal: previous close crosses below the previous upper Bollinger Band
 if prev_close > upper and close < upper:
 self.position.close()

Thanks

You must be logged in to vote

Replies: 1 comment 1 reply

Comment options

any suggestions?

You must be logged in to vote
1 reply
Comment options

The algorithm will open (self.buy()) and close (self.position.close()) the position on the next candle - this eliminates looking ahead.
But... you need to be careful with the data you transmit ['Adj Close'].
If you need the value on the current candle, then the index is -1, and the deal will already be opened on the next candle.
To get a good understanding, try studying the backtesting charts to see if they match the logic of your strategy.
Снимок1
orange and blue line - indicators self.I(...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /