Get startedGet started for free

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

View Course

Exercise instructions

  • Calculate a 50-day SMA of the Close price and save it in a new column SMA.
  • Calculate a 50-day EMA of the Close price and save it in a new column EMA.
  • Plot the SMA and EMA together with the Close 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()
Edit and Run Code