forked from lex-hue/Stock-Predictor-V4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSPV4.py
1259 lines (1081 loc) · 38.6 KB
/
SPV4.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
def install_dependencies():
import os
import subprocess
import time
import urllib.request
import tarfile
import sys
def download_file(url, filename):
print(f"Downloading {filename}...")
start_time = time.time()
response = urllib.request.urlopen(url)
file_size = int(response.headers["Content-Length"])
downloaded = 0
block_size = 8192
with open(filename, "wb") as file:
while True:
buffer = response.read(block_size)
if not buffer:
break
file.write(buffer)
downloaded += len(buffer)
progress = downloaded / file_size * 100
print(f"Progress: {progress:.2f}%", end="\r")
print()
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Download complete: {filename} (Time: {elapsed_time:.2f} seconds)")
def extract_tar_gz(filename):
print(f"Extracting {filename}...")
start_time = time.time()
with tarfile.open(filename, "r:gz") as tar:
file_count = len(tar.getmembers())
extracted = 0
for member in tar:
tar.extract(member)
extracted += 1
progress = extracted / file_count * 100
print(f"Progress: {progress:.2f}%", end="\r")
print()
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Extraction complete: {filename} (Time: {elapsed_time:.2f} seconds)")
def install_ta_lib():
print("Installing TA-Lib...")
start_time = time.time()
os.chdir("ta-lib")
subprocess.run(["./configure", "--prefix=/usr"], check=True)
subprocess.run(
["make", "-s"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
subprocess.run(
["sudo", "make", "-s", "install"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
os.chdir("..")
end_time = time.time()
elapsed_time = end_time - start_time
print(f"TA-Lib installation complete (Time: {elapsed_time:.2f} seconds)")
def install_dependencies():
print("Installing Python dependencies...")
start_time = time.time()
packages = [
"pandas",
"numpy",
"scikit-learn",
"tensorflow-cpu",
"matplotlib",
"ta-lib",
"optuna",
]
total_packages = len(packages)
progress = 0
for package in packages:
progress += 1
print(f"Installing {package}... ({progress}/{total_packages})")
subprocess.run(
[sys.executable, "-m", "pip", "install", "--quiet", package], check=True
)
end_time = time.time()
elapsed_time = end_time - start_time
print(
f"Python dependencies installation complete (Time: {elapsed_time:.2f} seconds)"
)
if __name__ == "__main__":
print("Welcome to the SPV4 installation!")
print("This script will install all the necessary dependencies.\n")
time.sleep(2)
download_file(
"https://deac-fra.dl.sourceforge.net/project/ta-lib/ta-lib/0.4.0/ta-lib-0.4.0-src.tar.gz",
"ta-lib-0.4.0-src.tar.gz",
)
print("Extraction process will begin shortly...")
print("Please wait while the files are being extracted.")
extract_tar_gz("ta-lib-0.4.0-src.tar.gz")
print("Extraction process completed successfully!\n")
print("TA-Lib installation will now begin.")
install_ta_lib()
print("TA-Lib installation completed successfully!\n")
print("Python dependencies installation will now begin.")
install_dependencies()
print("Python dependencies installation completed successfully!\n")
print("SPV4 installation completed successfully!")
print("Creating 'data' directory...")
os.makedirs("data", exist_ok=True)
filename = os.path.join("data", "add csvs in this folder.txt")
with open(filename, "w") as file:
file.write("This is the 'add csvs in this folder.txt' file.")
print("'data' directory and file created successfully!\n")
print("SPV4 installation completed successfully!")
def prepare_data():
print("Preprocessing and preparing the CSV data...")
import os
import pandas as pd
import talib
import matplotlib.pyplot as plt
# List all CSV files in the "data" folder
data_folder = "data"
csv_files = [file for file in os.listdir(data_folder) if file.endswith(".csv")]
# Print the available CSV files with numbers for selection
print("Available CSV files:")
for i, file in enumerate(csv_files):
print(f"{i + 1}. {file}")
# Ask for user input to select a CSV file
selected_file_index = (
int(input("Enter the number of the CSV file to preprocess: ")) - 1
)
selected_file = csv_files[selected_file_index]
selected_file_path = os.path.join(data_folder, selected_file)
# Preprocess the selected CSV file
df = pd.read_csv(selected_file_path)
df["SMA"] = talib.SMA(df["Close"], timeperiod=14)
df["RSI"] = talib.RSI(df["Close"], timeperiod=14)
df["MACD"], _, _ = talib.MACD(
df["Close"], fastperiod=12, slowperiod=26, signalperiod=9
)
df["upper_band"], df["middle_band"], df["lower_band"] = talib.BBANDS(
df["Close"], timeperiod=20
)
df["aroon_up"], df["aroon_down"] = talib.AROON(df["High"], df["Low"], timeperiod=25)
df["kicking"] = talib.CDLKICKINGBYLENGTH(
df["Open"], df["High"], df["Low"], df["Close"]
)
df["ATR"] = talib.ATR(df["High"], df["Low"], df["Close"], timeperiod=14)
df["upper_band_supertrend"] = df["High"] - (df["ATR"] * 2)
df["lower_band_supertrend"] = df["Low"] + (df["ATR"] * 2)
df["in_uptrend"] = df["Close"] > df["lower_band_supertrend"]
df["supertrend_signal"] = df["in_uptrend"].diff().fillna(0)
# Replace "False" with 0 and "True" with 1
df = df.replace({False: 0, True: 1})
# Fill missing values with 0
df.fillna(0, inplace=True)
# Concatenate the columns in the order you want
df2 = pd.concat(
[
df["Date"],
df["Close"],
df["Adj Close"],
df["Volume"],
df["High"],
df["Low"],
df["SMA"],
df["MACD"],
df["upper_band"],
df["middle_band"],
df["lower_band"],
df["supertrend_signal"],
df["RSI"],
df["aroon_up"],
df["aroon_down"],
df["kicking"],
df["upper_band_supertrend"],
df["lower_band_supertrend"],
],
axis=1,
)
# Save the DataFrame to a new CSV file with indicators
df2.to_csv("data.csv", index=False)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), sharex=True)
ax1.plot(df["Close"], label="Close")
ax1.plot(df["SMA"], label="SMA")
ax1.fill_between(
df.index, df["upper_band"], df["lower_band"], alpha=0.2, color="gray"
)
ax1.plot(df["upper_band"], linestyle="dashed", color="gray")
ax1.plot(df["middle_band"], linestyle="dashed", color="gray")
ax1.plot(df["lower_band"], linestyle="dashed", color="gray")
ax1.scatter(
df.index[df["supertrend_signal"] == 1],
df["Close"][df["supertrend_signal"] == 1],
marker="^",
color="green",
s=100,
)
ax1.scatter(
df.index[df["supertrend_signal"] == -1],
df["Close"][df["supertrend_signal"] == -1],
marker="v",
color="red",
s=100,
)
ax1.legend()
ax2.plot(df["RSI"], label="RSI")
ax2.plot(df["aroon_up"], label="Aroon Up")
ax2.plot(df["aroon_down"], label="Aroon Down")
ax2.scatter(
df.index[df["kicking"] == 100],
df["High"][df["kicking"] == 100],
marker="^",
color="green",
s=100,
)
ax2.scatter(
df.index[df["kicking"] == -100],
df["Low"][df["kicking"] == -100],
marker="v",
color="red",
s=100,
)
ax2.legend()
plt.xlim(df.index[0], df.index[-1])
plt.show()
def train_model():
import os
import sys
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import (
LSTM,
Dense,
BatchNormalization,
Conv1D,
MaxPooling1D,
TimeDistributed,
)
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.metrics import mean_absolute_percentage_error, r2_score
from optuna import create_study, Trial, visualization
from optuna.samplers import TPESampler
print("Training the SPV4 model...")
print("TensorFlow version:", tf.__version__)
# Define reward function
def get_reward(y_true, y_pred):
mape = mean_absolute_percentage_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
reward = ((1 - mape) + r2) / 2
return reward
# Load data
data = pd.read_csv("data.csv")
# Normalize data
scaler = MinMaxScaler()
data_norm = scaler.fit_transform(
data[
[
"Close",
"Adj Close",
"Volume",
"High",
"Low",
"SMA",
"MACD",
"upper_band",
"middle_band",
"lower_band",
"supertrend_signal",
"RSI",
"aroon_up",
"aroon_down",
"kicking",
"upper_band_supertrend",
"lower_band_supertrend",
]
]
)
# Split data into train and test sets
train_data_norm = data_norm[: int(0.8 * len(data))]
test_data_norm = data_norm[int(0.8 * len(data)):]
# Define time steps
timesteps = 100
# Create sequences of timesteps
def create_sequences(data, timesteps):
X = []
y = []
for i in range(timesteps, len(data)):
X.append(data[i - timesteps : i])
y.append(data[i, 0])
return np.array(X), np.array(y)
X_train, y_train = create_sequences(train_data_norm, timesteps)
X_test, y_test = create_sequences(test_data_norm, timesteps)
# Define the Deep RL model
def create_model(trial):
model = Sequential()
model.add(
Conv1D(
filters=trial.suggest_int("filters", 50, 450),
kernel_size=trial.suggest_int("kernel_size", 2, 15),
activation="relu"
)
)
model.add(MaxPooling1D(pool_size=2))
model.add(
Conv1D(
filters=trial.suggest_int("filters_2", 50, 450),
kernel_size=trial.suggest_int("kernel_size_2", 1, 15),
activation="relu"
)
)
model.add(
LSTM(
units=trial.suggest_int("units", 50, 300),
return_sequences=True,
input_shape=(timesteps, X_train.shape[2])
)
)
model.add(BatchNormalization())
model.add(
LSTM(
units=trial.suggest_int("units_2", 50, 300),
return_sequences=True
)
)
model.add(BatchNormalization())
model.add(Dense(units=trial.suggest_int("units_3", 50, 300)))
model.add(BatchNormalization())
model.add(TimeDistributed(Dense(units=trial.suggest_int("units_4", 50, 300))))
model.add(BatchNormalization())
model.add(
LSTM(
units=trial.suggest_int("units_5", 25, 150),
return_sequences=True
)
)
model.add(BatchNormalization())
model.add(
LSTM(
units=trial.suggest_int("units_6", 25, 150),
return_sequences=True
)
)
model.add(BatchNormalization())
model.add(TimeDistributed(Dense(units=trial.suggest_int("units_7", 25, 150))))
model.add(BatchNormalization())
model.add(LSTM(units=trial.suggest_int("units_8", 12, 75)))
model.add(BatchNormalization())
model.add(Dense(units=1))
# Define the RL optimizer and compile the model
optimizer = tf.keras.optimizers.Adam(learning_rate=trial.suggest_float("learning_rate", 0.001, 0.015))
model.compile(optimizer=optimizer, loss="mse")
return model
# Define RL training loop
epochs = 10
epochs1 = 3
batch_size = 50
best_reward = None
def optimize_model(trial: Trial):
model = create_model(trial)
for i in range(epochs1):
print("Epoch", i+1, "/", epochs1)
# Train the model for one epoch
for a in range(0, len(X_train), batch_size):
if a == 0:
print(
"Batch", a+1, "/", len(X_train),
"(", ((a/len(X_train))*100), "% Done)"
)
else:
sys.stdout.write('\033[F\033[K')
print(
"Batch", a+1, "/", len(X_train),
"(", ((a/len(X_train))*100), "% Done)"
)
batch_X = X_train[a:a + batch_size]
batch_y = y_train[a:a + batch_size]
history = model.fit(
batch_X, batch_y,
batch_size=batch_size, epochs=1, verbose=0
)
sys.stdout.write('\033[F\033[K')
sys.stdout.write('\033[F\033[K')
# Evaluate the model on the test set
y_pred_test = model.predict(X_test)
test_reward = get_reward(y_test, y_pred_test)
sys.stdout.write('\033[F\033[K')
return test_reward
# Define the search space boundaries and create Optuna study
sampler = TPESampler(seed=42)
study = create_study(sampler=sampler, direction="maximize")
study.optimize(optimize_model, n_trials=5)
# Get best parameters and reward
best_trial = study.best_trial
best_params = best_trial.params
best_reward = best_trial.value
print("\nBest reward:", best_reward)
print("Best parameters:", best_params)
# Load the best model and evaluate it
model = create_model(best_trial)
for i in range(epochs):
print("Epoch", i+1, "/", epochs)
# Train the model for one epoch
for a in range(0, len(X_train), batch_size):
if a == 0:
print(
"Batch", a+1, "/", len(X_train),
"(", ((a/len(X_train))*100), "% Done)"
)
else:
sys.stdout.write('\033[F\033[K')
print(
"Batch", a+1, "/", len(X_train),
"(", ((a/len(X_train))*100), "% Done)"
)
batch_X = X_train[a:a + batch_size]
batch_y = y_train[a:a + batch_size]
history = model.fit(
batch_X, batch_y,
batch_size=batch_size, epochs=1, verbose=0
)
# Evaluate the model on the test set
y_pred_test = model.predict(X_test)
sys.stdout.write('\033[F\033[K')
test_reward = get_reward(y_test, y_pred_test)
print("Test reward:", test_reward)
if i == 0:
best_reward1 = test_reward
if test_reward >= best_reward1:
print("Model saved!")
model.save("model.h5")
if i == epochs - 1:
model = load_model("model.h5")
y_pred_test = model.predict(X_test)
test_reward = get_reward(y_test, y_pred_test)
test_loss = model.evaluate(X_test, y_test)
print("Final test reward:", test_reward)
print("Final test loss:", test_loss)
def evaluate_model():
print("Evaluating the model...")
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import load_model
from sklearn.metrics import mean_squared_error, mean_absolute_percentage_error
import matplotlib.pyplot as plt
print("TensorFlow version:", tf.__version__)
# Load data
data = pd.read_csv("data.csv")
# Split data into train and test sets
train_data = data.iloc[: int(0.8 * len(data))]
test_data = data.iloc[int(0.8 * len(data)) :]
# Normalize data
scaler = MinMaxScaler()
train_data_norm = scaler.fit_transform(
train_data[
[
"Close",
"Adj Close",
"Volume",
"High",
"Low",
"SMA",
"MACD",
"upper_band",
"middle_band",
"lower_band",
"supertrend_signal",
"RSI",
"aroon_up",
"aroon_down",
"kicking",
"upper_band_supertrend",
"lower_band_supertrend",
]
]
)
test_data_norm = scaler.transform(
test_data[
[
"Close",
"Adj Close",
"Volume",
"High",
"Low",
"SMA",
"MACD",
"upper_band",
"middle_band",
"lower_band",
"supertrend_signal",
"RSI",
"aroon_up",
"aroon_down",
"kicking",
"upper_band_supertrend",
"lower_band_supertrend",
]
]
)
# Define time steps
timesteps = 100
def create_sequences(data, timesteps):
X = []
y = []
for i in range(timesteps, len(data)):
X.append(data[i - timesteps : i])
y.append(data[i, 0])
return np.array(X), np.array(y)
# Load model
model = load_model("model.h5")
# Evaluate model
rmse_scores = []
mape_scores = []
rewards = []
model = load_model("model.h5")
X_test, y_test = create_sequences(test_data_norm, timesteps)
y_pred = model.predict(X_test)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
mape = mean_absolute_percentage_error(y_test, y_pred)
rmse_scores.append(rmse)
mape_scores.append(mape)
rewards.append(1 - mape)
# Print results
print(f"Mean RMSE: {np.mean(rmse_scores)}")
print(f"Mean MAPE: {np.mean(mape_scores)}")
print(f"Total Reward: {sum(rewards)}")
def fine_tune_model():
print("Finetuning the model...")
import os
import signal
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import sys
import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import load_model
from sklearn.metrics import (
mean_squared_error,
r2_score,
mean_absolute_percentage_error,
)
import matplotlib.pyplot as plt
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
print("TensorFlow version:", tf.__version__)
# Define reward function
def get_reward(y_true, y_pred):
mape = mean_absolute_percentage_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
reward = ((1 - mape) + r2) / 2
return reward
# Load data
data = pd.read_csv("data.csv")
# Split data into train and test sets
train_data = data.iloc[: int(0.8 * len(data))]
test_data = data.iloc[int(0.8 * len(data)) :]
# Normalize data
scaler = MinMaxScaler()
train_data_norm = scaler.fit_transform(
train_data[
[
"Close",
"Adj Close",
"Volume",
"High",
"Low",
"SMA",
"MACD",
"upper_band",
"middle_band",
"lower_band",
"supertrend_signal",
"RSI",
"aroon_up",
"aroon_down",
"kicking",
"upper_band_supertrend",
"lower_band_supertrend",
]
]
)
test_data_norm = scaler.transform(
test_data[
[
"Close",
"Adj Close",
"Volume",
"High",
"Low",
"SMA",
"MACD",
"upper_band",
"middle_band",
"lower_band",
"supertrend_signal",
"RSI",
"aroon_up",
"aroon_down",
"kicking",
"upper_band_supertrend",
"lower_band_supertrend",
]
]
)
# Define time steps
timesteps = 100
# Create sequences of timesteps
def create_sequences(data, timesteps):
X = []
y = []
for i in range(timesteps, len(data)):
X.append(data[i - timesteps : i])
y.append(data[i, 0])
return np.array(X), np.array(y)
X_train, y_train = create_sequences(train_data_norm, timesteps)
X_test, y_test = create_sequences(test_data_norm, timesteps)
# Define reward threshold
reward_threshold = float(
input("Enter the reward threshold (0 - 1, 0.9 recommended): ")
)
# Initialize rewards
rewards = []
mses = []
mapes = []
r2s = []
count = 0
# Function to handle SIGINT signal (CTRL + C)
def handle_interrupt(signal, frame):
print("\nInterrupt received.")
# Ask the user for confirmation
user_input = input(
f"Are you sure that you want to End the Program? (yes/no): "
)
if user_input.lower() == "yes":
exit(0)
else:
print("Continuing the Fine-tuning Process")
# Register the signal handler
signal.signal(signal.SIGINT, handle_interrupt)
while True:
# Load model
model = load_model("model.h5")
print("\nEvaluating Model")
# Evaluate model
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
mape = mean_absolute_percentage_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
# Append rewards
reward = get_reward(y_test, y_pred)
rewards.append(reward)
mses.append(mse)
mapes.append(mape)
r2s.append(r2)
# Print current rewards
print("Rewards:", rewards)
print("MAPE:", mape)
print("MSE:", mse)
print("R2:", r2)
count += 1
print("Looped", count, "times.")
# Check if reward threshold is reached
if len(rewards) >= 1 and sum(rewards[-1:]) >= reward_threshold:
print("Reward threshold reached!")
model.save("model.h5")
break
else:
print("Training Model with 5 Epochs")
epochs = 5
batch_size = 50
for i in range(epochs):
print("Epoch", i, "/", epochs)
# Train the model for one epoch
for a in range(0, len(X_train), batch_size):
if a == 0:
print("Batch", a, "/", len(X_train), "(", ((a/len(X_train))*100), "% Done)")
else:
sys.stdout.write('\033[F\033[K')
print("Batch", a, "/", len(X_train), "(", ((a/len(X_train))*100), "% Done)")
batch_X = X_train[a:a + batch_size]
batch_y = y_train[a:a + batch_size]
history = model.fit(batch_X, batch_y, batch_size=batch_size, epochs=1, verbose=0)
# Evaluate the model on the test set
y_pred_test = model.predict(X_test)
sys.stdout.write('\033[F\033[K')
test_reward = get_reward(y_test, y_pred_test)
print("Test reward:", test_reward)
if i == 0 and count == 1:
best_reward1 = test_reward
if test_reward >= best_reward1:
print("Model saved!")
model_saved = 1
best_reward1 = test_reward
model.save("model.h5")
if test_reward >= reward_threshold:
print("Model reached reward threshold", test_reward, ". Saving and stopping epochs!")
model_saved = 1
model.save("model.h5")
break
def predict_future_data():
print("Utilizing the model for predicting future data (30 days)...")
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import load_model
import matplotlib.pyplot as plt
# Load data
data = pd.read_csv("data.csv")
# Normalize data
scaler = MinMaxScaler()
data_norm = scaler.fit_transform(
data[
[
"Close",
"Adj Close",
"Volume",
"High",
"Low",
"SMA",
"MACD",
"upper_band",
"middle_band",
"lower_band",
"supertrend_signal",
"RSI",
"aroon_up",
"aroon_down",
"kicking",
"upper_band_supertrend",
"lower_band_supertrend",
]
]
)
# Define time steps
timesteps = 100
# Create sequences of timesteps
def create_sequences(data, timesteps):
X = []
for i in range(timesteps, len(data)):
X.append(data[i - timesteps : i])
return np.array(X)
X_data = create_sequences(data_norm, timesteps)
# Load model
model = load_model("model.h5")
model.summary()
num_predictions = 30
# Make predictions for next num_predictions days
X_pred = X_data[-num_predictions:].reshape(
(num_predictions, timesteps, X_data.shape[2])
)
y_pred = model.predict(X_pred)[:, 0]
# Inverse transform predictions
y_pred = scaler.inverse_transform(
np.hstack(
[
np.zeros((len(y_pred), data_norm.shape[1] - 1)),
np.array(y_pred).reshape(-1, 1),
]
)
)[:, -1]
# Generate date index for predictions
last_date = data["Date"].iloc[-1]
index = pd.date_range(
last_date, periods=num_predictions, freq="D", tz="UTC"
).tz_localize(None)
# Calculate % change
y_pred_pct_change = (y_pred - y_pred[0]) / y_pred[0] * 100
# Save predictions and % change in a CSV file
predictions = pd.DataFrame(
{"Date": index, "Predicted Close": y_pred, "% Change": y_pred_pct_change}
)
predictions.to_csv("predictions.csv", index=False)
print(predictions)
# Find the rows with the lowest and highest predicted close and the highest and lowest % change
min_close_row = predictions.iloc[predictions["Predicted Close"].idxmin()]
max_close_row = predictions.iloc[predictions["Predicted Close"].idxmax()]
max_pct_change_row = predictions.iloc[predictions["% Change"].idxmax()]
min_pct_change_row = predictions.iloc[predictions["% Change"].idxmin()]
# Print the rows with the lowest and highest predicted close and the highest and lowest % change
print(f"\n\nHighest predicted close:\n{max_close_row}\n")
print(f"Lowest predicted close:\n{min_close_row}\n")
print(f"Highest % change:\n{max_pct_change_row}\n")
print(f"Lowest % change:\n{min_pct_change_row}")
# Plot historical data and predictions
plt.plot(data["Close"].values, label="Actual Data")
plt.plot(
np.arange(len(data), len(data) + num_predictions),
y_pred,
label="Predicted Data",
)
# Add red and green arrows for highest and lowest predicted close respectively, and highest and lowest percentage change
plt.annotate(
"↓",
xy=(min_close_row.name - len(data), min_close_row["Predicted Close"]),
color="red",
fontsize=16,
arrowprops=dict(facecolor="red", shrink=0.05),
)
plt.annotate(
"↑",
xy=(max_close_row.name - len(data), max_close_row["Predicted Close"]),
color="green",
fontsize=16,
arrowprops=dict(facecolor="green", shrink=0.05),
)
plt.annotate(
"↑",
xy=(max_pct_change_row.name - len(data), y_pred.max()),
color="green",
fontsize=16,
arrowprops=dict(facecolor="green", shrink=0.05),
)
plt.annotate(
"↓",
xy=(min_pct_change_row.name - len(data), y_pred.min()),
color="red",
fontsize=16,
arrowprops=dict(facecolor="red", shrink=0.05),
)
# Add legend and title
plt.legend()
plt.title("Predicted Close Prices")
# Show plot
plt.show()
def compare_predictions():
print("Comparing the predictions with the actual data...")
import os
import pandas as pd
import matplotlib.pyplot as plt
# Get a list of CSV files in the "data" folder
data_folder = "data"
csv_files = [file for file in os.listdir(data_folder) if file.endswith(".csv")]
# Display the list of CSV files to the user
print("Available CSV files:")
for i, file in enumerate(csv_files):
print(f"{i + 1}. {file}")
# Ask the user to select a CSV file
selected_file = None
while selected_file is None:
try:
file_number = int(
input(
"Enter the number corresponding to the CSV file you want to select: "
)
)
if file_number < 1 or file_number > len(csv_files):
raise ValueError()
selected_file = csv_files[file_number - 1]
except ValueError:
print("Invalid input. Please enter a valid number.")
# Load predicted and actual data
predicted_data = pd.read_csv("predictions.csv")
actual_data = pd.read_csv(os.path.join(data_folder, selected_file))