-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrade_simulator.py
331 lines (257 loc) · 12.8 KB
/
trade_simulator.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
import sys
from typing import Optional
import torch as th
import numpy as np
import pandas as pd
from data_config import ConfigData
import gymnasium
from gymnasium import spaces
class TradeSimulator(gymnasium.Env):
def __init__(
self,
num_sims=64,
slippage=5e-5,
max_position=2,
step_gap=1,
gamma=0.99,
delay_step=1,
num_ignore_step=60,
device=th.device("cpu"),
days = None,
eval = False,
gpu_id=-1,
seed=1234,
):
self.device = th.device(f"cuda:{gpu_id}") if gpu_id >= 0 else device
self.num_sims = num_sims
self.gamma = gamma
self.slippage = slippage
self.delay_step = delay_step
self.max_holding = 60 * 60 // step_gap
self.max_position = max_position
self.step_gap = step_gap
self.sim_ids = th.arange(self.num_sims, device=self.device)
self.eval = eval
self.days = days
#set seeds
self.seed = seed
np.random.seed(self.seed)
th.manual_seed(self.seed)
"""config"""
args = ConfigData()
"""load data"""
self.factor_ary = np.load(args.predict_ary_path)
self.factor_ary = th.tensor(self.factor_ary, dtype=th.float32) # CPU
# data_df = pd.read_csv(args.csv_path) # CSV READ HERE
data_df = pd.read_parquet(args.parquet_path) # PARQUET READ HERE
data_df["day"] = pd.to_datetime(data_df["system_time"]).dt.day
if days is not None:
data_df = data_df[
(data_df["day"] >= days[0]) & (data_df["day"] <= days[1])
] # get only selected days
self.factor_ary = self.factor_ary[data_df.index[0] : data_df.index[-1] + 1]
self.price_ary = data_df[["bids_distance_3", "asks_distance_3", "midpoint"]].values
self.price_ary[:, 0] = self.price_ary[:, 2] * (1 + self.price_ary[:, 0])
self.price_ary[:, 1] = self.price_ary[:, 2] * (1 + self.price_ary[:, 1])
"""Align with the rear of the dataset instead"""
# self.price_ary = self.price_ary[: self.factor_ary.shape[0], :]
self.price_ary = self.price_ary[-self.factor_ary.shape[0] :, :]
self.price_ary = th.tensor(self.price_ary, dtype=th.float32) # CPU
#if eval is False:
# self.factor_ary = self.factor_ary[:int(self.factor_ary.shape[0] * train_samples_pct)]
# self.price_ary = self.price_ary[:int(self.price_ary.shape[0] * train_samples_pct)]
#else:
# self.factor_ary = self.factor_ary[int(self.factor_ary.shape[0] * train_samples_pct):]
self.seq_len = 3600
self.full_seq_len = self.price_ary.shape[0]
# overwrite max_step to do whole dataset
assert self.price_ary.shape[0] == self.factor_ary.shape[0]
# reset()
self.step_i = 0
self.step_is = th.zeros((num_sims,), dtype=th.long, device=device)
self.action_int = th.zeros((num_sims,), dtype=th.long, device=device)
self.rolling_asset = th.zeros((num_sims,), dtype=th.long, device=device)
self.position = th.zeros((num_sims,), dtype=th.long, device=device)
self.holding = th.zeros((num_sims,), dtype=th.long, device=device)
self.empty_count = th.zeros((num_sims,), dtype=th.long, device=device)
self.cash = th.zeros((num_sims,), dtype=th.float32, device=device)
self.asset = th.zeros((num_sims,), dtype=th.float32, device=device)
# environment information
self.env_name = "TradeSimulator-v0"
self.state_dim = 8 + 2 # factor_dim + (position, holding)
self.action_dim = 3 # short, nothing, long
self.if_discrete = True
self.max_step = (self.seq_len - num_ignore_step) // step_gap
self.target_return = +np.inf
low = np.array([-1] + [0] + [-1] * 8)
high = np.array([+1] + [1] + [1] * 8)
self.action_space = spaces.Discrete(3)
self.observation_space = spaces.Box(low=low, high=high, dtype=np.float32)
"""stop-loss"""
self.best_price = th.zeros((num_sims,), dtype=th.float32, device=device)
self.stop_loss_thresh = 1e3
def _reset(self, slippage=None, _if_random=True, eval_sequential=False):
self.slippage = slippage if isinstance(slippage, float) else self.slippage
num_sims = self.num_sims
device = self.device
# if if_random:
# seleziona un punto causuale di partenza dal minimo di seq_len = 3600 ad un massimo di dataset_size - 3600 * 2
if not eval_sequential:
i0s = np.random.randint(self.seq_len, self.full_seq_len - self.seq_len * 2, size=self.num_sims)
else:
i0s = np.zeros(self.num_sims) #np.ones(self.num_sims) * self.seq_len
self.step_i = 0
self.step_is = th.tensor(i0s, dtype=th.long, device=self.device)
self.cash = th.zeros((num_sims,), dtype=th.float32, device=device)
self.asset = th.zeros((num_sims,), dtype=th.float32, device=device)
self.holding = th.zeros((num_sims,), dtype=th.long, device=device)
self.position = th.zeros((num_sims,), dtype=th.long, device=device)
self.empty_count = th.zeros((num_sims,), dtype=th.long, device=device)
"""stop-loss"""
self.best_price = th.zeros((self.num_sims,), dtype=th.float32, device=self.device)
step_is = self.step_is + self.step_i
state = self.get_state(step_is_cpu=step_is.to(th.device("cpu")))
info = {}
return state, info
def _step(self, action, _if_random=True):
self.step_i += self.step_gap
step_is = self.step_is + self.step_i
step_is_cpu = step_is.to(th.device("cpu"))
action_int = action - 1
old_cash = self.cash
old_asset = self.asset
old_position = self.position
# the data in price_ary is ['bid', 'ask', 'mid']
# bid_price = self.price_ary[step_is_cpu, 0].to(self.device)
# ask_price = self.price_ary[step_is_cpu, 1].to(self.device)
mid_price = self.price_ary[step_is_cpu, 2].to(self.device)
"""get action_int"""
next_step_i = self.step_i + self.step_gap
truncated = next_step_i >= (self.max_step * self.step_gap)
if truncated: #se ho raggiunto il limite di step, chiudo la posizione
action_int = -old_position
else:
new_position = (old_position + action_int).clip(
-self.max_position, self.max_position
) # limit the position
action_int = new_position - old_position # get the limit action
done_mask = (new_position * old_position).lt(0) & old_position.ne(0)
if done_mask.sum() > 0:
action_int[done_mask] = -old_position[done_mask]
"""holding"""
self.holding = self.holding + 1
mask_max_holding = self.holding.gt(self.max_holding)
if mask_max_holding.sum() > 0:
action_int[mask_max_holding] = -old_position[mask_max_holding]
self.holding[old_position == 0] = 0
# mask_min_holding = th.logical_and(self.holding.le(self.min_holding), old_position.ne(0))
# if mask_min_holding.sum() > 0:
# action_int[mask_min_holding] = 0
"""stop-loss"""
direction_mask1 = old_position.gt(0) #prendo tutte le simulazioni in cui sono stato long
if direction_mask1.sum() > 0:
_best_price = th.max(
th.stack([self.best_price[direction_mask1], mid_price[direction_mask1]]),
dim=0,
)[0] #prendo il massimo tra il best_price passato e il mid price attuale e lo salvo
self.best_price[direction_mask1] = _best_price
direction_mask2 = old_position.lt(0)
if direction_mask2.sum() > 0:
_best_price = th.min(
th.stack([self.best_price[direction_mask2], mid_price[direction_mask2]]),
dim=0,
)[0]
self.best_price[direction_mask2] = _best_price
# stop_loss_thresh = mid_price * self.stop_loss_rate
# se lo scarto tra il best price e il mid price è superiore alla treshold chiudo la posizione
stop_loss_mask1 = th.logical_and(direction_mask1, (self.best_price - mid_price).gt(self.stop_loss_thresh))
stop_loss_mask2 = th.logical_and(direction_mask2, (mid_price - self.best_price).gt(self.stop_loss_thresh))
stop_loss_mask = th.logical_or(stop_loss_mask1, stop_loss_mask2)
if stop_loss_mask.sum() > 0:
action_int[stop_loss_mask] = -old_position[stop_loss_mask]
"""get new_position via action_int"""
new_position = old_position + action_int
entry_mask = old_position.eq(0)
if entry_mask.sum() > 0:
self.best_price[entry_mask] = mid_price[entry_mask]
"""executing"""
direction = action_int.gt(0) # True: buy, False: sell
cost = action_int * mid_price # action_int * th.where(direction, ask_price, bid_price)
#action_int is the action performed to change the position (if action is -1 and position is 1 the new_position is 0)
new_cash = old_cash - cost * th.where(direction, 1 + self.slippage, 1 - self.slippage)
new_asset = new_cash + new_position * mid_price
reward = new_asset - old_asset
if self.eval is False:
reward = reward / 100
self.cash = new_cash # update the cash
self.asset = new_asset # update the total asset
self.position = new_position # update the position
self.action_int = action_int # update the action_int
state = self.get_state(step_is_cpu)
info_dict = {"asset_v": new_asset, 'mid': mid_price,'new_cash': new_cash, 'old_cash':old_cash,
"action_exec": action_int, "position": new_position}
if truncated:
terminal = th.ones_like(self.position, dtype=th.bool)
state, _ = self.reset()
else:
# terminal = old_position.ne(0) & new_position.eq(0)
terminal = th.zeros_like(self.position, dtype=th.bool)
return state, reward, terminal, truncated, info_dict
def reset(self, seed: Optional[int] = None, options: Optional[dict] = None, eval_sequential=False):
super().reset(seed=seed)
return self._reset(slippage=None, _if_random=True, eval_sequential=eval_sequential)
def step(self, action):
return self._step(action, _if_random=True)
def get_state(self, step_is_cpu):
factor_ary = self.factor_ary[step_is_cpu, :].to(self.device)
return th.concat(
(
(self.position.float() / self.max_position)[:, None],
(self.holding.float() / self.max_holding)[:, None],
factor_ary,
),
dim=1,
)
class EvalTradeSimulator(TradeSimulator):
def reset(self, seed: Optional[int] = None, options: Optional[dict] = None, slippage=None, date_strs=(), eval_sequential=False):
super().reset(seed=seed)
self.stop_loss_thresh = 1e-4
return self._reset(slippage=slippage, _if_random=False, eval_sequential=eval_sequential)
def step(self, action):
return self._step(action, _if_random=False)
def check_simulator():
gpu_id = int(sys.argv[1]) if len(sys.argv) > 1 else -1 # 从命令行参数里获得GPU_ID
device = th.device(f"cuda:{gpu_id}" if (th.cuda.is_available() and (gpu_id >= 0)) else "cpu")
num_sims = 6
slippage = 0
step_gap = 2
sim = TradeSimulator(num_sims=num_sims, step_gap=step_gap, slippage=slippage)
action_dim = sim.action_dim
delay_step = sim.delay_step
reward_ary = th.zeros((num_sims, 4800), dtype=th.float32, device=device)
state = sim.reset(slippage=slippage)
for step_i in range(sim.max_step):
action = th.randint(action_dim, size=(num_sims, 1), device=device)
state, reward, done, info_dict = sim.step(action=action)
reward_ary[:, step_i + delay_step] = reward
print(sim.asset) # if step_i + 2 == sim.max_step else None
print(reward_ary.sum(dim=1))
print(state.shape, num_sims, sim.state_dim)
assert state.shape == (num_sims, sim.state_dim)
print("############")
reward_ary = th.zeros((num_sims, sim.max_step + delay_step), dtype=th.float32, device=device)
state = sim.reset(slippage=slippage)
for step_i in range(sim.max_step):
if step_i == 0:
action = th.ones(size=(num_sims, 1), dtype=th.long, device=device) - 1
else:
action = th.ones(size=(num_sims, 1), dtype=th.long, device=device)
state, reward, done, info_dict = sim.step(action=action)
reward_ary[:, step_i + delay_step] = reward
print(sim.asset) if step_i + 2 == sim.max_step else None
print(reward_ary.sum(dim=1))
print(state.shape, num_sims, sim.state_dim)
assert state.shape == (num_sims, sim.state_dim)
print()
if __name__ == "__main__":
check_simulator()