In this blog post, we’ll explore how to use Python to analyze the stock market. We’ll cover retrieving stock data, calculating simple moving averages, and visualizing the results.

Requirements

  1. Python 3.6 or higher
  2. Pandas (pip install pandas)
  3. Pandas-datareader (pip install pandas-datareader)
  4. Matplotlib (pip install matplotlib)

Retrieving Stock Data

We’ll use the pandas-datareader library to fetch historical stock data from Yahoo Finance. Let’s fetch the last two years of daily data for Microsoft (MSFT):

import pandas_datareader as pdr
import datetime as dt

ticker = "MSFT"
start_date = dt.datetime.now() - dt.timedelta(days=2 * 365)
end_date = dt.date.today()

df = pdr.get_data_yahoo(ticker, start_date, end_date)
print(df.head())

Calculating Simple Moving Averages

Next, we’ll calculate the 50-day and 200-day simple moving averages (SMA):

df['SMA50'] = df['Close'].rolling(window=50).mean()
df['SMA200'] = df['Close'].rolling(window=200).mean()

Visualizing the Results

Finally, let’s plot the stock prices and moving averages using matplotlib:

import matplotlib.pyplot as plt

plt.figure(figsize=(12, 6))
plt.plot(df['Close'], label='Close Price', alpha=0.5)
plt.plot(df['SMA50'], label='50-day SMA', linestyle='--')
plt.plot(df['SMA200'], label='200-day SMA', linestyle='-.')

plt.title('Microsoft (MSFT) Stock Prices with 50 and 200-day SMAs')
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.legend(loc='upper left')
plt.show()

With this, we’ve successfully used Python to retrieve stock data, calculate simple moving averages, and visualize the results. You can adapt this code to analyze other stocks or use different indicators as needed.

Happy trading!