How to Calculate the Moving Average with Pyhton
In this tutorial, we will cover how to calculate the Simple Moving Average (MA) and the Exponential Moving Average (EMA) of a Time Series using the Pandas library in Python.
We will also take a brief look at what the Simple Moving Average and the Exponential Aveareg is.
What is the Moving Average?
The Moving Average is calcualted to identify the trend direction of a stock.
- The Moving Average can be used to determine the support and restance levels.
- Often categorized as a lagging indicator, as it is trendfollowing.
- The longer period used, the greater the lag.
- The 50-day and 200-day Moving Averages are considered by many the as important trading signals.
- The Simple Moving Average is taking the arithmetic mean over a specific number of days.
- The Exponential Moving Average is a weighted average with more importance in recent days. This makes it a more responsive indicator.
Watch how to calculate the Moving Average with Python
See the video to see how it can be done using the Python library pandas or see the code below.
Step 1: Read some Financial Historic Time Series Stock Prices
We will use Pandas DataReader to read some historic stock prices. See this tutorial for details.
import pandas_datareader as pdr from datetime import datetime ticker = "AAPL" start = datetime(2019, 1, 1) data = pdr.get_data_yahoo(ticker, start) # You can also add end-date print(data.head())
Resulting in this.
High Low Open Close Volume Adj Close Date 2019-01-02 39.712502 38.557499 38.722500 39.480000 148158800.0 38.505024 2019-01-03 36.430000 35.500000 35.994999 35.547501 365248800.0 34.669640 2019-01-04 37.137501 35.950001 36.132500 37.064999 234428400.0 36.149662 2019-01-07 37.207500 36.474998 37.174999 36.982498 219111200.0 36.069202 2019-01-08 37.955002 37.130001 37.389999 37.687500 164101200.0 36.756794
Step 2: Calculate the Simple Moving Average with Python and Pandas
Calculating the Simple Moving Average (MA) of the data can be done using the rolling and mean methods.
data['MA10'] = data['Close'].rolling(10).mean()
Where here we calculate the Simple Moving Average of 10 days. You can change it to fit your needs.
Step 3: Calculate the Exponential Moving Average with Python and Pandas
It is a bit more involved to calculate the Exponential Moving Average.
data['EMA10'] = data['Close'].ewm(span=10, adjust=False).mean()
There you need to set the span and adjust it to False. This is needed to get the same numbers as on Yahoo! Finance.
Bonus: Visualize the result
If you want to see the data on a chart you can use the following code.
import pandas_datareader as pdr from datetime import datetime import matplotlib.pyplot as plt data = pdr.get_data_yahoo('AAPL', datetime(2021,1,1)) data['MA50'] = data['Close'].rolling(50).mean() data['EMA50'] = data['Close'].ewm(span=50, adjust=False).mean() data[['Close', 'MA50', 'EMA50']].plot(figsize=(10,8))
This should result in a chart similar to this one.
Want to learn more?
This is part of the course of Master Technical Analysis with pandas.
In the next lesson you will learn about Calculating MACD with Pandas DataFrames.
12% Investment Solution
Would you like to get 12% in return of your investments?
D. A. Carter promises and shows how his simple investment strategy will deliver that in the book The 12% Solution. The book shows how to test this statement by using backtesting.
Did Carter find a strategy that will consistently beat the market?
Actually, it is not that hard to use Python to validate his calculations. But we can do better than that. If you want to work smarter than traditional investors then continue to read here.
Do you know what the 5 key success factors every programmer must have?
How is it possible that some people become programmer so fast?
While others struggle for years and still fail.
Not only do they learn python 10 times faster they solve complex problems with ease.
What separates them from the rest?
I identified these 5 success factors that every programmer must have to succeed:
- Collaboration: sharing your work with others and receiving help with any questions or challenges you may have.
- Networking: the ability to connect with the right people and leverage their knowledge, experience, and resources.
- Support: receive feedback on your work and ask questions without feeling intimidated or judged.
- Accountability: stay motivated and accountable to your learning goals by surrounding yourself with others who are also committed to learning Python.
- Feedback from the instructor: receiving feedback and support from an instructor with years of experience in the field.
I know how important these success factors are for growth and progress in mastering Python.
That is why I want to make them available to anyone struggling to learn or who just wants to improve faster.
With the Python Circle community, you can take advantage of 5 key success factors every programmer must have.
Be part of something bigger and join the Python Circle community.