forked from RL-MLDM/alphagen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_maskable_ppo.py
175 lines (152 loc) · 5.53 KB
/
train_maskable_ppo.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
import json
import os
from typing import Optional
from datetime import datetime
import numpy as np
from sb3_contrib.ppo_mask import MaskablePPO
from stable_baselines3.common.callbacks import BaseCallback
from alphagen.data.expression import *
from alphagen.models.alpha_pool import AlphaPool, SingleAlphaPool, AlphaPoolBase
from alphagen.rl.env.wrapper import AlphaEnv
from alphagen.rl.policy import LSTMSharedNet
from alphagen.utils.random import reseed_everything
from alphagen.rl.env.core import AlphaEnvCore
class CustomCallback(BaseCallback):
def __init__(self,
save_freq: int,
show_freq: int,
save_path: str,
valid_data: StockData,
valid_target: Expression,
test_data: StockData,
test_target: Expression,
name_prefix: str = 'rl_model',
timestamp: Optional[str] = None,
verbose: int = 0):
super().__init__(verbose)
self.save_freq = save_freq
self.show_freq = show_freq
self.save_path = save_path
self.name_prefix = name_prefix
self.valid_data = valid_data
self.valid_target = valid_target
self.test_data = test_data
self.test_target = test_target
if timestamp is None:
self.timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
else:
self.timestamp = timestamp
def _init_callback(self) -> None:
if self.save_path is not None:
os.makedirs(self.save_path, exist_ok=True)
def _on_step(self) -> bool:
return True
def _on_rollout_end(self) -> None:
assert self.logger is not None
self.logger.record('pool/size', self.pool.size)
self.logger.record('pool/significant', (np.abs(self.pool.weights[:self.pool.size]) > 1e-4).sum())
self.logger.record('pool/best_ic_ret', self.pool.best_ic_ret)
self.logger.record('pool/eval_cnt', self.pool.eval_cnt)
ic_test, rank_ic_test = self.pool.test_ensemble(self.test_data, self.test_target)
self.logger.record('test/ic', ic_test)
self.logger.record('test/rank_ic', rank_ic_test)
self.save_checkpoint()
def save_checkpoint(self):
path = os.path.join(self.save_path, f'{self.name_prefix}_{self.timestamp}', f'{self.num_timesteps}_steps')
self.model.save(path) # type: ignore
if self.verbose > 1:
print(f'Saving model checkpoint to {path}')
with open(f'{path}_pool.json', 'w') as f:
json.dump(self.pool.to_dict(), f)
def show_pool_state(self):
state = self.pool.state
n = len(state['exprs'])
print('---------------------------------------------')
for i in range(n):
weight = state['weights'][i]
expr_str = str(state['exprs'][i])
ic_ret = state['ics_ret'][i]
print(f'> Alpha #{i}: {weight}, {expr_str}, {ic_ret}')
print(f'>> Ensemble ic_ret: {state["best_ic_ret"]}')
print('---------------------------------------------')
@property
def pool(self) -> AlphaPoolBase:
return self.env_core.pool
@property
def env_core(self) -> AlphaEnvCore:
return self.training_env.envs[0].unwrapped # type: ignore
def main(
seed: int = 0,
instruments: str = "csi300",
pool_capacity: int = 10,
steps: int = 200_000
):
reseed_everything(seed)
device = torch.device('cuda:0')
close = Feature(FeatureType.CLOSE)
target = Ref(close, -20) / close - 1
data = StockData(instrument=instruments,
start_time='2009-01-01',
end_time='2018-12-31')
data_valid = StockData(instrument=instruments,
start_time='2019-01-01',
end_time='2019-12-31')
data_test = StockData(instrument=instruments,
start_time='2020-01-01',
end_time='2021-12-31')
pool = AlphaPool(
capacity=pool_capacity,
stock_data=data,
target=target,
ic_lower_bound=None
)
env = AlphaEnv(pool=pool, device=device, print_expr=True)
name_prefix = f"kdd_{instruments}_{pool_capacity}_{seed}"
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
checkpoint_callback = CustomCallback(
save_freq=10000,
show_freq=10000,
save_path='/path/for/checkpoints',
valid_data=data_valid,
valid_target=target,
test_data=data_test,
test_target=target,
name_prefix=name_prefix,
timestamp=timestamp,
verbose=1,
)
model = MaskablePPO(
'MlpPolicy',
env,
policy_kwargs=dict(
features_extractor_class=LSTMSharedNet,
features_extractor_kwargs=dict(
n_layers=2,
d_model=128,
dropout=0.1,
device=device,
),
),
gamma=1.,
ent_coef=0.01,
batch_size=128,
tensorboard_log='/path/for/tb/log',
device=device,
verbose=1,
)
model.learn(
total_timesteps=steps,
callback=checkpoint_callback,
tb_log_name=f'{name_prefix}_{timestamp}',
)
if __name__ == '__main__':
steps = {
10: 250_000,
20: 300_000,
50: 350_000,
100: 400_000
}
for capacity in [10, 20, 30, 50]:
for seed in range(5):
for instruments in ["csi300"]:
main(seed=seed, instruments=instruments, pool_capacity=capacity, steps=steps[capacity])