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.
NumPy prints this warning when you try to do something like divide infinity by infinity:
What to do depends on the specifics of the situation. E.g. there might be situations where this happens as part of some optimization algorithm that later filters out any results that gave
nan
, so all you might want to do is get rid of the warning (there are many questions about how to do this on StackOverflow, e.g. How to avoid "RuntimeWarning: invalid value encountered in divide" in NumPy?). In other situations it could indicate that something more drastic is wrong.If you don't know whether the warning indicates that something is wrong, it's probably best to "convert warnings into errors" temporarily (convert numpy warnings to errors) so that an exception is thrown whenever this happens and you get a full traceback, including which line of your own script it resulted from.