import gradio as gr import pandas as pd import numpy as np import matplotlib.pyplot as plt import yfinance as yf import joblib from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout from sklearn.metrics import mean_squared_error, mean_absolute_percentage_error import math import warnings warnings.filterwarnings("ignore") # ===== Utility functions ===== def rmse(a, b): return math.sqrt(mean_squared_error(a, b)) # ===== Download stock data ===== def download_data(ticker, start="2015-01-01", end=None): df = yf.download(ticker, start=start, end=end, progress=False) df = df[['Close']].dropna() df.index = pd.to_datetime(df.index) df.rename(columns={'Close': 'close'}, inplace=True) return df # ===== LSTM architecture (future use) ===== def build_lstm(window_size=60): model = Sequential([ LSTM(64, return_sequences=True, input_shape=(window_size,1)), Dropout(0.2), LSTM(32), Dropout(0.2), Dense(1) ]) model.compile(optimizer="adam", loss="mse") return model # ===== Forecast function ===== def run_app(ticker): stock_data = yf.download(ticker, start="2015-01-01", end="2023-01-01") stock_data = stock_data[['Close']].dropna() results = [] # ===== ARIMA ===== try: arima_model = joblib.load("arima_model.pkl") arima_forecast = arima_model.forecast(steps=30) arima_rmse = np.sqrt(mean_squared_error(stock_data['Close'][-30:], arima_forecast)) arima_mape = mean_absolute_percentage_error(stock_data['Close'][-30:], arima_forecast) results.append(["ARIMA", arima_rmse, arima_mape]) except Exception as e: results.append(["ARIMA", None, f"Error: {str(e)}"]) # ===== Prophet ===== try: prophet_model = joblib.load("prophet_model.pkl") prophet_future = prophet_model.make_future_dataframe(periods=30) prophet_forecast = prophet_model.predict(prophet_future) prophet_forecast = prophet_forecast.set_index("ds").loc[stock_data.index[-30:]] prophet_rmse = np.sqrt(mean_squared_error(stock_data['Close'][-30:], prophet_forecast['yhat'])) prophet_mape = mean_absolute_percentage_error(stock_data['Close'][-30:], prophet_forecast['yhat']) results.append(["Prophet", prophet_rmse, prophet_mape]) except Exception as e: results.append(["Prophet", None, f"Error: {str(e)}"]) # ===== Results Table ===== df_results = pd.DataFrame(results, columns=["Model", "RMSE", "MAPE"]) df_results = df_results.dropna(how="all") # remove empty rows # ===== Plot ===== plt.figure(figsize=(10, 5)) plt.plot(stock_data.index, stock_data['Close'], label="Actual") if "arima_forecast" in locals(): plt.plot(stock_data.index[-30:], arima_forecast, label="ARIMA Forecast") if "prophet_forecast" in locals(): plt.plot(prophet_forecast.index, prophet_forecast['yhat'], label="Prophet Forecast") plt.legend() plt.title(f"{ticker} - Stock Price Forecasting") plt.xlabel("Date") plt.ylabel("Price") plt.savefig("forecast_plot.png") plt.close() return "forecast_plot.png", df_results # ===== Gradio Interface ===== demo = gr.Interface( fn=run_app, inputs=gr.Textbox(label="Stock Ticker", placeholder="Enter ticker (e.g. AAPL)"), outputs=[ gr.Image(type="filepath", label="Forecast Plot"), gr.Dataframe(label="Performance Metrics") ], title="📈 Stock Price Forecasting (ARIMA & Prophet)", description="This app compares ARIMA and Prophet models on stock closing prices using RMSE & MAPE." ) if __name__ == "__main__": demo.launch()