"""
Stock Market Trend Tracker and Plotter
======================================
This Python program fetches historical stock data using the yfinance library
and plots trends using Matplotlib. It includes:
- Closing price line chart
- 50-day and 200-day moving averages (if sufficient data)
- Volume subplot
Requirements:
- pip install yfinance matplotlib pandas
Usage:
- Run the script
- Enter ticker symbol (e.g., AAPL, MSFT, TSLA)
- Enter start and end dates in YYYY-MM-DD format
- View the interactive plot
"""
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta
# Interactive user input with defaults
ticker = input("Enter stock ticker symbol (default: AAPL): ").strip().upper() or "AAPL"
start_date = input("Enter start date (YYYY-MM-DD, default: 1 year ago): ").strip()
end_date = input("Enter end date (YYYY-MM-DD, default: today): ").strip()
# Set defaults if not provided
if not start_date:
start_date = (datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d')
if not end_date:
end_date = datetime.now().strftime('%Y-%m-%d')
print(f"Fetching data for {ticker} from {start_date} to {end_date}...")
# Fetch historical data
data = yf.download(ticker, start=start_date, end=end_date, progress=False)
if data.empty:
print("No data found for the given ticker and date range. Please try again.")
exit()
# Calculate moving averages
data['MA50'] = data['Close'].rolling(window=50, min_periods=1).mean()
data['MA200'] = data['Close'].rolling(window=200, min_periods=1).mean()
# Create the plot with subplots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 10), height_ratios=[3, 1])
# Price subplot
ax1.plot(data.index, data['Close'], label='Close Price', linewidth=2, color='blue')
ax1.plot(data.index, data['MA50'], label='50-day MA', linewidth=1, color='orange', alpha=0.8)
ax1.plot(data.index, data['MA200'], label='200-day MA', linewidth=1, color='red', alpha=0.8)
ax1.set_title(f'{ticker} Stock Price Trend and Moving Averages', fontsize=16, fontweight='bold')
ax1.set_ylabel('Price ($)', fontsize=12)
ax1.legend(loc='upper left')
ax1.grid(True, alpha=0.3)
ax1.tick_params(axis='x', rotation=45)
# Volume subplot
ax2.bar(data.index, data['Volume'], color='gray', alpha=0.6, width=1)
ax2.set_title('Trading Volume', fontsize=12)
ax2.set_ylabel('Volume', fontsize=10)
ax2.set_xlabel('Date', fontsize=12)
ax2.grid(True, alpha=0.3)
ax2.tick_params(axis='x', rotation=45)
plt.tight_layout()
plt.show()
# Print summary statistics
print("\nSummary Statistics:")
print(data['Close'].describe())
print(f"\nLatest Close Price: ${data['Close'][-1]:.2f}")
print(f"50-day MA: ${data['MA50'][-1]:.2f}")
print(f"200-day MA: ${data['MA200'][-1]:.2f}")
How to Run:
- Install dependencies:
pip install yfinance matplotlib pandas
- Save the code to a file (e.g.,
stock_tracker.py).
- Run:
python stock_tracker.py.
- Follow the prompts for ticker and dates.
Features:
- Interactive input with sensible defaults (AAPL, last 1 year).
- Moving Averages: 50-day (short-term trend) and 200-day (long-term trend).
- Dual subplot: Price trends on top, volume below.
- Summary stats: Printed after plot closes.
- Error handling: Checks for empty data.
- Customizable: Easily modify for more tickers, indicators (e.g., RSI), or exports.
This provides a clear visualization of stock trends! 📈