Here is the part of the code that is specifying the backtest. I already have a ‘Signal’ column in another dataframe ‘data’, but that isnt the problem here.
temp = yf.download(
symb,
interval=interval,
period=period
)
temp.reset_index(inplace=True)
print(temp.columns)
class MyStrategy(Strategy):
stop_factor = 0.02 # stop loss factor
take_profit_factor = 0.04 # take profit factor for 1:2 risk-reward ratio
def init(self):
# Set up signals
self.signal = self.data['signals']
def next(self):
# If the signal is a buy, we want to buy
if self.signal == 1:
self.buy(size=1, stop=self.data.close[-1] * (1 - self.stop_factor), takeprofit=self.data.close[-1] * (1 + self.take_profit_factor))
# If the signal is a sell, we want to sell
elif self.signal == -1:
self.sell(size=1, stop=self.data.close[-1] * (1 + self.stop_factor), takeprofit=self.data.close[-1] * (1 - self.take_profit_factor))
# Backtest setup
bt = Backtest(temp, MyStrategy, cash=10000, commission=0.002)
stats = bt.run()
# Print the backtest results
print(stats)
I have tried to change the index to a new ‘Candle_No’ column and tried to reset the index but nothing has worked.
This is the error that actually shows up:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/multi.py in _convert_can_do_setop(self, other)
3853 try:
-> 3854 other = MultiIndex.from_tuples(other, names=self.names)
3855 except (ValueError, TypeError) as err:
8 frames
ValueError: Length of names must match number of levels in MultiIndex.
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/multi.py in _convert_can_do_setop(self, other)
3856 # ValueError raised by tuples_to_object_array if we
3857 # have non-object dtype
-> 3858 raise TypeError(msg) from err
3859 else:
3860 result_names = get_unanimous_names(self, other)
TypeError: other must be a MultiIndex or a list of tuples
New contributor
user28679678 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.