File size: 2,947 Bytes
69fb45d |
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 |
import yfinance as yf
import pandas as pd
import numpy as np
import plotly.graph_objs as go
from prophet import Prophet
import gradio as gr
# Function to fetch stock data
def fetch_stock_data(ticker, start_date, end_date):
stock_data = yf.download(ticker, start=start_date, end=end_date)
return stock_data
# Train the model using Prophet
def train_prophet_model(stock_data):
df = stock_data.reset_index()[['Date', 'Close']]
df.columns = ['ds', 'y']
model = Prophet()
model.fit(df)
future = model.make_future_dataframe(periods=90) # Predict for the next 3 months
forecast = model.predict(future)
return forecast
# Function to display stock information and prediction
def predict_stock(ticker, start_date, end_date):
# Fetch stock data
stock_data = fetch_stock_data(ticker, start_date, end_date)
# Train the model and get predictions
forecast = train_prophet_model(stock_data)
# Calculate metrics: % change, highest, lowest
start_price = stock_data['Close'].iloc[0]
current_price = stock_data['Close'].iloc[-1]
percentage_change = ((current_price - start_price) / start_price) * 100
highest_price = stock_data['Close'].max()
lowest_price = stock_data['Close'].min()
# Buy/Sell prediction (if price is predicted to increase, suggest Buy)
predicted_next_value = forecast['yhat'].iloc[-1]
suggestion = "Buy" if predicted_next_value > current_price else "Sell"
# Plot historical and predicted prices
fig = go.Figure()
fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['Close'], mode='lines', name='Historical'))
fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat'], mode='lines', name='Predicted'))
return fig, percentage_change, highest_price, lowest_price, suggestion
# Define Gradio UI components
tickers = ['AAPL', 'GOOG', 'MSFT', 'AMZN', 'TSLA', 'META', 'NVDA', 'NFLX', 'BABA', 'ORCL']
start_date = gr.components.DatePicker(label="Start Date", value="2023-01-01")
end_date = gr.components.DatePicker(label="End Date", value="2023-09-30")
ticker_dropdown = gr.components.Dropdown(choices=tickers, label="Stock Ticker")
# Gradio function to wrap the prediction
def gradio_interface(ticker, start_date, end_date):
fig, percentage_change, highest_price, lowest_price, suggestion = predict_stock(ticker, start_date, end_date)
return fig, f"{percentage_change:.2f}%", f"{highest_price:.2f}", f"{lowest_price:.2f}", suggestion
# Gradio interface and launch
output = [gr.components.Plot(label="Stock Price Plot"), gr.components.Textbox(label="Percentage Change"),
gr.components.Textbox(label="Highest Price"), gr.components.Textbox(label="Lowest Price"),
gr.components.Textbox(label="Prediction (Buy/Sell)")]
demo = gr.Interface(fn=gradio_interface, inputs=[ticker_dropdown, start_date, end_date], outputs=output, title="Stock Predictor App")
demo.launch()
|