Update app.py
Browse files
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 |
-
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
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 = '
|
16 |
-
end_date = '
|
17 |
stock_prices = get_stock_data(symbol, start_date, end_date)
|
18 |
|
19 |
-
#
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
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 |
-
|
|
|
36 |
|
37 |
-
|
|
|
|
|
|
|
38 |
|
39 |
-
|
40 |
-
|
41 |
|
42 |
-
#
|
43 |
-
|
44 |
|
45 |
-
#
|
46 |
-
|
47 |
|
48 |
-
#
|
49 |
-
|
|
|
50 |
|
51 |
-
#
|
52 |
-
|
53 |
-
|
54 |
|
55 |
-
#
|
56 |
-
|
57 |
-
st.line_chart(ensemble_forecast)
|
58 |
|
59 |
-
#
|
60 |
-
|
61 |
-
|
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
|
|