SMA vs. EMA
SMA and EMA are both commonly-used trend indicators. SMA gives equal weight to all data points, while EMA applies more weight to recent data points. You have some Google stock price data and want to decide on a moving average indicator to use. You plan to calculate both the SMA and EMA with the same lookback period 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 50-day SMA of the
Close
price and save it in a new columnSMA
. - Calculate a 50-day EMA of the
Close
price and save it in a new columnEMA
. - Plot the
SMA
andEMA
together with theClose
price.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Calculate the SMA
stock_data['SMA'] = ____(stock_data['____'], ____)
# Calculate the EMA
stock_data['EMA'] = ____(stock_data['____'], ____)
# Plot the SMA, EMA with price
____(stock_data['____'], label='SMA')
____(stock_data['____'], label='EMA')
____(stock_data['____'], label='Close')
# Customize and show the plot
plt.legend()
plt.title('SMA vs EMA')
plt.show()