Write a Python program to track and plot stock market trends using Matplotlib.
- User
Write a Python program to track and plot stock market trends using Matplotlib.
Assistant
The user wants a Python program to track and plot stock market trends using Matplotlib. This implies several requirements:
- Data Source: Where do we get stock data?
yfinanceis the standard and easiest library for this in Python. - Data Manipulation:
pandasis essential for handling the time series data. - Visualization:
matplotlibis specifically requested for plotting. - Functionality: The program should probably allow the user to specify a stock ticker (e.g., AAPL) and a date range.
- Analysis (Optional but good): Calculating moving averages (SMA) is a standard "trend" analysis technique.
Plan:
-
Import necessary libraries:
yfinance(for data)matplotlib.pyplot(for plotting)pandas(usually implicit with yfinance, but good to keep in mind)datetime(for handling dates)
-
Define a function to fetch data:
- Input: Ticker symbol, start date, end date.
- Output: A Pandas DataFrame.
-
Define a function for analysis (Trend identification):
- Simple Moving Averages (SMA) are great for visualization. Let's add a 20-day and 50-day SMA.
-
Define the plotting function:
- Create a figure.
- Plot the Closing Price.
- Plot the Moving Averages.
- Add labels, title, and legend.
- Maybe add volume as a subplot? (Keep it simple for now, maybe just price + MA is enough for a basic request, but adding volume makes it look more "stock market-y"). Let's stick to Price + MAs on one chart to keep code readable, perhaps add Volume if it doesn't clutter too much. Decision: Let's do Price + Moving Averages on the main chart.
-
Main execution block:
- Set a specific stock (e.g., Apple 'AAPL').
- Set dates.
- Call the functions.
Drafting the Code (Mental or Scratchpad):
import yfinance as yf import matplotlib.pyplot as plt def plot_stock(ticker, start, end): data = yf.download(ticker, start=start, end=end) # Calculate Moving Averages data['SMA20'] = data['Close'].rolling(window=20).mean() data['SMA50'] = data['Close'].rolling(window=50).mean() plt.figure(figsize=(10,5)) plt.plot(data.index, data['Close'], label='Close Price') plt.plot(data.index, data['SMA20'], label='20 Day SMA') plt.plot(data.index, data['SMA50'], label='50 Day SMA') plt.title(f"{ticker} Stock Trend") plt.legend() plt.show()Refining:
- Issue:
yfinancemight not be installed by default. I need to mentionpip install yfinance pandas matplotlib. - Styling: Matplotlib defaults are a bit dull. I can make it look slightly better (grid, maybe specific colors for lines).
- Robustness: Check if data is empty.
Revised Plan:
- Prerequisites: State clearly what libraries are needed.
- Code Structure:
- Imports.
- Function
analyze_stock(ticker, start_date). - Download data.
- Compute 20-day and 50-day Simple Moving Averages (standard trends).
- Plot the 'Adj Close' (Adjusted Close is better than Close for historical accuracy due to dividends/splits).
- Format the plot (Grid, Title, Labels).
- Show plot.
- Example Usage: Run it for AAPL.
Self-Correction during drafting: The user asked for "trends". Just plotting price is plotting history. To show "trends", technical indicators like Moving Averages are the standard way to visualize momentum. I will include those.
Let's write the actual response. I will provide a complete script that allows the user to change the ticker symbol at the bottom.
Code specifics:
yf.downloadreturns a DataFrame.rolling().mean()for trends.plt.subplotsis often cleaner than globalpltinterface, though global is easier for beginners. I'll stick to standardpltfor simplicity unless I need multiple subplots (like volume). I'll stick to one subplot for price/trend to keep it focused.
Final Output Generation:
- Intro.
pip installcommand.- Python code block.
- Explanation of what the code does. Here is a complete Python program to track and plot stock market trends.
We will use the
yfinancelibrary to fetch historical stock data from Yahoo Finance (which is free) andmatplotlibto visualize the trends. We will also calculate Simple Moving Averages (SMA) to help identify the trend direction.Prerequisites
You will need to install the necessary libraries via your terminal/command prompt:
pip install yfinance matplotlib pandasThe Python Program
Save this code in a file named
stock_tracker.pyand run it.import matplotlib.pyplot as plt import yfinance as yf import datetime def track_stock_trend(ticker, start_date): """ Fetches stock data and plots the closing price along with 20-day and 50-day Moving Averages. """ # 1. Fetch Data from Yahoo Finance print(f"Fetching data for {ticker}...") # auto_adjust=True accounts for dividends and splits data = yf.download(ticker, start=start_date, end=datetime.date.today(), auto_adjust=True) if data.empty: print("No data found. Check the ticker symbol.") return # 2. Calculate Trends (Moving Averages) # SMA = Simple Moving Average data['SMA_20'] = data['Close'].rolling(window=20).mean() data['SMA_50'] = data['Close'].rolling(window=50).mean() # 3. Plotting with Matplotlib plt.figure(figsize=(12, 6)) # Set figure size # Plot the Closing Price plt.plot(data.index, data['Close'], label='Closing Price', color='black', linewidth=1.5, alpha=0.8) # Plot the Moving Averages plt.plot(data.index, data['SMA_20'], label='20-Day SMA (Short Term)', color='blue', linestyle='--') plt.plot(data.index, data['SMA_50'], label='50-Day SMA (Long Term)', color='orange', linestyle='--') # 4. Formatting the Chart plt.title(f"{ticker} Stock Price Trend", fontsize=16) plt.xlabel("Date", fontsize=12) plt.ylabel("Price (USD)", fontsize=12) plt.legend(loc='upper left') # Show legend plt.grid(True, linestyle=':', alpha=0.6) # Add a grid for readability # Highlight the most recent price current_price = data['Close'].iloc[-1] plt.annotate(f"${current_price:.2f}", xy=(data.index[-1], current_price), xytext=(10, 0), textcoords='offset points', fontweight='bold', color='black') # Show the plot plt.tight_layout() plt.show() # --- Main Execution --- if __name__ == "__main__": # Define the stock you want to track (e.g., AAPL, GOOGL, TSLA) STOCK_TICKER = "AAPL" # Define how far back you want to look (e.g., Jan 1st, 2023) START_DATE = "2023-01-01" track_stock_trend(STOCK_TICKER, START_DATE)How the Code Works
-
Data Fetching (
yfinance):yf.download()grabs the historical Open, High, Low, Close, and Volume (OHLCV) data for the specific ticker.- We use
auto_adjust=Trueso the price reflects dividends and stock splits, giving a truer picture of the stock's value over time.
-
Trend Calculation:
- We calculate the Simple Moving Average (SMA).
- 20-Day SMA: reacts quickly to price changes (Short-term trend).
- 50-Day SMA: reacts slowly (Long-term trend).
- Trading Logic: When the Blue line crosses above the Orange line, it is often considered a "Golden Cross" (Bullish signal).
-
Plotting (
matplotlib):plt.figure(figsize=(12,6))creates a wide chart window.- We plot the Date (index) on the X-axis and Price on the Y-axis.
- We add a grid and a legend to make it readable.
How to Customize It
- Change the Stock: Change
STOCK_TICKER = "MSFT"for Microsoft or"TSLA"for Tesla. - Change the Timeframe: Change
START_DATEto"2022-01-01"to see a 2-year trend.
- Data Source: Where do we get stock data?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.