Spaces:
Runtime error
Runtime error
File size: 3,565 Bytes
2f0302c d48489f 2f0302c 42cc250 2f0302c 42cc250 2f0302c 42cc250 2f0302c 42cc250 2f0302c 42cc250 2f0302c 42cc250 2f0302c 42cc250 2f0302c d48489f 42cc250 2f0302c 42cc250 2f0302c d48489f 2f0302c 42cc250 2f0302c d48489f 2f0302c d48489f 2f0302c a621aaa 2f0302c a621aaa 2f0302c d48489f 2f0302c 42cc250 2f0302c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
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()
|