-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
-
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
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 1 reply
-
any suggestions?
Beta Was this translation helpful? Give feedback.
All reactions
-
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(...
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1