-
Notifications
You must be signed in to change notification settings - Fork 0
/
system.py
1938 lines (1616 loc) · 68.4 KB
/
system.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 datetime
import os
import warnings
import system
warnings.filterwarnings('ignore')
import random as rnd
import time as stime
import numpy as np
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.dates import date2num
from matplotlib.pyplot import gca
from matplotlib.pyplot import plot
from sklearn.neighbors import KernelDensity
from sklearn.preprocessing import scale
from tqdm.notebook import tqdm
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import VotingClassifier, BaggingClassifier, VotingRegressor, BaggingRegressor
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, ExtraTreesClassifier
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor
from sklearn.svm import SVC
from xgboost import XGBClassifier, XGBRegressor
from lightgbm import LGBMClassifier, LGBMRegressor
from catboost import CatBoostClassifier, CatBoostRegressor
# from hyperopt import fmin, hp, rand, tpe
from torch.utils.data import DataLoader, TensorDataset
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
from sklearn.preprocessing import StandardScaler
from gplearn.genetic import SymbolicRegressor
# from imblearn.over_sampling import SMOTE
from copy import deepcopy
# from deap import base, creator, tools, algorithms
from joblib import Parallel, delayed
from sklearn.model_selection import train_test_split
# from empyrical import sortino_ratio, omega_ratio, sharpe_ratio, calmar_ratio, stability_of_timeseries
import torch
import torch.nn as nn
import torch.nn.functional as F
import uuid
def uuname(): return str(uuid.uuid4()).replace('-','')[0:12]
def reseed():
def seed_everything(s=0):
rnd.seed(s)
np.random.seed(s)
os.environ['PYTHONHASHSEED'] = str(s)
seed = 0
while seed == 0:
seed = int(stime.time() * 100000) % 1000000
seed_everything(seed)
return seed
def newseed():
seed = 0
while seed == 0:
seed = int(stime.time() * 100000) % 1000000
return seed
seed = reseed()
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
from datetime import datetime, time
# global parameters
train_set_end = 0.4 # percentage point specifying the training set end point (1.0 means all data is training set)
val_set_end = 0.7 # percentage point specifying the validation set end point (1.0 means no test set and all data after the previous point is validation )
max_tries = 0.2 # for optimization, percentage of the grid space to cover (1.0 = exchaustive search)
cv_folds = 5
balance_data = 1
scale_data = 1
multiclass = 0
multiclass_move_threshold = 1.0
regression = 0
regression_move_threshold = 1.0
# the objective function to maximize during optimization
def objective(s):
return (0.05 * s['SQN'] +
0.0 * s['Profit Factor'] +
0.25 * s['Win Rate [%]'] / 100.0 +
0.2 * s['Exposure Time [%]'] / 100.0 +
1.0 * s['Return [%]']
)
# keyword parameters nearly always the same
# btkw = dict(commission=.000, margin=1.0, trade_on_close=False, exclusive_orders=True)
# optkw = dict(method='grid', max_tries=max_tries, maximize=objective, return_heatmap=True)
def get_optdata(results, consts):
return results[1][tuple([consts[y][0] for y in [x for x in consts.keys()]
if consts[y][0] in [x[0] for x in results[1].index.levels]])]
def plot_result(bt, results):
try:
bt.plot(plot_width=1200, plot_volume=False, plot_pl=1, resample=False)
except Exception as ex:
print(str(ex))
plot(np.cumsum(results[0]['_trades']['PnL'].values));
def plot_optresult(rdata, feature_name):
if rdata.index.to_numpy().shape[0] > 2:
rdata.plot(kind='line', use_index=False);
gca().set_xlabel(feature_name)
gca().set_ylabel('objective')
else:
xs = rdata.index.values
goodidx = np.where(~np.isnan(rdata.values))[0]
xs = xs[goodidx]
rda = rdata.values[goodidx]
if not isinstance(xs[0], time):
plt.plot(xs, rda)
gca().set_xlabel(feature_name)
gca().set_ylabel('objective')
if xs.dtype.kind == 'f':
try:
gca().set_xticks(np.linspace(np.min(xs), np.max(xs), 10), rotation=45)
except:
gca().set_xticks(np.linspace(np.min(xs), np.max(xs), 10))
else:
gca().set_xticks(np.linspace(np.min(xs), np.max(xs), 10))
else:
# convert xs to a list of datetime.datetime objects with a fixed date
fixed_date = datetime(2022, 1, 1) # or any other date you prefer
ixs = xs[:]
xs = [datetime.combine(fixed_date, x) for x in xs]
# convert xs to a list of floats using date2num
xs = date2num(xs)
# plot the data
ax = gca()
ax.plot(xs, rda)
ax.set_xticks(xs)
ax.set_xticklabels([x.strftime('%H:%M') for x in ixs], rotation=45)
ax.set_xlabel(feature_name)
ax.set_ylabel('objective')
def featformat(s):
return 'X__' + '_'.join(s.lower().split(' '))
def featdeformat(s):
return s[len('X__'):].replace('_', ' ').replace('-', ' ')
def filter_trades_by_feature(the_trades, data, feature, min_value=None, max_value=None, exact_value=None,
use_abs=False):
# Create a copy of the trades DataFrame
filtered_trades = the_trades.copy()
# Get the relevant portion of the predictions indicator that corresponds to the trades
relevant_predictions = data[feature].iloc[filtered_trades['entry_bar']]
# Add the rescaled predictions as a new column to the trades DataFrame
if use_abs:
ft = abs(relevant_predictions.values)
else:
ft = relevant_predictions.values
# Filter the trades by the prediction value
if exact_value is not None:
filtered_trades = filtered_trades.loc[ft == exact_value]
else:
# closed interval
if (min_value is not None) and (max_value is not None):
if min_value == max_value:
filtered_trades = filtered_trades.loc[ft == min_value]
else:
min_value, max_value = np.min([min_value, max_value]), np.max([min_value, max_value])
filtered_trades = filtered_trades.loc[(ft >= min_value) & (ft <= max_value)]
else:
# open intervals
if (min_value is not None) and (max_value is None):
filtered_trades = filtered_trades.loc[ft >= min_value]
else:
filtered_trades = filtered_trades.loc[ft <= max_value]
return filtered_trades
def filter_trades_by_confidence(the_trades, min_conf=None, max_conf=None):
trs = the_trades.copy()
if (min_conf is None) and (max_conf is None):
return trs
elif (min_conf is not None) and (max_conf is None):
return trs.loc[(np.abs(0.5 - trs['conf'].values) * 2.0) >= min_conf]
elif (min_conf is None) and (max_conf is not None):
return trs.loc[(np.abs(0.5 - trs['conf'].values) * 2.0) <= max_conf]
else:
return trs.loc[((np.abs(0.5 - trs['conf'].values) * 2.0) >= min_conf) & (
(np.abs(0.5 - trs['conf'].values) * 2.0) <= max_conf)]
class Custom3DScaler():
def fit(self, X):
self.mean_ = X.mean(axis=(0, 1))
self.std_ = X.std(axis=(0, 1))
def transform(self, X):
return (X - self.mean_) / (self.std_ + 1e-8)
def inverse_transform(self, X):
return X * self.std_ + self.mean_
class RnnNet(nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers=2, dropout=0.5):
super(RnnNet, self).__init__()
self.rnn = nn.RNN(input_dim, hidden_dim, num_layers=num_layers, batch_first=True,
dropout=dropout if num_layers > 1 else 0)
self.fc = nn.Linear(hidden_dim, 2) # Change output dimension to 2
self.softmax = nn.Softmax(dim=1) # Replace sigmoid with softmax
self.dropout = nn.Dropout(dropout)
def forward(self, x):
rnn_out, _ = self.rnn(x)
rnn_out = rnn_out[:, -1]
rnn_out = self.dropout(rnn_out)
out = self.fc(rnn_out)
out = self.softmax(out) # Use softmax instead of sigmoid
return out
class GruNet(nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers=2, dropout=0.5):
super(GruNet, self).__init__()
self.gru = nn.GRU(input_dim, hidden_dim, num_layers=num_layers, batch_first=True,
dropout=dropout if num_layers > 1 else 0)
self.fc = nn.Linear(hidden_dim, 2) # Change output dimension to 2
self.softmax = nn.Softmax(dim=1) # Replace sigmoid with softmax
self.dropout = nn.Dropout(dropout)
def forward(self, x):
gru_out, _ = self.gru(x)
gru_out = gru_out[:, -1]
gru_out = self.dropout(gru_out)
out = self.fc(gru_out)
out = self.softmax(out) # Use softmax instead of sigmoid
return out
class LstmNet(nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers=2, dropout=0.5):
super(LstmNet, self).__init__()
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers=num_layers, batch_first=True,
dropout=dropout if num_layers > 1 else 0)
self.fc = nn.Linear(hidden_dim, 2) # Change output dimension to 2
self.softmax = nn.Softmax(dim=1) # Replace sigmoid with softmax
self.dropout = nn.Dropout(dropout)
def forward(self, x):
lstm_out, _ = self.lstm(x)
lstm_out = lstm_out[:, -1]
lstm_out = self.dropout(lstm_out)
out = self.fc(lstm_out)
out = self.softmax(out) # Use softmax instead of sigmoid
return out
class RecurrentNetWrapper(BaseEstimator, ClassifierMixin):
def __init__(self, input_dim, hidden_dim, window_size, quiet=0, num_layers=2, dropout=0.5,
batch_size=32, learning_rate=1e-3, n_epochs=50, type='lstm', device='cpu'):
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.batch_size = batch_size
self.learning_rate = learning_rate
self.n_epochs = n_epochs
self.num_layers=num_layers
self.dropout = dropout
self.type = type
self.device = device
self.quiet = quiet
self.window_size = window_size
self.scaler = Custom3DScaler()
if type == 'lstm':
self.model = LstmNet(input_dim, hidden_dim,
num_layers=self.num_layers, dropout=self.dropout).to(device)
elif type == 'gru':
self.model = GruNet(input_dim, hidden_dim,
num_layers=self.num_layers, dropout=self.dropout).to(device)
elif type == 'rnn':
self.model = RnnNet(input_dim, hidden_dim,
num_layers=self.num_layers, dropout=self.dropout).to(device)
else:
# default is LSTM
self.model = LstmNet(input_dim, hidden_dim,
num_layers=self.num_layers, dropout=self.dropout).to(device)
self.criterion = nn.CrossEntropyLoss()
self.optimizer = optim.Adam(self.model.parameters(), lr=learning_rate)
def fit(self, X, y):
self.scaler.fit(X)
X = self.scaler.transform(X)
X_train_tensor = torch.tensor(X, dtype=torch.float).to(self.device)
y_train_tensor = torch.tensor(y, dtype=torch.long).to(self.device) # Change dtype to torch.long
y_train_tensor = F.one_hot(y_train_tensor) # Convert y to one-hot encoding
train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
train_loader = DataLoader(train_dataset, batch_size=self.batch_size, shuffle=True)
try:
self.model.train()
for epoch in range(self.n_epochs):
epoch_loss = 0
correct = 0
total = 0
for batch_x, batch_y in train_loader:
self.optimizer.zero_grad()
outputs = self.model(batch_x)
loss = self.criterion(outputs, batch_y.to(torch.float))
epoch_loss += loss.item()
loss.backward()
self.optimizer.step()
# Compute accuracy
predicted = torch.argmax(outputs, 1)
correct += (predicted == torch.argmax(batch_y, 1)).sum().item()
total += batch_y.size(0)
epoch_acc = correct / total
epoch_loss /= len(train_loader)
if not self.quiet:
print(f'Epoch {epoch} - Loss: {epoch_loss:.4f}, Accuracy: {epoch_acc:.4f}')
except KeyboardInterrupt:
print('Interrupted.')
return self
def predict_proba(self, X):
X = self.scaler.transform(X)
X_test_tensor = torch.tensor(X, dtype=torch.float).to(self.device)
self.model.eval()
with torch.no_grad():
outputs = self.model(X_test_tensor).cpu().numpy().reshape(-1)
return outputs
class RecurrentNetEnsemble:
def __init__(self, n_classifiers, *args, **kwargs):
self.classifiers = [RecurrentNetWrapper(*args, **kwargs) for _ in range(n_classifiers)]
def fit(self, X, y):
for i,classifier in enumerate(self.classifiers):
print(f'Fitting net {i+1}...')
classifier.fit(X, y)
def predict_proba(self, X):
probas = np.zeros((X.shape[0], 2)).reshape(-1)
for classifier in self.classifiers:
probas += classifier.predict_proba(X)
probas /= len(self.classifiers)
probas = np.exp(probas) / np.sum(np.exp(probas))
return probas
def predict(self, X):
probas = self.predict_proba(X)
return np.argmax(probas, axis=1)
class SelfAttention(nn.Module):
def __init__(self, hidden_dim):
super(SelfAttention, self).__init__()
self.query = nn.Linear(hidden_dim, hidden_dim)
self.key = nn.Linear(hidden_dim, hidden_dim)
self.value = nn.Linear(hidden_dim, hidden_dim)
def forward(self, x):
q = self.query(x)
k = self.key(x)
v = self.value(x)
attn_weights = F.softmax(torch.matmul(q, k.transpose(-2, -1)) / (x.size(-1) ** 0.5), dim=-1)
attn_output = torch.matmul(attn_weights, v)
return attn_output
class BinaryClassifier(nn.Module):
def __init__(self, input_dim, hidden_dim, dropout_prob=0.5, num_layers=2):
super(BinaryClassifier, self).__init__()
self.layer_norm = nn.LayerNorm(input_dim)
self.linear1 = nn.Linear(input_dim, hidden_dim)
self.batch_norm1 = nn.BatchNorm1d(hidden_dim)
self.relu1 = nn.ReLU()
self.dropout1 = nn.Dropout(dropout_prob)
self.self_attention = SelfAttention(hidden_dim)
self.linear_layers = nn.ModuleList()
self.batch_norm_layers = nn.ModuleList()
self.relu_layers = nn.ModuleList()
self.dropout_layers = nn.ModuleList()
for _ in range(num_layers):
self.linear_layers.append(nn.Linear(hidden_dim, hidden_dim))
self.batch_norm_layers.append(nn.BatchNorm1d(hidden_dim))
self.relu_layers.append(nn.ReLU())
self.dropout_layers.append(nn.Dropout(dropout_prob))
self.linear_output = nn.Linear(hidden_dim, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.layer_norm(x)
x = self.linear1(x)
x = self.batch_norm1(x)
x = self.relu1(x)
x = self.dropout1(x)
x = self.self_attention(x)
for linear, batch_norm, relu, dropout in zip(self.linear_layers, self.batch_norm_layers, self.relu_layers,
self.dropout_layers):
x = linear(x)
x = batch_norm(x)
x = relu(x)
x = dropout(x)
x = self.linear_output(x)
x = self.sigmoid(x)
return x
# Define the PyTorch wrapper to behave like an sklearn classifier
class NeuralNetClassifierWrapper(BaseEstimator, ClassifierMixin):
def __init__(self, input_dim, hidden_dim, quiet=0, dropout_prob=0.5, num_layers=2,
batch_size=32, learning_rate=1e-3, n_epochs=50, device='cpu'):
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.batch_size = batch_size
self.learning_rate = learning_rate
self.n_epochs = n_epochs
self.dropout_prob = dropout_prob
self.num_layers = num_layers
self.device = device
self.scaler = StandardScaler()
self.model = BinaryClassifier(input_dim, hidden_dim,
dropout_prob=self.dropout_prob, num_layers=self.num_layers).to(device)
self.criterion = nn.BCELoss()
self.optimizer = optim.Adam(self.model.parameters(), lr=learning_rate)
self.quiet = quiet
def fit(self, X, y):
X = self.scaler.fit_transform(X)
X_train_tensor = torch.tensor(X, dtype=torch.float).to(self.device)
y_train_tensor = torch.tensor(y, dtype=torch.float).view(-1, 1).to(self.device)
train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
train_loader = DataLoader(train_dataset, batch_size=self.batch_size, shuffle=True)
try:
self.model.train()
for epoch in range(self.n_epochs):
epoch_loss = 0
correct = 0
total = 0
for batch_x, batch_y in train_loader:
self.optimizer.zero_grad()
outputs = self.model(batch_x)
loss = self.criterion(outputs, batch_y)
epoch_loss += loss.item()
loss.backward()
self.optimizer.step()
# Compute accuracy
predicted = torch.round(outputs)
correct += (predicted == batch_y).sum().item()
total += batch_y.size(0)
epoch_acc = correct / total
epoch_loss /= len(train_loader)
if not self.quiet:
print(f'Epoch {epoch} - Loss: {epoch_loss:.4f}, Accuracy: {epoch_acc:.4f}')
except KeyboardInterrupt:
print('Interrupted.')
return self
def predict_proba(self, X):
X = self.scaler.transform(X)
X_test_tensor = torch.tensor(X, dtype=torch.float).to(self.device)
self.model.eval()
with torch.no_grad():
outputs = self.model(X_test_tensor).cpu().numpy()
return np.hstack((1 - outputs, outputs))
def predict(self, X):
proba = self.predict_proba(X)
return (proba[:, 1] > 0.5).astype(int)
class SymbolicRegressionClassifier(BaseEstimator, ClassifierMixin):
def __init__(
self,
# population_size=1000,
# generations=20,
# tournament_size=20,
# stopping_criteria=0.0,
# const_range=(-1.0, 1.0),
# init_depth=(2, 6),
# init_method="half and half",
# function_set=("add", "sub", "mul", "div"),
# metric="mean absolute error",
# parsimony_coefficient=0.001,
# p_crossover=0.9,
# p_subtree_mutation=0.01,
# p_hoist_mutation=0.01,
# p_point_mutation=0.01,
# p_point_replace=0.05,
# max_samples=1.0,
# feature_names=None,
# warm_start=False,
# low_memory=False,
# n_jobs=1,
# verbose=0,
# random_state=None
):
self.scaler = StandardScaler()
self.model = SymbolicRegressor(
# population_size=population_size,
# generations=generations,
# tournament_size=tournament_size,
# stopping_criteria=stopping_criteria,
# const_range=const_range,
# init_depth=init_depth,
# init_method=init_method,
# function_set=function_set,
# metric=metric,
# parsimony_coefficient=parsimony_coefficient,
# p_crossover=p_crossover,
# p_subtree_mutation=p_subtree_mutation,
# p_hoist_mutation=p_hoist_mutation,
# p_point_mutation=p_point_mutation,
# p_point_replace=p_point_replace,
# max_samples=max_samples,
# feature_names=feature_names,
# warm_start=warm_start,
# low_memory=low_memory,
# n_jobs=n_jobs,
# verbose=verbose,
# random_state=random_state
)
def fit(self, X, y):
X = self.scaler.fit_transform(X)
self.model.fit(X, y)
return self
def predict(self, X):
X = self.scaler.transform(X)
y_pred = self.model.predict(X)
return (y_pred > 0.5).astype(int)
#####################
# STRATEGIES
#####################
bestsofar = None
bestsofar_score = None
def optimize_model(model_class, model_name, space, X_train, y_train, max_evals=120, test_size=0.2, **kwargs):
global bestsofar, bestsofar_score
defaults = model_class(**kwargs).get_params()
# rstate = newseed()
bestsofar = deepcopy(defaults)
bestsofar_score = -99999.0
def sanitize(p): # because some classifiers are picky about the numeric types of parameters
toints = ['n_estimators', 'num_leaves', 'max_depth', 'min_child_samples', 'num_iterations']
for ti in toints:
if ti in p:
p[ti] = int(p[ti])
def objective(params):
global bestsofar, bestsofar_score
try:
model = model_class(**kwargs)
X_train_split, X_test_split, y_train_split, y_test_split = train_test_split(
X_train, y_train, test_size=test_size, random_state=newseed(),
)
sanitize(params)
model.set_params(**params)
model.fit(X_train_split, y_train_split)
if regression:
score = np.mean(model.score(X_test_split, y_test_split))
else:
score = model.score(X_test_split, y_test_split)
if score > bestsofar_score:
print('NEW RECORD:', score)
bestsofar_score = score
bestsofar = params
return -score
except Exception as ex:
print(str(ex))
return 9999999.0
try:
best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=max_evals)
except KeyboardInterrupt:
print('Interrupted. Best score so far:', bestsofar_score)
best = bestsofar
# if we can't instantiate and train the model, use the defaults
try:
model = model_class(**kwargs)
sanitize(best)
model.set_params(**best)
model.fit(X_train[0:50], y_train[0:50])
except Exception as ex:
print(str(ex))
print('No better parameters than the defaults were found.')
best = defaults
return best
def train_clf_ensemble(clf_classes, data, ensemble_size=1, time_window_size=1, n_jobs=-1, quiet=0, **kwargs):
if not isinstance(clf_classes, list):
clf_classes = [clf_classes]
clfs = []
if not quiet:
print(f'Training ensemble: {ensemble_size} classifiers... ', end=' ')
for enss in range(ensemble_size):
for i, clf_class in enumerate(clf_classes):
try:
clf = clf_class(random_state=newseed(), probability=True, **kwargs)
except:
try:
clf = clf_class(random_state=newseed(), **kwargs)
except:
clf = clf_class(**kwargs)
clfs.append((f'clf_{uuname()}', clf))
N_TRAIN = int(data.shape[0] * train_set_end)
df = data.iloc[0:N_TRAIN]
if time_window_size > 1:
X, y = get_clean_Xy_3d(df, time_window_size)
else:
X, y = get_clean_Xy(df)
scaler = None
if scale_data and not (time_window_size > 1):
scaler = StandardScaler()
Xt = scaler.fit_transform(X)
else:
Xt = X
# if balance_data and not (time_window_size > 1):
# # Apply SMOTE oversampling to balance the training data
# sm = SMOTE(random_state=newseed())
# Xt, y = sm.fit_resample(Xt, y)
# Create ensemble classifier
ensemble = VotingClassifier(estimators=clfs, n_jobs=n_jobs, voting='soft')
# Train ensemble on training data
ensemble.fit(Xt, y)
if not quiet:
print(f'Done. Mean CV score: {np.mean(cross_val_score(ensemble, Xt, y, cv=cv_folds, scoring="accuracy")):.5f}')
return ensemble, scaler
def train_reg_ensemble(reg_classes, data, ensemble_size=1, time_window_size=1, n_jobs=-1, quiet=0, **kwargs):
if not isinstance(reg_classes, list):
reg_classes = [reg_classes]
regs = []
if not quiet:
print(f'Training ensemble: {ensemble_size} classifiers... ', end=' ')
for enss in range(ensemble_size):
for i, reg_class in enumerate(reg_classes):
try:
reg = reg_class(random_state=newseed(), **kwargs)
except:
reg = reg_class(**kwargs)
regs.append((f'clf_{uuname()}', reg))
N_TRAIN = int(data.shape[0] * train_set_end)
df = data.iloc[0:N_TRAIN]
if time_window_size > 1:
X, y = get_clean_Xy_3d(df, time_window_size)
else:
X, y = get_clean_Xy(df)
scaler = None
if scale_data and not (time_window_size > 1):
scaler = StandardScaler()
Xt = scaler.fit_transform(X)
else:
Xt = X
# Create ensemble regressor
ensemble = VotingRegressor(estimators=regs, n_jobs=n_jobs)
# Train ensemble on training data
ensemble.fit(Xt, y)
if not quiet:
print(f'Done.')
return ensemble, scaler
def train_classifier(clf_class, data, quiet=0, time_window_size=1, **kwargs):
if not quiet:
print('Training', clf_class.__name__.split('.')[-1], '...', end=' ')
try:
clf = clf_class(quiet=quiet, **kwargs)
except Exception as ex:
clf = clf_class(**kwargs)
N_TRAIN = int(data.shape[0] * train_set_end)
df = data.iloc[0:N_TRAIN]
if time_window_size > 1:
X, y = get_clean_Xy_3d(df, time_window_size)
else:
X, y = get_clean_Xy(df)
scaler = None
if scale_data and not (time_window_size > 1):
scaler = StandardScaler()
Xt = scaler.fit_transform(X)
else:
Xt = X
# if balance_data and not (time_window_size > 1):
# # Apply SMOTE oversampling to balance the training data
# sm = SMOTE(random_state=newseed())
# Xt, y = sm.fit_resample(Xt, y)
if not quiet:
print('Data collected.')
print('Class 0 (up):', len(y[y == 0]))
print('Class 1 (down):', len(y[y == 1]))
print('Class 2 (none):', len(y[y == 2]))
clf.fit(Xt, y)
return clf, scaler
def train_regressor(reg_class, data, quiet=0, plot_dist=0, **kwargs):
if not quiet:
print('Training', reg_class.__name__.split('.')[-1], '...', end=' ')
try:
reg = reg_class(quiet=quiet, **kwargs)
except:
reg = reg_class(**kwargs)
N_TRAIN = int(data.shape[0] * train_set_end)
df = data.iloc[0:N_TRAIN]
X, y = get_clean_Xy(df)
scaler = StandardScaler()
if scale_data:
Xt = scaler.fit_transform(X)
else:
Xt = X
if plot_dist:
print('Data collected.')
# Plot histogram of the target variable (y)
plt.hist(y, bins='auto', alpha=0.7, color='blue', edgecolor='black')
plt.title('Distribution of Target Variable (Price Move)')
plt.xlabel('Price Move')
plt.ylabel('Frequency')
plt.grid(True)
plt.show()
reg.fit(Xt, y)
return reg, scaler
def confidence_from_softmax(softmax_array):
num_classes = len(softmax_array)
max_value = np.max(softmax_array)
if max_value == 1 / num_classes:
return 0.0
else:
confidence = 1 - (max_value - 1 / num_classes) / (1 - 1 / num_classes)
return confidence
class MLClassifierStrategy:
def __init__(self, clf, feature_columns, scaler, min_confidence=0.0, window_size=1, use_proba=False, reverse=False):
self.clf = clf
self.feature_columns = feature_columns
self.min_confidence = min_confidence
self.scaler = scaler
self.reverse = reverse
self.window_size = window_size
self.use_proba = use_proba
def next(self, idx, data):
if not hasattr(self, 'datafeats'):
self.datafeats = data[self.feature_columns].values
if idx < self.window_size:
return 'none', 0
if self.window_size > 1:
start_idx = idx - self.window_size
window_data = self.datafeats[start_idx:idx]
else:
window_data = self.datafeats[idx].reshape(1, -1)
if self.scaler:
features = self.scaler.transform(window_data)
else:
features = window_data
if self.use_proba:
try:
if self.window_size > 1:
features = features.reshape(1, self.window_size, -1)
prediction_proba = self.clf.predict_proba(torch.tensor(features, dtype=torch.float32))
else:
try:
prediction_proba = self.clf.predict_proba(features).reshape(-1)
except:
prediction_proba = self.clf.predict_proba(pd.DataFrame(features.reshape(1,-1))).values[0]#
class_label = np.argmax(prediction_proba)
conf = confidence_from_softmax(prediction_proba)
except:
class_label = self.clf.predict(features).reshape(-1)
conf = 1.0
else:
class_label = self.clf.predict(features).reshape(-1)
conf = 1.0
if conf >= self.min_confidence:
if not self.reverse:
if class_label == 0:
return 'buy', conf
elif class_label == 1:
return 'sell', conf
elif class_label == 2:
return 'none', conf
else:
if class_label == 0:
return 'sell', conf
elif class_label == 1:
return 'buy', conf
elif class_label == 2:
return 'none', conf
else:
return 'none', conf
class MLRegressorStrategy:
def __init__(self, reg, feature_columns, scaler, reverse=False):
# the sklearn regressor is already fitted to the data, we just store it here
self.reg = reg
self.feature_columns = feature_columns
self.scaler = scaler
self.reverse = reverse
def next(self, idx, data):
if not hasattr(self, 'datafeats'):
self.datafeats = data[self.feature_columns].values
# the current row is data[idx]
# extract features for the previous row
if scale_data:
features = self.scaler.transform(self.datafeats[idx].reshape(1, -1))
else:
features = (self.datafeats[idx].reshape(1, -1))
# get the regressor prediction
try:
prediction = self.reg.predict(features)[0]
except:
# AutoGluon prediction fix
prediction = self.reg.predict(pd.DataFrame(features)).values[0]
# determine the action based on the predicted price move
if abs(prediction) > regression_move_threshold:
if not self.reverse:
if prediction > 0:
return 'buy', prediction
elif prediction <= 0:
return 'sell', -prediction
else:
if prediction > 0:
return 'sell', prediction
elif prediction <= 0:
return 'buy', -prediction
else:
return 'none', 0
market_start_time = pd.Timestamp("09:30:00").time()
market_end_time = pd.Timestamp("16:00:00").time()
enter_on_close = True
def backtest_strategy_single(strategy, data, skip_train=1, skip_val=0, skip_test=1,
commission=0.0, slippage=0.0, position_value=100000, quiet=0):
equity_curve = np.zeros(len(data))
trades = []
current_profit = 0
if not system.enter_on_close:
if quiet:
theiter = range(0, len(data)-1)
else:
theiter = tqdm(range(0, len(data)-1))
else:
if quiet:
theiter = range(0, len(data)-1)
else:
theiter = tqdm(range(0, len(data)-1))
for idx in theiter:
current_time = data.index[idx].time()
if not data.daily:
if (current_time < market_start_time) or (current_time > market_end_time):
# Skip trading in pre/aftermarket hours
equity_curve[idx] = current_profit
continue
if (idx <= int(train_set_end * len(data))) and skip_train:
continue
if (idx > int(train_set_end * len(data))) and (idx <= int(val_set_end * len(data))) and skip_val:
continue
if (idx > int(val_set_end * len(data))) and skip_test:
continue
action, confidence = strategy.next(idx, data)
if system.enter_on_close:
entry_price = data.iloc[idx]['Close']
exit_price = data.iloc[idx+1]['Close']
else:
entry_price = data.iloc[idx+1]['Open']
exit_price = data.iloc[idx+1]['Close']
shares = int(position_value / entry_price)
if action == 'buy':
profit = (exit_price - entry_price - slippage) * shares - commission
elif action == 'sell':
profit = (entry_price - exit_price - slippage) * shares - commission
elif action == 'none':
profit = 0.0
else:
raise ValueError(f"Invalid action '{action}' at index {idx}")
current_profit += profit
equity_curve[idx] = current_profit
if action != 'none':
trades.append({
'pos': action,
'conf': confidence,
'shares': shares,
'entry_datetime': data.index[idx] if system.enter_on_close else data.index[idx+1],
'exit_datetime': data.index[idx+1],
'entry_bar': idx if system.enter_on_close else idx+1,
'exit_bar': idx+1,
'entry_price': entry_price,
'exit_price': exit_price,
'profit': profit
})
return equity_curve[0:-1], *compute_stats(data, trades)
def backtest_strategy_multi(strategy, data_list, skip_train=1, skip_val=0, skip_test=1,
commission=0.0, slippage=0.0, position_value=100000, quiet=0):