-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulate_agent.py
224 lines (178 loc) · 5.45 KB
/
simulate_agent.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
from datetime import datetime
from typing import Any, Dict, List, Optional
from trading_gym.utils.summary import stats
from trading_gym.agents.base import Agent
from trading_gym.envs.trading import TradingEnv
import pickle
from tqdm import tqdm
import pandas as pd
from joblib import Parallel, delayed
def simulate_agent_random_universes(
random_universes: List[List[str]],
start: datetime,
end: datetime,
agent_class: Agent,
agent_params_grid: List[Dict[str, Any]],
start_eval_date: datetime,
):
for i, params in enumerate(agent_params_grid):
statistics = []
for j, assets_data in enumerate(random_universes):
print(
f"Simulating params set {i}/{len(agent_params_grid)}, universe {j}/{len(random_universes)}"
)
env = TradingEnv(
assets_data=assets_data,
cash=True,
start=start,
end=end,
)
agent = agent_class(action_space=env.action_space, **params)
env.register(agent)
ob = env.reset()
reward = 0
done = False
for _ in tqdm(range(env._max_episode_steps)):
if done:
break
agent.observe(ob, None, reward, done, None)
action = agent.act(ob)
ob, reward, done, _ = env.step({agent.name: action})
statistics.append(
stats(env.agents[agent.name].rewards.loc[start_eval_date:].sum(axis=1))
)
pickle.dump(
statistics,
open(
f"./calibration_results/statistics_{agent.name}_params_{i}.pickle", "wb"
),
)
print("Done!")
def sim(
assets_data,
agent_class,
cash,
start,
end,
fee,
tipp_agent,
tipp_agent_params,
i,
params,
file_suffix,
):
env = TradingEnv(assets_data=assets_data, cash=cash, start=start, end=end, fee=fee)
if tipp_agent is None:
agent = agent_class(action_space=env.action_space, **params)
else:
agent = agent_class(
action_space=env.action_space,
agent=tipp_agent(action_space=env.action_space, **tipp_agent_params),
**params,
)
env.register(agent)
ob = env.reset()
reward = 0
done = False
for _ in range(env._max_episode_steps):
if done:
break
agent.observe(
observation=ob,
action=None,
reward=reward,
done=done,
next_reward=None,
)
action = agent.act(ob)
ob, reward, done, _ = env.step({agent.name: action})
results = {"agent": env.agents[agent.name], "params": params}
pickle.dump(
results,
open(
f"./simulation_results/{agent.name}/results_{agent.name}_params_{i}{'_' + file_suffix if file_suffix else ''}.pickle",
"wb",
),
)
def simulate_agent(
assets_data: Dict[str, pd.DataFrame],
start: datetime,
end: datetime,
agent_class: Agent,
agent_params_grid: List[Dict[str, Any]],
cash: bool = True,
fee: float = 0,
tipp_agent: Optional[Agent] = None,
tipp_agent_params: Optional[Dict[str, Any]] = None,
file_suffix: Optional[str] = None,
):
for i, params in enumerate(agent_params_grid):
# try:
print(f"Simulating params set {i+1}/{len(agent_params_grid)}")
env = TradingEnv(
assets_data=assets_data, cash=cash, start=start, end=end, fee=fee
)
if tipp_agent is None:
agent = agent_class(action_space=env.action_space, **params)
else:
agent = agent_class(
action_space=env.action_space,
agent=tipp_agent(action_space=env.action_space, **tipp_agent_params),
**params,
)
env.register(agent)
ob = env.reset()
reward = 0
done = False
for _ in tqdm(range(env._max_episode_steps)):
if done:
break
agent.observe(
observation=ob,
action=None,
reward=reward,
done=done,
next_reward=None,
)
action = agent.act(ob)
ob, reward, done, _ = env.step({agent.name: action})
results = {"agent": env.agents[agent.name], "params": params}
pickle.dump(
results,
open(
f"./simulation_results/{agent.name}/results_{agent.name}_params_{i}{'_' + file_suffix if file_suffix else ''}.pickle",
"wb",
),
)
# except Exception as e:
# print(e)
# print(params)
print("Done!")
def parallel_simulate_agent(
assets_data: Dict[str, pd.DataFrame],
start: datetime,
end: datetime,
agent_class: Agent,
agent_params_grid: List[Dict[str, Any]],
cash: bool = True,
fee: float = 0,
tipp_agent: Optional[Agent] = None,
tipp_agent_params: Optional[Dict[str, Any]] = None,
file_suffix: Optional[str] = None,
):
_ = Parallel(n_jobs=24)(
delayed(sim)(
assets_data,
agent_class,
cash,
start,
end,
fee,
tipp_agent,
tipp_agent_params,
i,
params,
file_suffix,
)
for i, params in tqdm(enumerate(agent_params_grid))
)