import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
def get_stock_data(ticker, period='1mo', interval='1d'):
"""
Fetch stock data for a given ticker.
Args:
ticker (str): The stock ticker symbol.
period (str): The time period for historical data (e.g., '1mo', '1y').
interval (str): The interval for the data (e.g., '1d', '1h').
Returns:
pandas.DataFrame: Historical stock data.
"""
try:
stock = yf.Ticker(ticker)
data = stock.history(period=period, interval=interval)
return data
except Exception as e:
print(f"Error fetching data: {e}")
return None
def plot_stock_data(data, ticker):
"""
Plot stock closing price data.
Args:
data (pandas.DataFrame): Historical stock data.
ticker (str): The stock ticker symbol.
"""
if data is not None and not data.empty:
plt.figure(figsize=(10, 6))
plt.plot(data.index, data['Close'], label=f'{ticker} Closing Price')
plt.title(f"{ticker} Stock Price")
plt.xlabel("Date")
plt.ylabel("Closing Price")
plt.legend()
plt.grid()
plt.show()
else:
print("No data available to plot.")
def main():
print("Welcome to the Stock Price Tracker!")
ticker = input("Enter the stock ticker symbol (e.g., AAPL, TSLA, GOOGL): ").upper()
period = input("Enter the time period (default is '1mo', e.g., '1d', '1y'): ") or '1mo'
interval = input("Enter the data interval (default is '1d', e.g., '1h', '1wk'): ") or '1d'
print("\nFetching stock data...")
data = get_stock_data(ticker, period, interval)
if data is not None and not data.empty:
print("\nStock data fetched successfully!")
print(data.tail()) # Display the last 5 rows of data
plot_stock_data(data, ticker)
else:
print("Failed to fetch stock data. Please check the ticker symbol or try again.")
if __name__ == "__main__":
main()
No comments:
Post a Comment