Fundamentals 3 min read

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.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Plot 5‑Day and 20‑Day Moving Averages for Stock Prices with Python

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 plt
end_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.

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.

Matplotlibpandasdata-visualizationmoving averagestock analysis
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.