|
|
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 |
|
|
|
|
|
|
|
|
def fetch_stock_data(ticker, start_date, end_date): |
|
|
stock_data = yf.download(ticker, start=start_date, end=end_date) |
|
|
return stock_data |
|
|
|
|
|
|
|
|
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) |
|
|
forecast = model.predict(future) |
|
|
return forecast |
|
|
|
|
|
|
|
|
def predict_stock(ticker, start_date, end_date): |
|
|
|
|
|
stock_data = fetch_stock_data(ticker, start_date, end_date) |
|
|
|
|
|
|
|
|
forecast = train_prophet_model(stock_data) |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
predicted_next_value = forecast['yhat'].iloc[-1] |
|
|
suggestion = "Buy" if predicted_next_value > current_price else "Sell" |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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") |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
|