#2 AlgoTrade Beginner's Course: Plotting Stocks Prices and Moving Averages with Python
Welcome to our beginner-friendly guide on using Python for stock market analysis! If you're new to coding, don't worry. We'll walk through each step slowly and explain everything you need to know.
We already know how to download stock prices with Yahoo Finance. So now it’s time to learn how to plot stock data and understand two important concepts: the Simple Moving Average (SMA) and the Exponential Moving Average (EMA).
Setting Up Your Environment
Once you have installed Python, we'll use a tool called 'pip' (Python's package installer) to install Matplotlib, a library for creating charts and graphs. Open your command prompt or terminal and type:
pip install matplotlib
Plotting Stock Data with Matplotlib
Matplotlib is a library in Python used for creating visualizations. We'll use it to plot the stock data we have.
First, let's understand the code you provided. It fetches stock data for Microsoft (MSFT) from January 1, 2021, to August 1, 2021. Now, let's plot this data:
import matplotlib.pyplot as plt
# Assuming 'stock_data' contains the fetched MSFT data
plt.figure(figsize=(10, 5)) # This creates a figure with a certain size
plt.plot(stock_data, label='MSFT Close Price') # This plots the stock data
plt.title('MSFT Stock Price') # Adds a title to the plot
plt.xlabel('Date') # Labels the x-axis as 'Date'
plt.ylabel('Price') # Labels the y-axis as 'Price'
plt.legend() # Displays a legend
plt.show() # Shows the plot
(the code for downloading MSFT stock price was shown in #2 Chapter)
It should look like this:
Let’s try to plot some additional data to see some relationships in the stock price over time.
What is SMA (Simple Moving Average)?
The Simple Moving Average (SMA) is a calculation that takes the average of a selected range of prices, usually closing prices, over a set number of days. For example, a 20-day SMA would add up the closing prices for the last 20 days and divide by 20.
Calculating SMA in Python
To calculate SMA, we'll write a simple function. Don't worry if you don't understand functions yet; think of them as a set of instructions that we can use repeatedly.
def calculate_sma(data, window):
return data.rolling(window=window).mean()
# Calculate 20-day SMA
sma_20 = calculate_sma(stock_data, 20)
plt.plot(stock_data, label='MSFT Close Price')
plt.plot(sma_20, label='20-day SMA')
plt.legend()
plt.show()
Understanding the SMA Calculation
The Simple Moving Average (SMA) is a method used in financial analysis to smooth out price data by creating an average price that is updated over a specific period of time, like 10 days, 20 days, etc.
The calculate_sma
Function
def calculate_sma(data, window):
return data.rolling(window=window).mean()
This function takes two arguments:
data
: This is the series of stock prices. In your case, it's the closing prices of Microsoft stock.window
: This is the number of periods over which you want to calculate the average. For example, if you want a 20-day SMA,window
will be 20.
Breaking Down the Function
data.rolling(window=window)
: This line is where the magic happens. Therolling
method is a feature provided by pandas (a Python library for data manipulation) that allows us to apply a function (in this case, calculating the mean) over a rolling window of a specified size.Think of it as a sliding window that moves across your data. At each position, it covers
window
number of data points.For example, if
window=20
, the rolling method will look at the first 20 data points first, then move one step forward and look at the next 20 data points (from the 2nd to the 21st), and so on.
.mean()
: This calculates the average (mean) of the data points in each window.So, for each set of 20 data points (in our example), it sums them up and divides by 20, giving the average of those 20 days.
Example
Let's say you have closing stock prices for 5 days: [100, 105, 110, 115, 120], and you want to calculate a 3-day SMA.
The first window covers [100, 105, 110]. The average is (100 + 105 + 110) / 3 = 105.
The window then moves one step forward to cover [105, 110, 115]. The average is (105 + 110 + 115) / 3 = 110.
Finally, it moves again to cover [110, 115, 120]. The average is (110 + 115 + 120) / 3 = 115.
So, the 3-day SMA for this data would be [105, 110, 115].
Conclusion
The calculate_sma
function is a concise and efficient way to calculate the SMA over a given window. It's a powerful tool in financial analysis for understanding trends by smoothing out short-term fluctuations in price data.
So, executing this above code to calculate 20-day SMA for MSFT stock price, you should see the plot as follows: stock price and it’s 20-day SMA:
Ok, so we know a lot already, let’s move to the more advanced calculations.
What is the EMA (Exponential Moving Average)?
EMA is similar to SMA but gives more weight to recent prices. This means it reacts more quickly to price changes than SMA.
Calculating EMA in Python
Calculating EMA is a bit more complex, but Python makes it easy for us. Here's how you do it:
def calculate_ema(data, span):
return data.ewm(span=span, adjust=False).mean()
# Calculate 20-day EMA
ema_20 = calculate_ema(stock_data, 20)
plt.plot(stock_data, label='MSFT Close Price')
plt.plot(ema_20, label='20-day EMA')
plt.legend()
plt.show()
Again, plot of 20-day EMA looks as:
Combining SMA and EMA on a Single Plot
Let's put both SMA and EMA on the same plot to compare them:
plt.figure(figsize=(12, 6))
plt.plot(stock_data, label='MSFT Close Price', alpha=0.5)
plt.plot(sma_20, label='20-day SMA', alpha=0.8)
plt.plot(ema_20, label='20-day EMA', alpha=0.8)
plt.title('MSFT Stock Price with SMA and EMA')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()
And output as:
You may play with different stocks and different variables calculated based on the price of the stock.
Conclusion
Congratulations! You've just learned how to plot stock data and calculate important indicators like SMA and EMA using Python. These tools are essential for analyzing stock market trends. Remember, practice is key in coding, so feel free to experiment with the code and try plotting different stocks or changing the SMA and EMA periods.
In our next article, we'll explore how to store data locally on the hard drive with the use of Arctic DB. Stay tuned!