STOCKS / app.py
mistermprah's picture
Update app.py
1b108a9 verified
raw
history blame
4.91 kB
import gradio as gr
import numpy as np
import pandas as pd
import yfinance as yf
from datetime import datetime, timedelta
from tensorflow.keras.models import load_model
from joblib import load
# Load the saved LSTM model and scaler
lstm_model = load_model('lstm_model.h5')
scaler = load('scaler.joblib')
# Define the list of stocks
stock_list = ['GOOG', 'AAPL', 'TSLA', 'AMZN', 'MSFT']
# Function to get the last row of stock data
def get_last_stock_data(ticker):
try:
start_date = '2010-01-01'
end_date = datetime.now().strftime('%Y-%m-%d')
data = yf.download(ticker, start=start_date, end=end_date)
last_row = data.iloc[-1]
return last_row.to_dict()
except Exception as e:
return str(e)
# Function to make predictions
def predict_stock_price(ticker, open_price, close_price):
try:
start_date = '2010-01-01'
end_date = datetime.now().strftime('%Y-%m-%d')
data = yf.download(ticker, start=start_date, end=end_date)
# Prepare the data
data = data[['Close']]
dataset = data.values
scaled_data = scaler.transform(dataset)
# Append the user inputs as the last row in the data
user_input = np.array([[close_price]])
user_input_scaled = scaler.transform(user_input)
scaled_data = np.vstack([scaled_data, user_input_scaled])
# Prepare the data for LSTM
x_test_lstm = []
for i in range(60, len(scaled_data)):
x_test_lstm.append(scaled_data[i-60:i])
x_test_lstm = np.array(x_test_lstm)
x_test_lstm = np.reshape(x_test_lstm, (x_test_lstm.shape[0], x_test_lstm.shape[1], 1))
# LSTM Predictions
lstm_predictions = lstm_model.predict(x_test_lstm)
lstm_predictions = scaler.inverse_transform(lstm_predictions)
next_day_lstm_price = lstm_predictions[-1][0]
result = f"Predicted future price for {ticker}: ${next_day_lstm_price:.2f}"
return result
except Exception as e:
return str(e)
# Function to predict next month's price
def predict_next_month_price(ticker):
try:
start_date = '2010-01-01'
end_date = datetime.now().strftime('%Y-%m-%d')
data = yf.download(ticker, start=start_date, end=end_date)
# Prepare the data
data = data[['Close']]
dataset = data.values
scaled_data = scaler.transform(dataset)
# Prepare the data for LSTM
x_test_lstm = []
for i in range(60, len(scaled_data)):
x_test_lstm.append(scaled_data[i-60:i])
x_test_lstm = np.array(x_test_lstm)
x_test_lstm = np.reshape(x_test_lstm, (x_test_lstm.shape[0], x_test_lstm.shape[1], 1))
# Predicting the next 30 days
predictions = []
for _ in range(30):
pred = lstm_model.predict(x_test_lstm[-1].reshape(1, 60, 1))
predictions.append(pred)
x_test_lstm = np.append(x_test_lstm, pred.reshape(1, 1, 1), axis=1)
x_test_lstm = x_test_lstm[:, 1:, :]
predictions = np.array(predictions).reshape(-1, 1)
next_month_predictions = scaler.inverse_transform(predictions)
next_month_price = next_month_predictions[-1][0]
result = f"Predicted price for {ticker} next month: ${next_month_price:.2f}"
return result
except Exception as e:
return str(e)
# Function to display historical data
def display_historical_data(ticker):
try:
start_date = '2010-01-01'
end_date = datetime.now().strftime('%Y-%m-%d')
data = yf.download(ticker, start=start_date, end=end_date)
return data.tail(30)
except Exception as e:
return str(e)
# Set up Gradio interface
ticker_input = gr.Dropdown(choices=stock_list, label="Stock Ticker")
iface = gr.Interface(
fn=predict_stock_price,
inputs=[
ticker_input,
gr.Number(label="Open"),
gr.Number(label="Close")
],
outputs=gr.Textbox(),
title="Stock Price Predictor",
description="Select the stock ticker and input the last recorded values to predict the closing price using the LSTM model."
)
next_month_iface = gr.Interface(
fn=predict_next_month_price,
inputs=[ticker_input],
outputs=gr.Textbox(),
title="Next Month Stock Price Predictor",
description="Select the stock ticker to predict the closing price for the next month using the LSTM model."
)
historical_data_iface = gr.Interface(
fn=display_historical_data,
inputs=[ticker_input],
outputs=gr.Dataframe(),
title="Historical Data Viewer",
description="Select the stock ticker to view the historical data."
)
# Combine interfaces
app = gr.TabbedInterface(
interface_list=[iface, next_month_iface, historical_data_iface],
tab_names=["Predict Today's Price", "Predict Next Month's Price", "View Historical Data"]
)
app.launch()