import gradio as gr import numpy as np import pandas as pd import yfinance as yf from datetime import datetime from tensorflow.keras.models import load_model from joblib import load import io from PIL import Image # 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, high_price, low_price, close_price, adj_close_price, volume): 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] # Plot the data plt.figure(figsize=(10, 6)) plt.plot(data.index, data['Close'], label='Historical Close Prices') plt.axvline(x=data.index[-1], color='r', linestyle='--', label='Prediction Date') plt.plot([data.index[-1], data.index[-1] + pd.DateOffset(1)], [data['Close'].iloc[-1], next_day_lstm_price], 'go-', label='Predicted Price') plt.title(f'Predicted Closing Price for {ticker}') plt.xlabel('Date') plt.ylabel('Close Price USD ($)') plt.legend() # Save the plot to a buffer buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) plt.close() # Load the image from the buffer img = Image.open(buf) result = f"Predicted future price for {ticker}: ${next_day_lstm_price:.2f}" return result, img except Exception as e: return str(e) # Set up Gradio interface ticker_input = gr.Dropdown(choices=stock_list, label="Stock Ticker") def get_user_inputs(ticker): last_data = get_last_stock_data(ticker) if isinstance(last_data, str): return gr.Textbox.update(value=last_data) else: return gr.update(inputs=[ gr.Number(value=last_data['Open'], label='Open'), gr.Number(value=last_data['High'], label='High'), gr.Number(value=last_data['Low'], label='Low'), gr.Number(value=last_data['Close'], label='Close'), gr.Number(value=last_data['Adj Close'], label='Adj Close'), gr.Number(value=last_data['Volume'], label='Volume') ]) iface = gr.Interface( fn=predict_stock_price, inputs=[ ticker_input, gr.Number(label="Open"), gr.Number(label="High"), gr.Number(label="Low"), gr.Number(label="Close"), gr.Number(label="Adj Close"), gr.Number(label="Volume") ], outputs=[gr.Textbox(), gr.Image(type="pil")], title="Stock Price Predictor", description="Select the stock ticker and input the last recorded values to predict the closing price using the LSTM model." ) iface.launch()