I've started mapping out the project, and the need for data retrieval is paramount. Right now, I'm leaning towards API calls to a reliable source for the stock data, and then using that to plot the trend. The choice of the data source is the current focus, which will also inform the structure of my subsequent data processing steps.
Structuring the Code
I'm now deep in the process of building the code framework. I'm thinking through the logical flow, and I've started defining a function, plot_stock_trend. The essential parameters are the stock ticker, and the date range. I'm now integrating the yfinance library, and considering error handling for invalid tickers. This is where I am right now.
Implementing the Core Logic
I'm presently building the plot_stock_trend function. I've successfully incorporated yfinance to fetch the stock data and am now integrating the Pandas library. I'm focusing on calculating moving averages and building the plot itself. The current hurdle is to ensure robustness against invalid inputs, for which I'm exploring exception handling methods.
Formulating the Script
I'm now outlining the complete program structure. I'm focusing on defining the plot_stock_trend function, which will download data, calculate moving averages, and plot the trend. I am currently considering input parameters like the start and end dates. After that, I will begin incorporating user input for ticker symbols.
Planning the Program
I'm now outlining the comprehensive plan for the Python script. I'm focusing on the modularity of the design, and its overall robustness. I've broken down the project, starting with imports, then building out the plot_stock_trend function. After that, I will incorporate error handling, and finally, user input. I'm prioritizing clarity in the code's structure and overall maintainability.
To create a robust stock tracking program, we will use three main libraries:
yfinance: To retrieve historical market data (Yahoo Finance API).
pandas: To handle the time-series data and calculate moving averages.
matplotlib: To visualize the price and trends.
Prerequisites
You will need to install the necessary libraries via your terminal or command prompt:
bash
pip install yfinance matplotlib pandas
The Python Program
Here is the complete, commented code. It plots the Closing Price along with the 50-day and 200-day Moving Averages (a common method for determining market trends).
python
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta
def plot_stock_trend(ticker_symbol, years=1):
"""
Downloads stock data and plots the closing price along with
50-day and 200-day moving averages.
Parameters:
ticker_symbol (str): The stock symbol (e.g., 'AAPL', 'MSFT', 'GOOGL')
years (int): Number of historical years to analyze
"""
# 1. Define Date Range
end_date = datetime.now()
start_date = end_date - timedelta(days=years*365)
print(f"Downloading data for {ticker_symbol}...")
# 2. Fetch Data using yfinance
try:
data = yf.download(ticker_symbol, start=start_date, end=end_date, progress=False)
if data.empty:
print(f"Error: No data found for ticker symbol '{ticker_symbol}'.")
return
except Exception as e:
print(f"An error occurred: {e}")
return
# 3. Calculate Moving Averages (Trends)
# 50-day Moving Average (Short-term trend)
data['MA50'] = data['Close'].rolling(window=50).mean()
# 200-day Moving Average (Long-term trend)
data['MA200'] = data['Close'].rolling(window=200).mean()
# 4. Plotting with Matplotlib
plt.figure(figsize=(12, 6)) # Set chart size
# Plot Close Price
plt.plot(data.index, data['Close'], label='Close Price', color='skyblue', linewidth=2, alpha=0.8)
# Plot Moving Averages
plt.plot(data.index, data['MA50'], label='50-Day MA', color='orange', linestyle='--')
plt.plot(data.index, data['MA200'], label='200-Day MA', color='red', linestyle='--')
# Styling the Chart
plt.title(f'{ticker_symbol} Stock Price & Trends ({years} Year History)', fontsize=16)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Price (USD)', fontsize=12)
plt.legend(loc='upper left')
plt.grid(True, which='both', linestyle='--', linewidth=0.5)
# Auto-format date on x-axis for readability
plt.gcf().autofmt_xdate()
# Show the plot
plt.show()
if __name__ == "__main__":
# Input from user
symbol = input("Enter Stock Ticker Symbol (e.g., AAPL, NVDA, TSLA): ").upper()
try:
period = int(input("Enter number of years to analyze (default 2): ") or 2)
except ValueError:
period = 2
plot_stock_trend(symbol, period)
How the Code Works:
Data Retrieval (yf.download): We fetch the historical data. The start and end parameters define the time range.
Data Cleaning: We check if data.empty is true to handle cases where the user types a fake ticker symbol.
Trend Calculation (rolling().mean()):
We calculate the 50-day Moving Average (MA). If the price is above this line, the short-term trend is usually considered "Up".
We calculate the 200-day MA. This is the benchmark for long-term trends.
Visualization:
figsize: Sets the resolution and aspect ratio of the window.
plot: Draws the lines. We use different colors and linestyles (--) to distinguish between raw price and trend lines.
grid: Adds a background grid to make reading prices easier.
autofmt_xdate(): Rotates the dates on the bottom so they don't overlap.