Implementation of the relative strength indicator

Now, let's implement and plot a relative strength indicator on our dataset:

import statistics as stats

time_period = 20 # look back period to compute gains & losses

gain_history = [] # history of gains over look back period (0 if no gain, magnitude of gain if gain)
loss_history = [] # history of losses over look back period (0 if no loss, magnitude of loss if loss)
avg_gain_values = [] # track avg gains for visualization purposes
avg_loss_values = [] # track avg losses for visualization purposes

rsi_values = [] # track computed RSI values

last_price = 0 # current_price - last_price > 0 => gain. current_price - last_price < 0 => loss.

for close_price in close:
if last_price == 0:
last_price = close_price

gain_history.append(max(0, close_price - last_price))
loss_history.append(max(0, last_price - close_price))
last_price = close_price

if len(gain_history) > time_period: # maximum observations is equal to lookback period
del (gain_history[0])
del (loss_history[0])

avg_gain = stats.mean(gain_history) # average gain over lookback period
avg_loss = stats.mean(loss_history) # average loss over lookback period
avg_gain_values.append(avg_gain)
avg_loss_values.append(avg_loss)

rs = 0
if avg_loss > 0: # to avoid division by 0, which is undefined
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
rsi_values.append(rsi)

In the preceding code, the following applies:

  • We have used 20 days as our time period over which we computed the average gains and losses and then normalized it to be between 0 and 100 based on our formula for values.
  • For our dataset where prices have been steadily rising, it is obvious that the values are consistently over 50% or more.

Now, let's look at the code to visualize the final signal as well as the components involved:

goog_data = goog_data.assign(ClosePrice=pd.Series(close, index=goog_data.index))
goog_data = goog_data.assign(RelativeStrengthAvgGainOver20Days=pd.Series(avg_gain_values, index=goog_data.index))
goog_data = goog_data.assign(RelativeStrengthAvgLossOver20Days=pd.Series(avg_loss_values, index=goog_data.index))
goog_data = goog_data.assign(RelativeStrengthIndicatorOver20Days=pd.Series(rsi_values, index=goog_data.index))
close_price = goog_data['ClosePrice']
rs_gain = goog_data['RelativeStrengthAvgGainOver20Days']
rs_loss = goog_data['RelativeStrengthAvgLossOver20Days']
rsi = goog_data['RelativeStrengthIndicatorOver20Days']

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(311, ylabel='Google price in $')
close_price.plot(ax=ax1, color='black', lw=2., legend=True)
ax2 = fig.add_subplot(312, ylabel='RS')
rs_gain.plot(ax=ax2, color='g', lw=2., legend=True)
rs_loss.plot(ax=ax2, color='r', lw=2., legend=True)
ax3 = fig.add_subplot(313, ylabel='RSI')
rsi.plot(ax=ax3, color='b', lw=2., legend=True)
plt.show()

The preceding code will return the following output. Let's have a look at the plot:

The first observation we can make from our analysis of the RSI signal applied to our GOOGLE dataset is that the AverageGain over our time frame of 20 days more often than not exceeds the AverageLoss over the same time frame, which intuitively makes sense because Google has been a very successful stock, increasing in value more or less consistently. Based on that, the RSI indicator also stays above 50% for the majority of the lifetime of the stock, again reflecting the continued gains in the Google stock over the course of its lifetime.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset