cftgff / app.py
gopichandra's picture
Update app.py
d48489f verified
import yfinance as yf
from prophet import Prophet
import gradio as gr
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
# List of stock tickers for the dropdown
tickers = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'AMZN', 'NFLX', 'NVDA', 'FB', 'INTC', 'AMD']
# Function to fetch stock data using yfinance
def fetch_stock_data(ticker, start_date, end_date):
stock_data = yf.download(ticker, start=start_date, end=end_date)
return stock_data
# Function to train the model and predict stock prices
def predict_stock(ticker, start_date, end_date):
# Fetch stock data
stock_data = fetch_stock_data(ticker, start_date, end_date)
# Prepare data for Prophet model
stock_df = stock_data[['Close']].reset_index()
stock_df = stock_df.rename(columns={'Date': 'ds', 'Close': 'y'})
# Train Prophet model
model = Prophet()
model.fit(stock_df)
# Make future predictions for 90 days (3 months)
future = model.make_future_dataframe(periods=90)
forecast = model.predict(future)
# Plot the stock price history
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(stock_data.index, stock_data['Close'], label="Historical Prices")
# Plot the forecast
ax.plot(forecast['ds'], forecast['yhat'], label="Predicted Prices", linestyle='--')
# Customize the plot
ax.set_title(f"{ticker} Stock Price Prediction", fontsize=14)
ax.set_xlabel("Date", fontsize=12)
ax.set_ylabel("Price (USD)", fontsize=12)
ax.legend(loc="upper left")
# Save the plot to a file
plt.savefig('/tmp/stock_prediction.png')
plt.close(fig) # Close the plot to prevent display issues in some environments
# Calculate key statistics
current_price = stock_data['Close'][-1]
highest_price = stock_data['Close'].max()
lowest_price = stock_data['Close'].min()
percent_change = ((current_price - stock_data['Close'][0]) / stock_data['Close'][0]) * 100
# Simple buy/sell recommendation
future_avg = forecast['yhat'].mean()
buy_sell = "Buy" if current_price < future_avg else "Sell"
# Return the plot file path and statistics
return '/tmp/stock_prediction.png', current_price, highest_price, lowest_price, percent_change, buy_sell
# Interface function for the Gradio UI
def app_interface(ticker, start_date, end_date):
graph, current_price, highest_price, lowest_price, percent_change, buy_sell = predict_stock(ticker, start_date, end_date)
# Return the file path for the plot and text outputs
return graph, current_price, highest_price, lowest_price, percent_change, buy_sell
# Updated Gradio UI using Textbox for date input instead of DatePicker
gr_interface = gr.Interface(
fn=app_interface,
inputs=[
gr.Dropdown(label="Select Stock Ticker", choices=tickers, value='AAPL'),
gr.Textbox(label="Start Date (YYYY-MM-DD)", value="2020-01-01"),
gr.Textbox(label="End Date (YYYY-MM-DD)", value=datetime.now().strftime('%Y-%m-%d'))
],
outputs=[
gr.Image(label="Stock Price Prediction"), # Display the saved plot image
gr.Textbox(label="Current Price"),
gr.Textbox(label="Highest Price"),
gr.Textbox(label="Lowest Price"),
gr.Textbox(label="Percentage Change"),
gr.Textbox(label="Buy/Sell Recommendation")
],
title="Stock Prediction App",
description="Select a stock, start and end date to predict future performance and get buy/sell recommendations."
)
# Launch the Gradio app
gr_interface.launch()