forked from notadamking/RLTrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
69 lines (51 loc) · 2.17 KB
/
train.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
import gym
import optuna
import pandas as pd
import numpy as np
from stable_baselines.common.policies import MlpLnLstmPolicy
from stable_baselines.common.vec_env import SubprocVecEnv, DummyVecEnv
from stable_baselines import A2C, ACKTR, PPO2
from env.BitcoinTradingEnv import BitcoinTradingEnv
from util.indicators import add_indicators
study = optuna.load_study(study_name='ppo2_calmar',
storage='sqlite:///params.db')
params = study.best_trial.params
print("Training PPO2 agent with params:", params)
print("Best trial:", study.best_trial.value)
df = pd.read_csv('./data/coinbase_hourly.csv')
df = df.drop(['Symbol'], axis=1)
df = df.sort_values(['Date'])
df = add_indicators(df.reset_index())
test_len = int(len(df) * 0.2)
train_len = int(len(df)) - test_len
train_df = df[:train_len]
test_df = df[train_len:]
train_env = DummyVecEnv([lambda: BitcoinTradingEnv(
train_df, reward_func="calmar", forecast_len=int(params['forecast_len']), confidence_interval=params['confidence_interval'])])
test_env = DummyVecEnv([lambda: BitcoinTradingEnv(
test_df, reward_func="calmar", forecast_len=int(params['forecast_len']), confidence_interval=params['confidence_interval'])])
model_params = {
'n_steps': int(params['n_steps']),
'gamma': params['gamma'],
'learning_rate': params['learning_rate'],
'ent_coef': params['ent_coef'],
'cliprange': params['cliprange'],
'noptepochs': int(params['noptepochs']),
'lam': params['lam'],
}
curr_idx = -1
model = PPO2(MlpLnLstmPolicy, train_env, verbose=0, nminibatches=1,
tensorboard_log="./tensorboard", **model_params)
# curr_idx = 2
# model = PPO2.load('./agents/ppo2_calmar_' + str(curr_idx) + '.pkl', env=train_env)
for idx in range(curr_idx + 1, 5):
print('[', idx, '] Training for: ', train_len, ' time steps')
model.learn(total_timesteps=train_len)
obs = test_env.reset()
done, reward_sum = False, 0
while not done:
action, _states = model.predict(obs)
obs, reward, done, info = test_env.step(action)
reward_sum += reward
print('[', idx, '] Total reward: ', reward_sum, ' (calmar)')
model.save('./agents/ppo2_calmar_' + str(idx) + '.pkl')