Fundamentals 3 min read

Plotting 5-Day and 20-Day Moving Averages of Stock Prices with Python

This tutorial demonstrates how to fetch historical stock data with pandas_datareader, calculate 5‑day and 20‑day moving averages using pandas, and visualize the price series together with these averages in a Matplotlib chart to illustrate simple trading‑strategy concepts.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Plotting 5-Day and 20-Day Moving Averages of Stock Prices with Python

The article explains how to use Python to draw the 5‑day and 20‑day moving averages of a stock price, noting that the 5‑day average is a short‑term trading threshold while the 20‑day average marks a medium‑term trend line, enabling simple strategy design.

import pandas as pd
import numpy as np
from pandas_datareader import data
import datetime
import matplotlib.pyplot as plt

After importing the required libraries, the script retrieves the last 100 days of price data for the Shanghai‑listed stock '601127.ss' from Yahoo Finance using data.DataReader, and displays the first few rows with price.head().

The fetched data (starting from 2021‑10‑08) is shown in a screenshot, confirming successful acquisition.

Moving averages are then added to the DataFrame:

price['ma5'] = price['Adj Close'].rolling(5).mean()
price['ma20'] = price['Adj Close'].rolling(20).mean()
price.tail()

The resulting DataFrame now contains the 5‑day and 20‑day average columns, as illustrated by another screenshot.

Finally, the script creates a Matplotlib figure to plot the adjusted closing price together with the two moving‑average lines:

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 generated chart clearly displays the price series and the two moving averages, allowing readers to visually assess the relationship between different periods and to devise moving‑average‑based trading strategies.

Disclaimer: This article is compiled from online sources; copyright belongs to the original author. Please contact us for removal or licensing requests.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

pandasfinancedata-visualizationmoving averagestock analysis
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.