-
Notifications
You must be signed in to change notification settings - Fork 1
/
GUI.py
333 lines (273 loc) · 13.2 KB
/
GUI.py
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import tkinter as tk
from tkinter import ttk, messagebox
import numpy as np
import pickle
from lgbm_model import LGBMRegressorModel
def catboost_prediction(ticker, start_date, end_date, load_var, save_var):
from Catboost_Regressor import CatBoostPredictor
predictor = CatBoostPredictor()
try:
if load_var.get():
try:
predictor.load_model('catboost_model.joblib')
messagebox.showinfo("Info", "Model loaded successfully.")
except FileNotFoundError:
messagebox.showerror("Error", "Model file not found. Please train a new model.")
return
X_train, X_test, y_train, y_test = predictor.yfdown(ticker, start_date, end_date)
new_predictions = predictor.predict(X_test)
predictor.plot_catboost(ticker, new_predictions, y_test)
else:
X_train, X_test, y_train, y_test = predictor.yfdown(ticker, start_date, end_date)
best_params = predictor.search_catboost(X_train, y_train)
pred = predictor.train_model(X_train, y_train, X_test, y_test, best_params)
predictor.plot_catboost(ticker, pred, y_test)
if save_var.get():
predictor.save_model('catboost_model.joblib')
messagebox.showinfo("Info", "Model saved successfully.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def lstm_prediction(ticker, start_date, end_date, load_var, save_var):
from Lstm_model import LSTMPredictor
from configs.LstmConfig import Config
try:
if load_var.get():
try:
predictor = LSTMPredictor.load_model(Config.MODEL_SAVE_PATH)
messagebox.showinfo("Info", "Model loaded successfully.")
except FileNotFoundError:
messagebox.showerror("Error", "Model file not found. Please train a new model.")
return
df = predictor.yf_Down(ticker, start_date, end_date)
X_train, X_test, y_train, y_test = predictor.prepare_data(df)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
y_pred = predictor.predict(X_test)
y_true = predictor.scaler_y.inverse_transform(y_test)
rmse = predictor.evaluate_model(y_true, y_pred)
messagebox.showinfo("RMSE", f'RMSE: {rmse}')
predictor.plot_results(y_true, y_pred, ticker)
else:
predictor = LSTMPredictor()
Config.TICKER = ticker
df = predictor.yf_Down(Config.TICKER, Config.START_DATE, Config.END_DATE)
X_train, X_test, y_train, y_test = predictor.prepare_data(df)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
history = predictor.train_model(X_train, y_train, X_test, y_test)
y_pred = predictor.predict(X_test)
y_true = predictor.scaler_y.inverse_transform(y_test)
rmse = predictor.evaluate_model(y_true, y_pred)
messagebox.showinfo("RMSE", f'RMSE: {rmse}')
predictor.plot_results(y_true, y_pred, Config.TICKER)
if save_var.get():
predictor.save_model(Config.MODEL_SAVE_PATH)
messagebox.showinfo("Saved!", "Model saved successfully.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def MetaProphet(ticker, start_date, end_date, load_var, save_var):
# Prophet
from Prophet_model import MProphet
import yaml
try:
# Load the config file
config_path = 'configs/prophet_config.yaml'
with open(config_path, 'r') as file:
config = yaml.safe_load(file)
except Exception as e:
messagebox.showerror("Error", "Config file not found.")
try:
if load_var.get():
try:
# Update config with user input
config['start_date'] = start_date
config['end_date'] = end_date
config['ticker'] = ticker
# Save updated config
with open(config_path, 'w') as file:
yaml.dump(config, file)
mp_loaded = MProphet(config_path)
mp_loaded.load_model()
messagebox.showinfo("Info", "Model loaded successfully.")
except FileNotFoundError:
messagebox.showerror("Error", "Model file not found. Please train a new model.")
return
mp_loaded.download_data()
mp_loaded.fit_predict()
mp_loaded.plot()
messagebox.showinfo("Info", "Plots saved to '/plots' directory.")
else:
# Update config with user input
config['start_date'] = start_date
config['end_date'] = end_date
config['ticker'] = ticker
# Save updated config
with open(config_path, 'w') as file:
yaml.dump(config, file)
best_params = MProphet.tune_hyperparameters(config_path)
print("Best hyperparameters:", best_params)
mp_final = MProphet(config_path)
mp_final.hyperparams = best_params
results = mp_final.run()
print(f"Final RMSE: {results['rmse']}")
messagebox.showinfo("Info", "Plots saved to '/plots' directory.")
if save_var.get():
mp_final.save_model()
messagebox.showinfo("Info", "Model saved successfully.")
else:
pass
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def xgboost_prediction(ticker, start_date, end_date, load_var, save_var):
from Xgboost_model import XGBoost_Predictor
import yaml
config_path = "configs/Xgboost_config.yaml"
try:
with open(config_path, 'r') as file:
config = yaml.safe_load(file)
except FileNotFoundError:
config = {
"ticker": ticker,
"start_date": start_date,
"end_date": end_date,
"test_size": 0.2,
"plot_dir": "plots",
"hyperparameter_tuning": {
"max_depth": {"min": 3, "max": 10},
"n_estimators": {"min": 100, "max": 500},
"learning_rate": {"min": 0.01, "max": 0.3},
"subsample": {"min": 0.8, "max": 1.0},
"colsample_bytree": {"min": 0.8, "max": 1.0},
"n_iter": 20
}
}
config['start_date'] = start_date
config['end_date'] = end_date
config['ticker'] = ticker
# Save updated config
with open(config_path, 'w') as file:
yaml.dump(config, file)
predictor = XGBoost_Predictor(config_path)
try:
if load_var.get():
model_path = "models/xgboost_model.json"
try:
predictor.load_model(model_path)
messagebox.showinfo("Info", "Model loaded successfully.")
except FileNotFoundError:
messagebox.showerror("Error", "Model file not found. Please train a new model.")
return
df = predictor.download_data()
X_test, _, _, _ = predictor.prepare_data(df)
y_pred = predictor.predict(X_test)
y_pred_real = predictor.scaler_y.inverse_transform(y_pred.reshape(-1, 1))
predictor.plot_results(df['Close'].values[-len(y_pred_real):], y_pred_real)
messagebox.showinfo("Info", "Prediction completed. Check the plots directory for visualization.")
else:
predictor.run()
if save_var.get():
model_filename = "models/xgboost_model.json"
predictor.save_model(model_filename)
messagebox.showinfo("Info", f"Model saved to {model_filename}.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def run_lgbm(ticker, start_date, end_date, load_var, save_var):
lgbm_model = LGBMRegressorModel()
if load_var.get():
try:
model = lgbm_model.load_model(ticker)
rmse, dates, y_true, y_pred = lgbm_model.predict_new_data(model, ticker, start_date, end_date)
messagebox.showinfo("LGBM Results",
f'RMSE on new data: {rmse}\n\nPredictions saved in plots/{ticker}_prediction_new_data.png')
except Exception as e:
messagebox.showerror("Error", f"Failed to load model or predict: {str(e)}")
else:
try:
model, rmse = lgbm_model.run(ticker, start_date, end_date)
messagebox.showinfo("LGBM Results", f'RMSE: {rmse}')
if save_var.get():
lgbm_model.save_model(model, ticker)
messagebox.showinfo("Save Successful", f"Model for {ticker} saved successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to run LGBM model: {str(e)}")
def random_forest_prediction(ticker, start_date, end_date, load_var, save_var):
from Random_Forest_Regressor import RandomForestPredictor
rf_predictor = RandomForestPredictor()
try:
if load_var.get():
try:
rf_predictor.load_model()
messagebox.showinfo("Info", "Model loaded successfully.")
except FileNotFoundError:
messagebox.showerror("Error", "Model file not found. Please train a new model.")
return
mse, mae, r2, dates, y_true, y_pred = rf_predictor.predict_new_data(ticker, start_date, end_date)
messagebox.showinfo("Random Forest Results",
f'MSE: {mse}\nMAE: {mae}\nR-squared: {r2}\n\nPredictions saved in plots/{ticker}_prediction_new_data.png')
else:
mse, mae, r2 = rf_predictor.run(ticker, start_date, end_date)
messagebox.showinfo("Random Forest Results", f'MSE: {mse}\nMAE: {mae}\nR-squared: {r2}')
if save_var.get():
rf_predictor.save_model()
messagebox.showinfo("Save Successful", f"Model for {ticker} saved successfully.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def run_selected_model(selection, ticker):
start_date = start_date_entry.get()
end_date = end_date_entry.get()
if selection == "1":
# LSTM
lstm_prediction(ticker, start_date, end_date, load_var, save_var)
if selection == "2":
#Catboost
catboost_prediction(ticker, start_date, end_date, load_var, save_var)
if selection == "3":
#Prophet
MetaProphet(ticker, start_date, end_date, load_var, save_var)
if selection == "4":
#XGBoost
xgboost_prediction(ticker, start_date, end_date, load_var, save_var)
if selection == "5":
#LGBM
run_lgbm(ticker, start_date, end_date, load_var, save_var)
if selection == "6":
# Random Forest
random_forest_prediction(ticker, start_date, end_date, load_var, save_var)
window = tk.Tk()
window.title("Cryptocurrency & Stock Price Predictor")
# Ticker Label and Entry
ticker_label = ttk.Label(window, text="Ticker:")
ticker_label.grid(row=0, column=0, padx=5, pady=5, sticky="w")
ticker_entry = ttk.Entry(window)
ticker_entry.insert(0, "BTC-USD") # Default ticker
ticker_entry.grid(row=0, column=1, padx=5, pady=5)
# Start and End Date Labels and Entries
start_date_label = ttk.Label(window, text="Start Date (YYYY-MM-DD):")
start_date_label.grid(row=1, column=0, padx=5, pady=5, sticky="w")
start_date_entry = ttk.Entry(window)
start_date_entry.grid(row=1, column=1, padx=5, pady=5)
end_date_label = ttk.Label(window, text="End Date (YYYY-MM-DD):")
end_date_label.grid(row=2, column=0, padx=5, pady=5, sticky="w")
end_date_entry = ttk.Entry(window)
end_date_entry.grid(row=2, column=1, padx=5, pady=5)
# Load/Save
load_var = tk.BooleanVar(value=False)
load_check = ttk.Checkbutton(window, text="Load Model", variable=load_var)
load_check.grid(row=3, column=0, padx=5, pady=5, sticky="w")
save_var = tk.BooleanVar(value=False)
save_check = ttk.Checkbutton(window, text="Save Model", variable=save_var)
save_check.grid(row=3, column=1, padx=5, pady=5, sticky="w")
# Model Selection
model_var = tk.StringVar(value="1")
model_frame = ttk.LabelFrame(window, text="Select Model")
model_frame.grid(row=4, columnspan=2, padx=5, pady=5, sticky="w")
ttk.Radiobutton(model_frame, text="LSTM", variable=model_var, value="1").pack(anchor="w")
ttk.Radiobutton(model_frame, text="Catboost", variable=model_var, value="2").pack(anchor="w")
ttk.Radiobutton(model_frame, text="Prophet", variable=model_var, value="3").pack(anchor="w")
ttk.Radiobutton(model_frame, text="Xgboost", variable=model_var, value="4").pack(anchor="w")
ttk.Radiobutton(model_frame, text="LGBM", variable=model_var, value="5").pack(anchor="w")
ttk.Radiobutton(model_frame, text="Random Forest", variable=model_var, value="6").pack(anchor="w")
# Run Button
run_button = ttk.Button(window, text="Run", command=lambda: run_selected_model(model_var.get(), ticker_entry.get()))
run_button.grid(row=5, columnspan=2, pady=10)
window.mainloop()