Geek7 commited on
Commit
c28f349
·
verified ·
1 Parent(s): 6d7caab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -99
app.py CHANGED
@@ -1,12 +1,12 @@
 
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):
@@ -20,128 +20,104 @@ def prepare_data(data):
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
 
 
 
 
 
1
+ import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ from statsmodels.tsa.arima.model import ARIMA
6
  from sklearn.preprocessing import MinMaxScaler
 
7
  from tensorflow.keras.models import Sequential
8
  from tensorflow.keras.layers import Dense, LSTM, GRU
9
+ import numpy as np
 
10
 
11
  # Function to load stock data using yfinance
12
  def get_stock_data(symbol, start_date, end_date):
 
20
  return scaled_data, scaler
21
 
22
  # Function to create LSTM model
23
+ def create_lstm_model(input_shape):
24
  model = Sequential()
25
+ model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
26
+ model.add(LSTM(units=50, return_sequences=True))
27
+ model.add(LSTM(units=50))
 
 
28
  model.add(Dense(units=1))
29
  model.compile(optimizer='adam', loss='mean_squared_error')
30
  return model
31
 
32
  # Function to create GRU model
33
+ def create_gru_model(input_shape):
34
  model = Sequential()
35
+ model.add(GRU(units=50, return_sequences=True, input_shape=input_shape))
36
+ model.add(GRU(units=50, return_sequences=True))
37
+ model.add(GRU(units=50))
 
 
38
  model.add(Dense(units=1))
39
  model.compile(optimizer='adam', loss='mean_squared_error')
40
  return model
41
 
42
+ # Function to fit LSTM/GRU model and make predictions
43
+ def lstm_gru_forecast(data, model_type, steps):
44
+ scaled_data, scaler = prepare_data(data)
45
+ input_data = scaled_data.reshape(-1, 1)
 
 
 
 
 
46
 
47
+ # Split data into training and testing sets
48
+ train_size = int(len(input_data) * 0.80)
49
+ train_data, test_data = input_data[0:train_size, :], input_data[train_size:len(input_data), :]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ x_train, y_train = [], []
52
+ for i in range(60, len(train_data)):
53
+ x_train.append(train_data[i - 60:i, 0])
54
+ y_train.append(train_data[i, 0])
55
+
56
+ x_train, y_train = np.array(x_train), np.array(y_train)
57
+ x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
58
+
59
+ # Create and fit the model
60
+ input_shape = (x_train.shape[1], 1)
61
+ if model_type == 'lstm':
62
+ model = create_lstm_model(input_shape)
63
+ elif model_type == 'gru':
64
+ model = create_gru_model(input_shape)
65
 
66
+ model.fit(x_train, y_train, epochs=25, batch_size=32)
67
 
68
+ # Make predictions
69
+ inputs = input_data[len(input_data) - len(test_data) - 60:]
70
+ inputs = inputs.reshape(-1, 1)
71
+ x_test = []
72
+ for i in range(60, len(inputs)):
73
+ x_test.append(inputs[i - 60:i, 0])
74
+ x_test = np.array(x_test)
75
+
76
+ x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
77
+ predicted_prices = model.predict(x_test)
78
+ predicted_prices = scaler.inverse_transform(predicted_prices)
79
+
80
+ # Create an index for the forecasted values
81
+ forecast_index = pd.date_range(start=data.index[-1], periods=steps + 1, freq=data.index.freq)
82
+
83
+ return pd.Series(predicted_prices.flatten(), index=forecast_index[1:])
84
+
85
+ # Function to create an ensemble forecast by averaging predictions
86
  def ensemble_forecast(predictions_list):
87
  return pd.DataFrame(predictions_list).mean(axis=0)
88
 
89
+ # Streamlit App
90
+ st.title("Stock Price Forecasting App")
91
+
92
  # Load stock data
93
  symbol = 'AAPL' # Replace with the desired stock symbol
94
  start_date = '2021-01-01'
95
  end_date = '2022-01-01'
96
  stock_prices = get_stock_data(symbol, start_date, end_date)
97
 
98
+ # ARIMA parameters
99
+ arima_order = (3, 0, 0) # Example: AR component (p) is set to 3, differencing (d) is 0, MA component (q) is 0
100
+ arima_forecast_steps = 30 # Number of steps to forecast (adjust based on your preference)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
+ # LSTM and GRU parameters
103
+ lstm_gru_forecast_steps = 30 # Number of steps to forecast (adjust based on your preference)
104
 
105
+ # ARIMA Forecast
106
+ arima_predictions = arima_forecast(stock_prices, arima_order, arima_forecast_steps)
107
 
108
+ # LSTM Forecast
109
+ lstm_predictions = lstm_gru_forecast(stock_prices, 'lstm', lstm_gru_forecast_steps)
 
110
 
111
+ # GRU Forecast
112
+ gru_predictions = lstm_gru_forecast(stock_prices, 'gru', lstm_gru_forecast_steps)
 
113
 
114
+ # Ensemble Forecast (Averaging)
115
+ ensemble_predictions = ensemble_forecast([arima_predictions, lstm_predictions, gru_predictions])
116
 
117
+ # Plotting
118
+ st.write("### Historical Stock Prices and Forecasts")
119
+ st.line_chart(stock_prices)
120
+ st.line_chart(arima_predictions)
121
+ st.line_chart(lstm_predictions)
122
+ st.line_chart(gru_predictions)
123
+ st.line_chart(ensemble_predictions)