-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulate_hrp_riskfolio_agent_optuna.py
149 lines (116 loc) · 3.32 KB
/
simulate_hrp_riskfolio_agent_optuna.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
from datetime import datetime
from typing import Dict, Optional
from trading_gym.utils.summary import stats
from trading_gym.envs.trading import TradingEnv
import pickle
from tqdm import tqdm
import pandas as pd
import optuna
from trading_gym.agents.hrp_riskfoliolib import HRPAgent
from trading_gym.utils.screener import Screener
from trading_gym.utils.summary import stats
def objective(
trial,
assets_data: Dict[str, pd.DataFrame],
start: datetime,
end: datetime,
start_eval_date: datetime,
cash: bool = True,
fee: float = 0,
):
window = trial.suggest_int("window", 30, 180)
n_assets = trial.suggest_int("n_assets", 5, 20)
n_obs = trial.suggest_int("n_obs", 5, 30)
codependence = trial.suggest_categorical(
"codependence",
[
"pearson",
"spearman",
"abs_pearson",
"abs_spearman",
"distance",
"mutual_info",
"tail",
],
)
risk_measure = trial.suggest_categorical(
"risk_measure",
[
"MV",
"MSV",
"FLPM",
"SLPM",
"VaR",
"CVaR",
"WR",
"MDD",
],
)
rebalance_each_n_obs = trial.suggest_int("rebalance_each_n_obs", 1, 15)
leaf_order = trial.suggest_categorical("leaf_order", [True, False])
env = TradingEnv(assets_data=assets_data, cash=cash, start=start, end=end, fee=fee)
agent = HRPAgent(
action_space=env.action_space,
window=window,
screener=Screener(n_assets=n_assets, n_obs=n_obs),
model="HRP",
rebalance_each_n_obs=rebalance_each_n_obs,
codependence=codependence,
covariance="hist",
objective="Sharpe",
risk_measure=risk_measure,
leaf_order=leaf_order,
)
try:
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})
returns = env.agents[agent.name].rewards.loc[start_eval_date:].sum(axis=1)
returns.iloc[0] = 0.0
statistics = stats(returns)
return statistics["Sharpe Ratio"]
except Exception as e:
print(e)
return -999.0
if __name__ == "__main__":
import pickle
from datetime import datetime
assets_data = pickle.load(open("./assets_data_training_v2.pickle", "rb"))
start = datetime(2018, 5, 1)
end = datetime(2021, 1, 1)
start_eval_date = datetime(2019, 1, 1)
study = optuna.create_study(direction="maximize")
study.optimize(
lambda trial: objective(
trial,
assets_data,
start,
end,
start_eval_date,
True,
0.1,
),
n_trials=500,
)
best_params = study.best_params
print(best_params)
pickle.dump(
best_params,
open(
"./simulation_results/hrp_riskfolio/best_params_cash_01.pickle",
"wb",
),
)