I'm trying to backtest a trading strategy using the bt
library by using one of the examples presented on their web page (I'm not retrieving the data as presented due to the bt.get()
function not working. But here is the code that I'm using (I know some of the df
handling is messy but it gets the job done):
import bt, pandas as pd, yfinance as yf, datetime as dt, os, requests
from pandas_datareader import data as pdr
yf.pdr_override
ticks = ['AAPL','MSFT','C','GS','GE']
data = tdaph(ticks[0])
data = data.set_index('datetime')
data[ticks[0]] = data['close']
data = data.drop('close',axis=1)
for i in range(1,len(ticks)):
aa = tdaph(ticks[i])
aa = aa.set_index('datetime')
data[ticks[i]] = aa['close']
print('done')
data.index = pd.to_datetime(data.index)
data = data.astype('float')
sma = data.rolling(50).mean()
class SelectWhere(bt.Algo):
def __init__(self, signal):
self.signal = signal
def __call__(self, target):
if target.now in self.signal.index:
sig = self.signal.loc[target.now]
selected = list(sig.index[sig])
target.temp['selected'] = selected
print('hecho')
s = bt.Strategy('above50sma', [SelectWhere(data > sma),
bt.algos.WeighEqually(),
bt.algos.Rebalance()])
print('strat hecha')
t = bt.Backtest(strategy=s,data=data)
print('backtest hecho')
res = bt.run(t)
But when running the bt.run()
function, I'm getting the following RuntimeWarning message:
Warning (from warnings module):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/ffn/core.py", line 2299
res = np.divide(er.mean(), std)
RuntimeWarning: invalid value encountered in true_divide
Any thoughts on what might be the problem? Thank you to anyone in advance.