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 # 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 historical data and the predicted future price plt.figure(figsize=(12, 6)) plt.plot(data.index, data['Close'], label='Historical Data') plt.axhline(y=next_day_lstm_price, color='g', linestyle='--', label='Predicted Future Price') plt.title(f'Historical Stock Price and Predicted Future Price for {ticker}') plt.xlabel('Date') plt.ylabel('Price (USD)') plt.legend() # Save the plot to a file plot_filename = 'stock_price_prediction.png' plt.savefig(plot_filename) plt.close() result = f"Predicted future price for {ticker}: ${next_day_lstm_price:.2f}" return result, plot_filename 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()], 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()