Tuesday , December 1 2026
Real Stock Data Plotting using Matplotlib

Real Stock Data Plotting using Matplotlib

Updated: 28 November 2026Level: IntermediateReading time: about 10 minutesMatplotlib · pandas · yfinance

In this project you will download real historical stock prices and visualise them: closing price, moving averages and trading volume. It brings together pandas and Matplotlib on real data.

Prerequisites

Matplotlib basics and pandas.
pip install yfinance pandas matplotlib

Step 1: Download Prices

Example
import yfinance as yf
import matplotlib.pyplot as plt

df = yf.download('RELIANCE.NS', start='2024-01-01', end='2025-12-31', auto_adjust=True)
print(df.tail())

Explanation: yfinance fetches data from Yahoo Finance. .NS means the NSE (India). Use symbols like AAPL or MSFT for US stocks.

Note: yfinance is an unofficial tool; Yahoo can change or limit access. It is fine for learning, not for production or trading decisions. Recent versions may return columns with two levels (field and ticker); df['Close'] may then be a one-column DataFrame, and .squeeze() turns it into a Series.

Step 2: Plot the Closing Price

Example
close = df['Close'].squeeze()
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(close.index, close, label='Close')
ax.set_title('Reliance Industries - Closing Price')
ax.set_ylabel('Price (₹)')
ax.legend()
plt.show()

Step 3: Moving Averages

Example
ma50 = close.rolling(50).mean()
ma200 = close.rolling(200).mean()
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(close, label='Close', alpha=0.6)
ax.plot(ma50, label='50-day MA')
ax.plot(ma200, label='200-day MA')
ax.legend()
plt.show()

Explanation: A moving average is the mean of the last N days. It smooths daily noise so the trend is easier to see.

Step 4: Price and Volume Together

Example
vol = df['Volume'].squeeze()
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6), sharex=True,
                               gridspec_kw={'height_ratios': [3, 1]})
ax1.plot(close)
ax1.set_ylabel('Price')
ax2.bar(vol.index, vol, width=1)
ax2.set_ylabel('Volume')
fig.tight_layout()
plt.show()

Step 5: Daily Returns

Example
returns = close.pct_change().dropna() * 100
fig, ax = plt.subplots()
ax.hist(returns, bins=50)
ax.set_xlabel('Daily return (%)')
plt.show()
print(returns.describe().round(2))

Explanation: pct_change gives the % change from the previous day. The histogram shows how volatile the stock is.

Common Errors

Problem Cause and fix
Empty DataFrame Wrong ticker symbol, no internet, or Yahoo temporarily blocked the request.
KeyError: 'Close' or odd column names Print df.columns; newer yfinance returns MultiIndex columns.

Practice Exercises

  1. Compare two stocks on one chart after normalising both to start at 100.
  2. Mark the days when the 50-day MA crosses above the 200-day MA.

Interview Questions

Q: What is a moving average?
The average of the last N values, recalculated each day to smooth noise.

Summary

Download prices with yfinance, then plot close price, moving averages, volume and returns with Matplotlib. This is for learning, not financial advice.

Next: Back to Matplotlib series

About Machine Learning

Check Also

Exploratory Data Analysis (EDA) in Python: Step-by-Step Checklist

A step-by-step EDA checklist in pandas with tested outputs: shape, missing values, describe, value counts, groupby, correlations and charts.