I have a function that calculates the RSI indicator from OHLC values stored in a pandas datafram. The function is as follows:
def rsi_indicator(df):
diff = df.close.diff().values
gains = diff
losses = -diff
with np.errstate(invalid='ignore'):
gains[(gains < 0) | np.isnan(gains)] = 0.0
losses[(losses <= 0) | np.isnan(losses)] = 1e-10 # we don't want divide by zero/NaN
n = 14
m = (n - 1) / n
ni = 1 / n
try:
g = gains[n] = np.nanmean(gains[:n])
l = losses[n] = np.nanmean(losses[:n])
except IndexError as e:
????
gains[:n] = losses[:n] = np.nan
for i, v in enumerate(gains[n:], n):
g = gains[i] = ni * v m * g
for i, v in enumerate(losses[n:], n):
l = losses[i] = ni * v m * l
rs = gains / losses
rsi = 100 - (100 / (1 rs))
return rsi
I am looping through few dataframes to calculate the RSI but whenever I have a dataframe with no enough records to calculate the indicator values I get an IndexError:
IndexError: index 14 is out of bounds for axis 0 with size 13
How can I continue using the next item in the loop list when I get such an error?
I added some ???? where I need the code to fix this issue, otherwise feel free to change the code however you like.
CodePudding user response:
It is generally a bad practice to suppress errors or exceptions without handling them, but this can be easily done like this:
# block raising an exception
except:
pass # doing nothing on exception```
This can obviously be used in any other control statement, such as a loop:
for i in xrange(0,960):
try:
... run your code
except:
pass