Calculate and plot two EMAs
A 12-period EMA and 26-period EMA are two moving averages used in calculating a more complex indicator called MACD (Moving Average Convergence Divergence). The MACD turns two EMAs into a momentum indicator by subtracting the longer EMA from the shorter one. Before learning more about MACD, you want to get familiar with its components first. You decide to calculate two EMAs using the Google daily stock prices and plot them in one chart.
The daily historical price data of the Google stock has been loaded in stock_data
. Also, talib
has been imported for you, and matplotlib.pyplot
has been imported as plt
.
This exercise is part of the course
Financial Trading in Python
Exercise instructions
- Calculate a 12-day EMA of the
Close
price and save it in a new columnEMA_12
. - Calculate a 26-day EMA of the
Close
price and save it in a new columnEMA_26
. - Plot the 12-day EMA and 26-day EMA together with the
Close
price.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Calculate 12-day EMA
stock_data['EMA_12'] = ____(stock_data['____'], ____)
# Calculate 26-day EMA
stock_data['EMA_26'] = ____
# Plot the EMAs with price
____(stock_data['____'], label='EMA_12')
____(stock_data['____'], label='EMA_26')
____(stock_data['____'], label='Close')
# Customize and show the plot
plt.legend()
plt.title('EMAs')
plt.show()