Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import numpy as np | |
| import tensorflow as tf | |
| import joblib | |
| import yfinance as yf | |
| from datetime import datetime, timedelta | |
| # Load model and scaler | |
| model = tf.keras.models.load_model("stock_price_lstm_model.keras") | |
| scaler = joblib.load("scaler.save") | |
| # Mapping of dropdown labels to Yahoo Finance tickers | |
| ticker_map = { | |
| "TCS": "TCS.NS", | |
| "INFY": "INFY.NS", | |
| "RELIANCE": "RELIANCE.NS" | |
| } | |
| def get_last_60_closing_prices(stock, end_date_str): | |
| try: | |
| end_date = datetime.strptime(end_date_str, "%Y-%m-%d") | |
| start_date = end_date - timedelta(days=100) # buffer for weekends/holidays | |
| ticker = ticker_map[stock] | |
| data = yf.download(ticker, start=start_date.strftime('%Y-%m-%d'), end=end_date_str) | |
| if data.shape[0] < 60: | |
| return None | |
| return data['Close'][-60:].values | |
| except Exception as e: | |
| print(e) | |
| return None | |
| def predict_next_day_price(stock, last_date): | |
| closing_prices = get_last_60_closing_prices(stock, last_date) | |
| if closing_prices is None: | |
| return "β Could not fetch enough data. Try a different date closer to market activity." | |
| # Scale and reshape for LSTM input | |
| scaled_input = scaler.transform(closing_prices.reshape(-1, 1)) | |
| X_test = np.reshape(scaled_input, (1, 60, 1)) | |
| pred_scaled = model.predict(X_test) | |
| predicted_price = scaler.inverse_transform(pred_scaled) | |
| return f"π Predicted next day price for {stock}: βΉ{predicted_price[0][0]:.2f}" | |
| # Gradio UI | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# π Stock Price Predictor using LSTM") | |
| gr.Markdown("Select a stock and input the last available date (YYYY-MM-DD). The model will fetch the previous 60 days of data and predict the next day's price.") | |
| stock_dropdown = gr.Dropdown(choices=["TCS", "INFY", "RELIANCE"], label="Select Stock") | |
| date_input = gr.Textbox(label="Enter last known date (YYYY-MM-DD)", placeholder="Example: 2025-06-10") | |
| output_text = gr.Textbox(label="Prediction Result") | |
| predict_btn = gr.Button("Predict Price") | |
| predict_btn.click(fn=predict_next_day_price, inputs=[stock_dropdown, date_input], outputs=output_text) | |
| demo.launch() | |