How to Plot 5‑Day and 20‑Day Moving Averages for Stock Prices with Python
This tutorial shows how to fetch historical stock data using Python, compute 5‑day and 20‑day moving averages with pandas, and visualize them with matplotlib to support short‑term and medium‑term trading strategy design.
Using Python, you can fetch historical stock data, compute 5‑day and 20‑day moving averages, and visualize them to aid short‑term and medium‑term trading decisions.
First, import pandas, numpy, pandas_datareader, datetime, and matplotlib.pyplot. Then retrieve the last 100 days of price data for stock 601127.SS from Yahoo Finance.
import pandas as pd
import numpy as np
from pandas_datareader import data
import datetime
import matplotlib.pyplot as pltend_date = datetime.date.today()
start_date = end_date - datetime.timedelta(days=100)
price = data.DataReader('601127.ss','yahoo', start_date, end_date)
price.head()Calculate the moving averages:
price['ma5'] = price['Adj Close'].rolling(5).mean()
price['ma20'] = price['Adj Close'].rolling(20).mean()
price.tail()Plot the adjusted close price together with the two moving averages:
fig = plt.figure(figsize=(16,9))
ax1 = fig.add_subplot(111, ylabel='Price')
price['Adj Close'].plot(ax=ax1, color='g', lw=2, legend=True)
price.ma5.plot(ax=ax1, color='r', lw=2, legend=True)
price.ma20.plot(ax=ax1, color='b', lw=2, legend=True)
plt.grid()
plt.show()The resulting chart clearly shows the price line along with the 5‑day (red) and 20‑day (blue) moving averages, providing a visual basis for designing simple moving‑average trading strategies.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
