Implementation of momentum

Now, let's have a look at the code that demonstrates the implementation of momentum:

time_period = 20 # how far to look back to find reference price to compute momentum

history = [] # history of observed prices to use in momentum calculation
mom_values = [] # track momentum values for visualization purposes

for close_price in close:
history.append(close_price)
if len(history) > time_period: # history is at most 'time_period' number of observations
del (history[0])

mom = close_price - history[0]
mom_values.append(mom)

This maintains a list history of past prices and, at each new observation, computes the momentum to be the difference between the current price and the price time_period days ago, which, in this case, is 20 days:

goog_data = goog_data.assign(ClosePrice=pd.Series(close, index=goog_data.index))
goog_data = goog_data.assign(MomentumFromPrice20DaysAgo=pd.Series(mom_values, index=goog_data.index))
close_price = goog_data['ClosePrice']
mom = goog_data['MomentumFromPrice20DaysAgo']

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(211, ylabel='Google price in $')
close_price.plot(ax=ax1, color='g', lw=2., legend=True)
ax2 = fig.add_subplot(212, ylabel='Momentum in $')
mom.plot(ax=ax2, 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 plot for momentum shows us the following:

  • Momentum values peak when the stock price changes by a large amount as compared to the price 20 days ago.
  • Here, most momentum values are positive, mainly because, as we discussed in the previous section, Google stock has been increasing in value over the course of its lifetime and has large upward momentum values from time to time.
  • During the brief periods where the stock prices drop in value, we can observe negative momentum values.

In this section, we learned how to create trading signals based on technical analysis. In the next section, we will learn how to implement advanced concepts, such as seasonality, in trading instruments.

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

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