Visualizing Stock Price Trends with Matplotlib

By: fyvo July 31, 2025 Python

Description

This Python script fetches historical stock data using yfinance and generates an interactive plot showing closing prices over time using Matplotlib. The plot includes a moving average for better trend visualization.

Code Snippet

import yfinance as yf
import matplotlib.pyplot as plt
import numpy as np

ticker = 'AAPL'
start_date = '2023-01-01'
end_date = '2023-10-27'

data = yf.download(ticker, start=start_date, end=end_date)

plt.figure(figsize=(12, 6))
plt.plot(data['Close'], label='Closing Price')

# Calculate and plot 50-day moving average
ma50 = data['Close'].rolling(window=50).mean()
plt.plot(ma50, label='50-Day MA')

plt.title(f'{ticker} Stock Price Trend ({start_date} - {end_date})')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid(True)
plt.show()

Discussion (0)