Spaces:
Sleeping
Sleeping
File size: 3,710 Bytes
43a653b 2a985bb 946fd9f 322aa1a 43a653b a361a2a 43a653b a361a2a 43a653b 971a0d9 946fd9f a361a2a 43a653b 094b8bb a361a2a 971a0d9 a361a2a 094b8bb a361a2a 971a0d9 a361a2a 094b8bb a361a2a 094b8bb 971a0d9 094b8bb a361a2a 094b8bb a361a2a 094b8bb 43a653b a361a2a 43a653b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | 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()
|