-
Notifications
You must be signed in to change notification settings - Fork 1
/
baseline_model.py
171 lines (143 loc) · 6.05 KB
/
baseline_model.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
import numpy as np
import os
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from backtest import BackTest
from tqdm import tqdm
class BaselineModel:
"""
Baseline Model
------------------
Input Layer:
9 * 30 data picture, flatten as 270 features, batch normalized
2 Hidden Dense Layers:
30 units with ReLU activation function, 50% dropout
10 units with ReLU activation function, 50% dropout
Output Layer:
1 unit with Linear activation function
-------------------
"""
def __init__(self, name: str, config: dict, fit_config: dict):
self.name = name
self.config = config
self.fit_config = fit_config
tf.random.set_seed(1)
self.model = tf.keras.Sequential([
tf.keras.Input(shape=(self.config['feat_num'],)),
tf.keras.layers.BatchNormalization(), # normalize data
tf.keras.layers.Dense(units=30, activation='relu',
kernel_initializer=tf.keras.initializers.TruncatedNormal()),
tf.keras.layers.Dropout(rate=0.5), # drop out 50% of the neurons
tf.keras.layers.Dense(units=10, activation='relu',
kernel_initializer=tf.keras.initializers.TruncatedNormal()),
tf.keras.layers.Dropout(rate=0.5), # drop out 50% of the neurons
tf.keras.layers.Dense(units=1, kernel_initializer=tf.keras.initializers.TruncatedNormal())
])
earlystop = tf.keras.callbacks.EarlyStopping(monitor="loss", min_delta=0, patience=10,
verbose=0, mode="min", baseline=None,
restore_best_weights=True)
checkpoint = tf.keras.callbacks.ModelCheckpoint(config['model_path'], monitor='loss', verbose=0,
save_best_only=True, mode='min')
self.cb_list = [earlystop, checkpoint]
opt = tf.keras.optimizers.Adam(learning_rate=self.config['learning_rate'], clipvalue=0.5)
self.model.compile(loss=self.config['loss'], optimizer=opt, metrics=self.config['metrics'])
def fit(self, x: np.array, y: np.array):
self.model.fit(
x=x,
y=y,
callbacks=self.cb_list,
**self.fit_config
)
def predict(self, x_test: np.array):
y_pred = self.model.predict(x_test)
return y_pred
def baseline_result(begin_t: str, end_t: str):
"""
Calculate baseline model backtest result
----------------
:param begin_t: str
backtest begin date
:param end_t: str
backtest end date
:return: bt: class<BackTest>
backtest results
----------------
"""
# Model config
config = {
'model_path': Path('models'),
'feat_num': 270,
'learning_rate': 0.002,
'loss': 'mse',
'metrics': 'mse',
}
fit_config = {
'batch_size': 2000,
'epochs': 10000,
}
# read data
data = pd.read_parquet("data.parquet")
# get all trade days
date_list = data.date.unique()
begin_n = np.argmax(date_list[date_list <= pd.to_datetime(begin_t)]) + 1
end_n = np.argmax(date_list[date_list <= pd.to_datetime(end_t)])
# predicting results
df_predict = pd.DataFrame(columns=['date', 'stock', 'score'])
for n in tqdm(np.arange(begin_n, end_n, 10)):
# Training inputs for baseline model, start from 12 days before.
# The reason is that to trade in t, we can only use t-1 data to predict, then training
# data should started from t-12 (with return label from t-11 to t-1)
x_train_raw = []
y_train = []
for i in np.arange(n - 12, n - 512, -5):
t = pd.to_datetime(date_list[i]).strftime('%Y%m%d')
X_t = np.load("pictures/X_%s.npy" % t)
Y_t = np.load("pictures/Y_%s.npy" % t)
if len(x_train_raw):
x_train_raw = np.concatenate((x_train_raw, X_t), axis=0)
else:
x_train_raw = X_t
if len(y_train):
y_train = np.concatenate((y_train, Y_t), axis=0)
else:
y_train = Y_t
x_train_raw = x_train_raw.reshape(x_train_raw.shape[0], 270)
# delete nan and inf data
isnum = ~ (np.isnan(x_train_raw).max(axis=1) | np.isinf(x_train_raw).max(axis=1))
x_train_raw = x_train_raw[isnum]
y_train = y_train[isnum]
# shuffle data
shuffle = np.random.permutation(x_train_raw.shape[0])
x_train_raw = x_train_raw[shuffle]
y_train = y_train[shuffle]
# Model training
selector = BaselineModel('baseline_selector_on_%s' % t, config, fit_config)
selector.fit(x_train_raw, y_train)
# predicting today's label
# this should use t-1 data to predict!
predict_t = pd.to_datetime(date_list[n - 1]).strftime('%Y%m%d')
x_predict = np.load("pictures/X_%s.npy" % predict_t)
x_predict = x_predict.reshape(x_predict.shape[0], 270)
stock_predict = np.load("pictures/stock_%s.npy" % predict_t)
y_predict = selector.predict(np.asarray(x_predict).astype(np.float32))
# combined with stock ticker
score_t = pd.DataFrame(np.transpose([stock_predict, y_predict.reshape(-1)]), columns=['stock', 'score'])
# convert data type and drop na prediction
score_t.score = score_t.score.astype(float)
score_t['date'] = pd.to_datetime(date_list[n])
score_t = score_t.dropna()
df_predict = pd.concat([df_predict, score_t])
print(date_list[n])
# save all predictions to /predictions as .parquet file
df_predict = df_predict.set_index(['date', 'stock'])
df_predict.to_parquet("predictions/Baseline_%s_%s.parquet" % (begin_t, end_t))
# Backtest based on model prediction
bt = BackTest(df_predict)
bt.backtest()
print(bt.netvalue)
print(bt.evaluation())
return bt
if __name__ == "__main__":
bt = baseline_result('2019-01-01', '2020-12-31')