-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
168 lines (133 loc) · 3.93 KB
/
main.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
from binance_download import download_dataset
from process_data import get_data, add_indicators
from agent import DQNTrader
from sklearn import preprocessing
from collections import deque
import numpy as np
import random
import time
from neural_networks import nn
import matplotlib.pyplot as plt
print('HELLO')
settings = {
"filepath": "./data/binance6.csv",
"columns": [
'Open Time',
'Open',
'High',
'Low',
'Close',
'Volume',
'Close Time',
'Quote Asset Volume',
'Number Of Trades',
'Taker Buy Base Asset Volume',
'Taker Buy Quote Asset Volume',
'Ignore'
],
"features": [
# 'Open Time',
'Open',
'High',
'Low',
'Close',
'Volume',
# 'Close Time',
# 'Quote Asset Volume',
# 'Number Of Trades',
# 'Taker Buy Base Asset Volume',
# 'Taker Buy Quote Asset Volume',
# 'Ignore'
]
}
# download_dataset(settings["filepath"], settings["columns"])
TIME_STEP = 1
df = get_data(settings["filepath"], settings["features"])
df = add_indicators(df)
df['Future'] = df['Close'].shift(-TIME_STEP)
# df = df[130: - TIME_STEP].reset_index(drop=True)
df = df.dropna().reset_index(drop=True)
# x = list(range(len(df)))
# plt.plot(x, df['Close'].values)
# plt.plot(x, df['BB_lower_20'].values)
# plt.plot(x, df['BB_middle_20'].values)
# plt.plot(x, df['BB_upper_20'].values)
# plt.show()
print(df)
print(df.columns)
# df = df[-1000:].reset_index(drop=True)
assert df.isnull().values.any() == False
# print(df)
# agent = DQNTrader(df, batch_size=256, n_episodes=1000)
# # agent.fit()
# agent.test(1)
WINDOW_LENGTH = 30
EPOCHS = 100
BATCH_SIZE = 64
NAME = f"{WINDOW_LENGTH}-SEQ-{TIME_STEP}-PRED-{int(time.time())}"
def classify(current, next):
if float(next) > float(current):
return 0
else:
return 1
df['BuySell'] = list(map(classify, df['Close'], df['Future']))
df = df.drop(['Future'], axis=1)
print(df)
train = df[:int(len(df) * .95)].reset_index(drop=True)
validation = df[-int(len(df) * .05):].reset_index(drop=True)
def preprocess_df(df):
for col in df.columns:
if col in ['Open', 'High', 'Low', 'Close', 'Volume'] or col.startswith("BBANDS") or col.startswith("MA_"):
df[col] = df[col].pct_change()
df.dropna(inplace=True)
df[col] = preprocessing.scale(df[col].values)
elif col not in ['BuySell']:
df[[col]] = preprocessing.StandardScaler().fit_transform(df[[col]])
df.dropna(inplace=True)
df.dropna(inplace=True)
sequential_data = []
sequence = deque(maxlen=WINDOW_LENGTH)
for i in df.values:
sequence.append([n for n in i[:-1]])
if(len(sequence) == WINDOW_LENGTH):
sequential_data.append([np.array(sequence), i[-1]])
buys = []
sells = []
for seq, target in sequential_data:
if target == 0:
buys.append([seq, target])
elif target == 1:
sells.append([seq, target])
random.shuffle(buys)
random.shuffle(sells)
lower = min(len(buys), len(sells))
buys = buys[: lower]
sells = sells[: lower]
sequential_data = buys + sells
random.shuffle(sequential_data)
X = []
Y = []
for seq, target in sequential_data:
X.append(seq)
Y.append(target)
return np.array(X), np.array(Y, dtype='int')
train_x, train_y = preprocess_df(train)
validation_x, validation_y = preprocess_df(validation)
assert (train_y == 0).sum() == (train_y == 1).sum()
assert (validation_y == 0).sum() == (validation_y == 1).sum()
# print(train_x)
# input()
# print(train_y)
# input()
# print(validation_x)
# input()
# print(validation_y)
# input()
model, tensorboard, checkpoint = nn(train_x.shape, NAME)
history = model.fit(
train_x, train_y,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
validation_data=(validation_x, validation_y),
callbacks=[tensorboard, checkpoint]
)