Felix
Felix

Reputation: 1

MACD Strategy in Backtesting.py

Good afternoon, can anyone tell my why the following strategy is not generating signals? The RSI part works fine but I have problems with the MACD. I tried the logic on a normal data frame, it worked there and I think it has something to do with the backtesting.py library.

import ta
import pandas as pd
from backtesting import Backtest, Strategy
from backtesting.lib import crossover

class MACD_RSIStrategy(Strategy):
    def init(self):
        close = pd.Series(self.data.Close)
        rsi_indicator = ta.momentum.RSIIndicator(close, window=14)
        macd_indicator = ta.trend.MACD(close, 26, 12, 9, False)
        self.macd = macd_indicator.macd()
        self.signal = macd_indicator.macd_signal()
        self.rsi = self.I(rsi_indicator.rsi)
        self.macd = self.I(macd_indicator.macd)

    def next(self):
        if crossover(self.macd, self.signal) and self.rsi[-1] < 30:
            self.position.close()
            self.buy()
        elif crossover(self.signal, self.macd) and self.rsi[-1] > 70:
            self.position.close()
            self.sell()

Upvotes: 0

Views: 791

Answers (1)

jbf
jbf

Reputation: 1

This is because backtesting.py takes in a vector for result. Therefore, if your indicator is returning more than 1 vector, then you should modify it. I realised this when i was using pandas-ta, and a dataframe was returned. so it just takes the last column as a series (aka vector)

Upvotes: 0

Related Questions