hrid0yyy commited on
Commit
0048da4
·
verified ·
1 Parent(s): 8682dbb

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ from statsmodels.tsa.arima.model import ARIMA
6
+ from tensorflow import keras # Use full TensorFlow Keras for custom_objects
7
+ import joblib
8
+ from datetime import datetime, timedelta
9
+ import warnings
10
+ warnings.filterwarnings('ignore')
11
+
12
+ # Load your saved models/data (upload these files to Colab if needed via !wget or upload)
13
+ arima_model = ARIMA(pd.read_pickle('final_df.pkl')['Target'].tail(750), order=(5,1,0)).fit() # Re-fit or load saved
14
+
15
+ # Fixed: Load LSTM with custom_objects to resolve 'mse' deserialization issue
16
+ lstm_model = keras.models.load_model('lstm_model.h5',
17
+ custom_objects={'mse': keras.losses.MeanSquaredError()})
18
+
19
+ target_scaler = joblib.load('target_scaler.pkl')
20
+ final_df = pd.read_pickle('final_df.pkl')
21
+
22
+ def forecast_aapl(start_date_str, model_type='LSTM', days=30):
23
+ try:
24
+ start_date = pd.to_datetime(start_date_str)
25
+ # Simple forecast logic (adapt from your notebook)
26
+ if model_type == 'ARIMA':
27
+ forecast = arima_model.forecast(steps=days)
28
+ else: # LSTM
29
+ # Use last window for input (simplified)
30
+ recent_data = final_df.tail(30).values # n_lags=30
31
+ X_input = recent_data.reshape(1, 30, recent_data.shape[1])
32
+ preds_scaled = lstm_model.predict(X_input)[0][0]
33
+ forecast = np.full(days, target_scaler.inverse_transform([[preds_scaled]])[0][0]) # Placeholder; extend for multi-step
34
+
35
+ future_dates = pd.date_range(start=start_date, periods=days, freq='D')
36
+ results_df = pd.DataFrame({'Date': future_dates, 'Forecast': forecast})
37
+
38
+ # Plot
39
+ fig, ax = plt.subplots(figsize=(10, 5))
40
+ ax.plot(results_df['Date'], results_df['Forecast'], marker='o', label=f'{model_type} Forecast')
41
+ ax.set_title(f'AAPL {days}-Day Forecast from {start_date_str}')
42
+ ax.set_xlabel('Date')
43
+ ax.set_ylabel('Price ($)')
44
+ ax.legend()
45
+ ax.grid(True)
46
+ plt.xticks(rotation=45)
47
+ plt.tight_layout()
48
+ return fig, results_df.to_string(index=False)
49
+ except Exception as e:
50
+ return None, f"Error: {str(e)}"
51
+
52
+ # Gradio interface
53
+ iface = gr.Interface(
54
+ fn=forecast_aapl,
55
+ inputs=[
56
+ gr.Textbox(label="Start Date (YYYY-MM-DD)", value="2023-01-01"),
57
+ gr.Dropdown(choices=['LSTM', 'ARIMA'], label="Model", value='LSTM'),
58
+ gr.Slider(1, 90, value=30, label="Forecast Days")
59
+ ],
60
+ outputs=[gr.Plot(label="Forecast Plot"), gr.Textbox(label="Forecast Table")],
61
+ title="AAPL Stock Price Forecaster",
62
+ description="Enter a start date to get future AAPL price forecasts using ARIMA or LSTM."
63
+ )
64
+
65
+ # Launch locally first (test in Colab)
66
+ iface.launch(share=True, debug=True) # This gives a public link for testing