Geek7 commited on
Commit
4eaa6d3
·
verified ·
1 Parent(s): 73dbed8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -41
app.py CHANGED
@@ -1,62 +1,147 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import matplotlib.pyplot as plt
4
  import yfinance as yf
5
- from TSEnsemble.ensemble import Ensemble
6
- from TSEnsemble import arima, nn, utils
 
 
 
 
 
 
7
 
8
  # Function to load stock data using yfinance
9
  def get_stock_data(symbol, start_date, end_date):
10
  stock_data = yf.download(symbol, start=start_date, end=end_date)
11
  return stock_data['Close']
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  # Load stock data
14
  symbol = 'AAPL' # Replace with the desired stock symbol
15
- start_date = '2020-01-01'
16
- end_date = '2023-01-01'
17
  stock_prices = get_stock_data(symbol, start_date, end_date)
18
 
19
- # Set up ARIMA, CNN, LSTM, and Transformer models
20
- ar = arima.auto_arima(stock_prices, method='stepwise', season=12, max_p=3, max_q=3, max_Q=3, max_P=3, train_split=0.8, plot=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- transformer = nn.generate_transformer(
23
- look_back=12,
24
- horizon=1,
25
- n_features=1,
26
- num_transformer_blocks=4,
27
- dropout=0.25,
28
- head_size=256,
29
- num_heads=4,
30
- ff_dim=4,
31
- mlp_units=[128],
32
- mlp_dropout=0.4
33
- )
34
 
35
- lstm = nn.generate_rnn(look_back=12, hidden_layers=1, units=64, type="LSTM", dropout=0.0)
 
36
 
37
- cnn = nn.generate_cnn(look_back=12, hidden_layers=3, kernel_size=2, filters=64, dilation_rate=1, dilation_mode="multiplicative")
 
 
 
38
 
39
- # Create an ensemble model
40
- ensemble_model = Ensemble(models=[ar, cnn, lstm, transformer], regressor='wmean')
41
 
42
- # Fit the ensemble model
43
- ensemble_model.fit(stock_prices, train_size=0.8, look_back=12, val_size=0.2, train_models_size=0.7, epochs=20, batch_size=16, metric="rmse")
44
 
45
- # Forecast with the ensemble model
46
- ensemble_forecast = ensemble_model.forecast(stock_prices, steps=12, fig_size=(10, 6))
47
 
48
- # Streamlit app
49
- st.title("Stock Price Prediction App")
 
50
 
51
- # Display historical stock prices
52
- st.subheader("Historical Stock Prices")
53
- st.line_chart(stock_prices)
54
 
55
- # Display ensemble forecast
56
- st.subheader("Ensemble Forecast")
57
- st.line_chart(ensemble_forecast)
58
 
59
- # Display ARIMA forecast
60
- arima_forecast = utils.model_forecast(ar, stock_prices, steps=12)
61
- st.subheader("ARIMA Forecast")
62
- st.line_chart(arima_forecast)
 
 
 
 
1
  import yfinance as yf
2
+ import pandas as pd
3
+ import numpy as np
4
+ from sklearn.preprocessing import MinMaxScaler
5
+ from tensorflow import keras
6
+ from tensorflow.keras.models import Sequential
7
+ from tensorflow.keras.layers import Dense, LSTM, GRU
8
+ from statsmodels.tsa.arima.model import ARIMA
9
+ from kerastuner.tuners import RandomSearch
10
 
11
  # Function to load stock data using yfinance
12
  def get_stock_data(symbol, start_date, end_date):
13
  stock_data = yf.download(symbol, start=start_date, end=end_date)
14
  return stock_data['Close']
15
 
16
+ # Function to normalize data and prepare it for LSTM/GRU
17
+ def prepare_data(data):
18
+ scaler = MinMaxScaler(feature_range=(0, 1))
19
+ scaled_data = scaler.fit_transform(data.values.reshape(-1, 1))
20
+ return scaled_data, scaler
21
+
22
+ # Function to create LSTM model
23
+ def create_lstm_model(input_shape, hp):
24
+ model = Sequential()
25
+ model.add(LSTM(units=hp.Int('units', min_value=32, max_value=512, step=32),
26
+ return_sequences=True, input_shape=input_shape))
27
+ model.add(LSTM(units=hp.Int('units', min_value=32, max_value=512, step=32),
28
+ return_sequences=True))
29
+ model.add(LSTM(units=hp.Int('units', min_value=32, max_value=512, step=32)))
30
+ model.add(Dense(units=1))
31
+ model.compile(optimizer='adam', loss='mean_squared_error')
32
+ return model
33
+
34
+ # Function to create GRU model
35
+ def create_gru_model(input_shape, hp):
36
+ model = Sequential()
37
+ model.add(GRU(units=hp.Int('units', min_value=32, max_value=512, step=32),
38
+ return_sequences=True, input_shape=input_shape))
39
+ model.add(GRU(units=hp.Int('units', min_value=32, max_value=512, step=32),
40
+ return_sequences=True))
41
+ model.add(GRU(units=hp.Int('units', min_value=32, max_value=512, step=32)))
42
+ model.add(Dense(units=1))
43
+ model.compile(optimizer='adam', loss='mean_squared_error')
44
+ return model
45
+
46
+ # Function to create ARIMA model
47
+ def create_arima_model(data, hp):
48
+ # The order parameter is the hyperparameter to be tuned
49
+ p = hp.Int('p', min_value=1, max_value=5, step=1)
50
+ d = hp.Int('d', min_value=0, max_value=1, step=1)
51
+ q = hp.Int('q', min_value=1, max_value=5, step=1)
52
+
53
+ model = ARIMA(data, order=(p, d, q))
54
+ return model
55
+
56
+ # Function to create Keras Tuner RandomSearch
57
+ def create_tuner(model_builder, objective):
58
+ return RandomSearch(model_builder,
59
+ objective=objective,
60
+ max_epochs=10,
61
+ factor=3,
62
+ directory='keras_tuner_logs',
63
+ project_name='stock_price_forecasting')
64
+
65
+ # Function to fit ARIMA model using Keras Tuner
66
+ def tune_arima_model(data, tuner, hp):
67
+ # The ARIMA model is fit differently than neural networks
68
+ model = tuner.oracle.get_best_trials(1)[0].hyperparameters.values
69
+ order = (model['p'], model['d'], model['q'])
70
+
71
+ # Fit ARIMA model
72
+ arima_model = ARIMA(data, order=order)
73
+ arima_model_fit = arima_model.fit()
74
+
75
+ # Make predictions
76
+ forecast_steps = tuner.oracle.get_best_trials(1)[0].metrics.values['steps']
77
+ arima_forecast = arima_model_fit.get_forecast(steps=forecast_steps)
78
+ arima_predictions = arima_forecast.predicted_mean
79
+
80
+ return arima_predictions
81
+
82
+ # Function to create ensemble forecast by averaging predictions
83
+ def ensemble_forecast(predictions_list):
84
+ return pd.DataFrame(predictions_list).mean(axis=0)
85
+
86
  # Load stock data
87
  symbol = 'AAPL' # Replace with the desired stock symbol
88
+ start_date = '2021-01-01'
89
+ end_date = '2022-01-01'
90
  stock_prices = get_stock_data(symbol, start_date, end_date)
91
 
92
+ # Define input shape for LSTM
93
+ input_shape = (60, 1)
94
+
95
+ # Objective for Keras Tuner
96
+ def objective(hp):
97
+ lstm_model = create_lstm_model(input_shape, hp)
98
+ lstm_model.fit(x_train, y_train, epochs=10, validation_split=0.2)
99
+ loss = lstm_model.evaluate(x_test, y_test)
100
+ return loss
101
+
102
+ # Create Keras Tuner for LSTM
103
+ tuner_lstm = create_tuner(create_lstm_model, objective)
104
+
105
+ # Split data into training and testing sets for LSTM
106
+ scaled_data, scaler = prepare_data(stock_prices)
107
+ input_data = scaled_data.reshape(-1, 1)
108
+
109
+ train_size = int(len(input_data) * 0.80)
110
+ train_data, test_data = input_data[0:train_size, :], input_data[train_size:len(input_data), :]
111
 
112
+ x_train, y_train = [], []
113
+ for i in range(60, len(train_data)):
114
+ x_train.append(train_data[i - 60:i, 0])
115
+ y_train.append(train_data[i, 0])
 
 
 
 
 
 
 
 
116
 
117
+ x_train, y_train = np.array(x_train), np.array(y_train)
118
+ x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
119
 
120
+ x_test, y_test = [], []
121
+ for i in range(60, len(test_data)):
122
+ x_test.append(test_data[i - 60:i, 0])
123
+ y_test.append(test_data[i, 0])
124
 
125
+ x_test, y_test = np.array(x_test), np.array(y_test)
126
+ x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
127
 
128
+ # Tune LSTM model
129
+ tuner_lstm.search(x_train, y_train, epochs=10, validation_split=0.2)
130
 
131
+ # Retrieve the best LSTM model
132
+ best_lstm_model = tuner_lstm.get_best_models(num_models=1)[0]
133
 
134
+ # Make LSTM predictions
135
+ lstm_predictions = best_lstm_model.predict(x_test)
136
+ lstm_predictions = scaler.inverse_transform(lstm_predictions)
137
 
138
+ # Tune ARIMA model
139
+ tuner_arima = create_tuner(create_arima_model, 'val_loss')
140
+ tuner_arima.search(stock_prices, epochs=10, validation_split=0.2)
141
 
142
+ # Retrieve the best ARIMA model
143
+ arima_predictions = tune_arima_model(stock_prices, tuner_arima, x_test, y_test)
 
144
 
145
+ # Tune GRU model (similar to LSTM tuning)
146
+ tuner_gru = create_tuner(create_gru_model, objective)
147
+ tuner