|
| 1 | +#================================================================ |
| 2 | +# |
| 3 | +# File name : RL-Bitcoin-trading-bot_3.py |
| 4 | +# Author : PyLessons |
| 5 | +# Created date: 2020-12-20 |
| 6 | +# Website : https://pylessons.com/ |
| 7 | +# GitHub : https://github.com/pythonlessons/RL-Bitcoin-trading-bot |
| 8 | +# Description : Trading Crypto with Reinforcement Learning #3 |
| 9 | +# |
| 10 | +#================================================================ |
| 11 | +import os |
| 12 | +os.environ['CUDA_VISIBLE_DEVICES'] = '0' |
| 13 | +import copy |
| 14 | +import pandas as pd |
| 15 | +import numpy as np |
| 16 | +import random |
| 17 | +from collections import deque |
| 18 | +from tensorboardX import SummaryWriter |
| 19 | +from tensorflow.keras.optimizers import Adam, RMSprop |
| 20 | + |
| 21 | +from model import Actor_Model, Critic_Model |
| 22 | +from utils import TradingGraph, Write_to_file |
| 23 | + |
| 24 | + |
| 25 | +class CustomEnv: |
| 26 | + # A custom Bitcoin trading environment |
| 27 | + def __init__(self, df, initial_balance=1000, lookback_window_size=50, Render_range = 100): |
| 28 | + # Define action space and state size and other custom parameters |
| 29 | + self.df = df.dropna().reset_index() |
| 30 | + self.df_total_steps = len(self.df)-1 |
| 31 | + self.initial_balance = initial_balance |
| 32 | + self.lookback_window_size = lookback_window_size |
| 33 | + self.Render_range = Render_range # render range in visualization |
| 34 | + |
| 35 | + # Action space from 0 to 3, 0 is hold, 1 is buy, 2 is sell |
| 36 | + self.action_space = np.array([0, 1, 2]) |
| 37 | + |
| 38 | + # Orders history contains the balance, net_worth, crypto_bought, crypto_sold, crypto_held values for the last lookback_window_size steps |
| 39 | + self.orders_history = deque(maxlen=self.lookback_window_size) |
| 40 | + |
| 41 | + # Market history contains the OHCL values for the last lookback_window_size prices |
| 42 | + self.market_history = deque(maxlen=self.lookback_window_size) |
| 43 | + |
| 44 | + # State size contains Market+Orders history for the last lookback_window_size steps |
| 45 | + self.state_size = (self.lookback_window_size, 10) |
| 46 | + |
| 47 | + # Neural Networks part bellow |
| 48 | + self.lr = 0.00001 |
| 49 | + self.epochs = 1 |
| 50 | + self.normalize_value = 100000 |
| 51 | + self.optimizer = Adam |
| 52 | + |
| 53 | + # Create Actor-Critic network model |
| 54 | + self.Actor = Actor_Model(input_shape=self.state_size, action_space = self.action_space.shape[0], lr=self.lr, optimizer = self.optimizer) |
| 55 | + self.Critic = Critic_Model(input_shape=self.state_size, action_space = self.action_space.shape[0], lr=self.lr, optimizer = self.optimizer) |
| 56 | + |
| 57 | + # create tensorboard writer |
| 58 | + def create_writer(self): |
| 59 | + self.replay_count = 0 |
| 60 | + self.writer = SummaryWriter(comment="Crypto_trader") |
| 61 | + |
| 62 | + # Reset the state of the environment to an initial state |
| 63 | + def reset(self, env_steps_size = 0): |
| 64 | + self.visualization = TradingGraph(Render_range=self.Render_range) # init visualization |
| 65 | + self.trades = deque(maxlen=self.Render_range) # limited orders memory for visualization |
| 66 | + |
| 67 | + self.balance = self.initial_balance |
| 68 | + self.net_worth = self.initial_balance |
| 69 | + self.prev_net_worth = self.initial_balance |
| 70 | + self.crypto_held = 0 |
| 71 | + self.crypto_sold = 0 |
| 72 | + self.crypto_bought = 0 |
| 73 | + self.episode_orders = 0 # test |
| 74 | + self.env_steps_size = env_steps_size |
| 75 | + if env_steps_size > 0: # used for training dataset |
| 76 | + self.start_step = random.randint(self.lookback_window_size, self.df_total_steps - env_steps_size) |
| 77 | + self.end_step = self.start_step + env_steps_size |
| 78 | + else: # used for testing dataset |
| 79 | + self.start_step = self.lookback_window_size |
| 80 | + self.end_step = self.df_total_steps |
| 81 | + |
| 82 | + self.current_step = self.start_step |
| 83 | + |
| 84 | + for i in reversed(range(self.lookback_window_size)): |
| 85 | + current_step = self.current_step - i |
| 86 | + self.orders_history.append([self.balance, self.net_worth, self.crypto_bought, self.crypto_sold, self.crypto_held]) |
| 87 | + self.market_history.append([self.df.loc[current_step, 'Open'], |
| 88 | + self.df.loc[current_step, 'High'], |
| 89 | + self.df.loc[current_step, 'Low'], |
| 90 | + self.df.loc[current_step, 'Close'], |
| 91 | + self.df.loc[current_step, 'Volume'] |
| 92 | + ]) |
| 93 | + |
| 94 | + state = np.concatenate((self.market_history, self.orders_history), axis=1) |
| 95 | + return state |
| 96 | + |
| 97 | + # Get the data points for the given current_step |
| 98 | + def _next_observation(self): |
| 99 | + self.market_history.append([self.df.loc[self.current_step, 'Open'], |
| 100 | + self.df.loc[self.current_step, 'High'], |
| 101 | + self.df.loc[self.current_step, 'Low'], |
| 102 | + self.df.loc[self.current_step, 'Close'], |
| 103 | + self.df.loc[self.current_step, 'Volume'] |
| 104 | + ]) |
| 105 | + obs = np.concatenate((self.market_history, self.orders_history), axis=1) |
| 106 | + return obs |
| 107 | + |
| 108 | + # Execute one time step within the environment |
| 109 | + def step(self, action): |
| 110 | + self.crypto_bought = 0 |
| 111 | + self.crypto_sold = 0 |
| 112 | + self.current_step += 1 |
| 113 | + |
| 114 | + # Set the current price to a random price between open and close |
| 115 | + current_price = random.uniform( |
| 116 | + self.df.loc[self.current_step, 'Open'], |
| 117 | + self.df.loc[self.current_step, 'Close']) |
| 118 | + Date = self.df.loc[self.current_step, 'Date'] # for visualization |
| 119 | + High = self.df.loc[self.current_step, 'High'] # for visualization |
| 120 | + Low = self.df.loc[self.current_step, 'Low'] # for visualization |
| 121 | + |
| 122 | + if action == 0: # Hold |
| 123 | + pass |
| 124 | + |
| 125 | + elif action == 1 and self.balance > self.initial_balance/100: |
| 126 | + # Buy with 100% of current balance |
| 127 | + self.crypto_bought = self.balance / current_price |
| 128 | + self.balance -= self.crypto_bought * current_price |
| 129 | + self.crypto_held += self.crypto_bought |
| 130 | + self.trades.append({'Date' : Date, 'High' : High, 'Low' : Low, 'total': self.crypto_bought, 'type': "buy"}) |
| 131 | + self.episode_orders += 1 |
| 132 | + |
| 133 | + elif action == 2 and self.crypto_held>0: |
| 134 | + # Sell 100% of current crypto held |
| 135 | + self.crypto_sold = self.crypto_held |
| 136 | + self.balance += self.crypto_sold * current_price |
| 137 | + self.crypto_held -= self.crypto_sold |
| 138 | + self.trades.append({'Date' : Date, 'High' : High, 'Low' : Low, 'total': self.crypto_sold, 'type': "sell"}) |
| 139 | + self.episode_orders += 1 |
| 140 | + |
| 141 | + self.prev_net_worth = self.net_worth |
| 142 | + self.net_worth = self.balance + self.crypto_held * current_price |
| 143 | + |
| 144 | + self.orders_history.append([self.balance, self.net_worth, self.crypto_bought, self.crypto_sold, self.crypto_held]) |
| 145 | + #Write_to_file(Date, self.orders_history[-1]) |
| 146 | + |
| 147 | + # Calculate reward |
| 148 | + reward = self.net_worth - self.prev_net_worth |
| 149 | + |
| 150 | + if self.net_worth <= self.initial_balance/2: |
| 151 | + done = True |
| 152 | + else: |
| 153 | + done = False |
| 154 | + |
| 155 | + obs = self._next_observation() / self.normalize_value |
| 156 | + |
| 157 | + return obs, reward, done |
| 158 | + |
| 159 | + # render environment |
| 160 | + def render(self, visualize = False): |
| 161 | + #print(f'Step: {self.current_step}, Net Worth: {self.net_worth}') |
| 162 | + if visualize: |
| 163 | + Date = self.df.loc[self.current_step, 'Date'] |
| 164 | + Open = self.df.loc[self.current_step, 'Open'] |
| 165 | + Close = self.df.loc[self.current_step, 'Close'] |
| 166 | + High = self.df.loc[self.current_step, 'High'] |
| 167 | + Low = self.df.loc[self.current_step, 'Low'] |
| 168 | + Volume = self.df.loc[self.current_step, 'Volume'] |
| 169 | + |
| 170 | + # Render the environment to the screen |
| 171 | + self.visualization.render(Date, Open, High, Low, Close, Volume, self.net_worth, self.trades) |
| 172 | + |
| 173 | + def get_gaes(self, rewards, dones, values, next_values, gamma = 0.99, lamda = 0.95, normalize=True): |
| 174 | + deltas = [r + gamma * (1 - d) * nv - v for r, d, nv, v in zip(rewards, dones, next_values, values)] |
| 175 | + deltas = np.stack(deltas) |
| 176 | + gaes = copy.deepcopy(deltas) |
| 177 | + for t in reversed(range(len(deltas) - 1)): |
| 178 | + gaes[t] = gaes[t] + (1 - dones[t]) * gamma * lamda * gaes[t + 1] |
| 179 | + |
| 180 | + target = gaes + values |
| 181 | + if normalize: |
| 182 | + gaes = (gaes - gaes.mean()) / (gaes.std() + 1e-8) |
| 183 | + return np.vstack(gaes), np.vstack(target) |
| 184 | + |
| 185 | + def replay(self, states, actions, rewards, predictions, dones, next_states): |
| 186 | + # reshape memory to appropriate shape for training |
| 187 | + states = np.vstack(states) |
| 188 | + next_states = np.vstack(next_states) |
| 189 | + actions = np.vstack(actions) |
| 190 | + predictions = np.vstack(predictions) |
| 191 | + |
| 192 | + # Compute discounted rewards |
| 193 | + #discounted_r = np.vstack(self.discount_rewards(rewards)) |
| 194 | + |
| 195 | + # Get Critic network predictions |
| 196 | + values = self.Critic.predict(states) |
| 197 | + next_values = self.Critic.predict(next_states) |
| 198 | + # Compute advantages |
| 199 | + #advantages = discounted_r - values |
| 200 | + advantages, target = self.get_gaes(rewards, dones, np.squeeze(values), np.squeeze(next_values)) |
| 201 | + ''' |
| 202 | + pylab.plot(target,'-') |
| 203 | + pylab.plot(advantages,'.') |
| 204 | + ax=pylab.gca() |
| 205 | + ax.grid(True) |
| 206 | + pylab.show() |
| 207 | + ''' |
| 208 | + # stack everything to numpy array |
| 209 | + y_true = np.hstack([advantages, predictions, actions]) |
| 210 | + |
| 211 | + # training Actor and Critic networks |
| 212 | + a_loss = self.Actor.Actor.fit(states, y_true, epochs=self.epochs, verbose=0, shuffle=True) |
| 213 | + c_loss = self.Critic.Critic.fit(states, target, epochs=self.epochs, verbose=0, shuffle=True) |
| 214 | + |
| 215 | + self.writer.add_scalar('Data/actor_loss_per_replay', np.sum(a_loss.history['loss']), self.replay_count) |
| 216 | + self.writer.add_scalar('Data/critic_loss_per_replay', np.sum(c_loss.history['loss']), self.replay_count) |
| 217 | + self.replay_count += 1 |
| 218 | + |
| 219 | + def act(self, state): |
| 220 | + # Use the network to predict the next action to take, using the model |
| 221 | + prediction = self.Actor.predict(np.expand_dims(state, axis=0))[0] |
| 222 | + action = np.random.choice(self.action_space, p=prediction) |
| 223 | + return action, prediction |
| 224 | + |
| 225 | + def save(self, name="Crypto_trader"): |
| 226 | + # save keras model weights |
| 227 | + self.Actor.Actor.save_weights(f"{name}_Actor.h5") |
| 228 | + self.Critic.Critic.save_weights(f"{name}_Critic.h5") |
| 229 | + |
| 230 | + def load(self, name="Crypto_trader"): |
| 231 | + # load keras model weights |
| 232 | + self.Actor.Actor.load_weights(f"{name}_Actor.h5") |
| 233 | + self.Critic.Critic.load_weights(f"{name}_Critic.h5") |
| 234 | + |
| 235 | +def Random_games(env, visualize, train_episodes = 50): |
| 236 | + average_net_worth = 0 |
| 237 | + for episode in range(train_episodes): |
| 238 | + state = env.reset() |
| 239 | + while True: |
| 240 | + env.render(visualize) |
| 241 | + action = np.random.randint(3, size=1)[0] |
| 242 | + state, reward, done = env.step(action) |
| 243 | + if env.current_step == env.end_step: |
| 244 | + average_net_worth += env.net_worth |
| 245 | + print("net_worth:", episode, env.net_worth) |
| 246 | + break |
| 247 | + |
| 248 | + print("average {} episodes random net_worth: {}".format(train_episodes, average_net_worth/train_episodes)) |
| 249 | + |
| 250 | +def train_agent(env, visualize=False, train_episodes = 50, training_batch_size=500): |
| 251 | + env.create_writer() # create TensorBoard writer |
| 252 | + total_average = deque(maxlen=100) # save recent 100 episodes net worth |
| 253 | + best_average = 0 # used to track best average net worth |
| 254 | + for episode in range(train_episodes): |
| 255 | + state = env.reset(env_steps_size = training_batch_size) |
| 256 | + |
| 257 | + states, actions, rewards, predictions, dones, next_states = [], [], [], [], [], [] |
| 258 | + for t in range(training_batch_size): |
| 259 | + env.render(visualize) |
| 260 | + action, prediction = env.act(state) |
| 261 | + next_state, reward, done = env.step(action) |
| 262 | + states.append(np.expand_dims(state, axis=0)) |
| 263 | + next_states.append(np.expand_dims(next_state, axis=0)) |
| 264 | + action_onehot = np.zeros(3) |
| 265 | + action_onehot[action] = 1 |
| 266 | + actions.append(action_onehot) |
| 267 | + rewards.append(reward) |
| 268 | + dones.append(done) |
| 269 | + predictions.append(prediction) |
| 270 | + state = next_state |
| 271 | + |
| 272 | + env.replay(states, actions, rewards, predictions, dones, next_states) |
| 273 | + total_average.append(env.net_worth) |
| 274 | + average = np.average(total_average) |
| 275 | + |
| 276 | + env.writer.add_scalar('Data/average net_worth', average, episode) |
| 277 | + env.writer.add_scalar('Data/episode_orders', env.episode_orders, episode) |
| 278 | + |
| 279 | + print("net worth {} {:.2f} {:.2f} {}".format(episode, env.net_worth, average, env.episode_orders)) |
| 280 | + if episode > len(total_average): |
| 281 | + if best_average < average: |
| 282 | + best_average = average |
| 283 | + print("Saving model") |
| 284 | + env.save() |
| 285 | + |
| 286 | +def test_agent(env, visualize=True, test_episodes=10): |
| 287 | + env.load() # load the model |
| 288 | + average_net_worth = 0 |
| 289 | + for episode in range(test_episodes): |
| 290 | + state = env.reset() |
| 291 | + while True: |
| 292 | + env.render(visualize) |
| 293 | + action, prediction = env.act(state) |
| 294 | + state, reward, done = env.step(action) |
| 295 | + if env.current_step == env.end_step: |
| 296 | + average_net_worth += env.net_worth |
| 297 | + print("net_worth:", episode, env.net_worth, env.episode_orders) |
| 298 | + break |
| 299 | + |
| 300 | + print("average {} episodes agent net_worth: {}".format(test_episodes, average_net_worth/test_episodes)) |
| 301 | + |
| 302 | +df = pd.read_csv('./pricedata.csv') |
| 303 | +df = df.sort_values('Date') |
| 304 | + |
| 305 | +lookback_window_size = 50 |
| 306 | +train_df = df[:-720-lookback_window_size] |
| 307 | +test_df = df[-720-lookback_window_size:] # 30 days |
| 308 | + |
| 309 | +train_env = CustomEnv(train_df, lookback_window_size=lookback_window_size) |
| 310 | +test_env = CustomEnv(test_df, lookback_window_size=lookback_window_size) |
| 311 | + |
| 312 | +#train_agent(train_env, visualize=False, train_episodes=20000, training_batch_size=500) |
| 313 | +test_agent(test_env, visualize=True, test_episodes=1000) |
| 314 | +Random_games(test_env, visualize=False, train_episodes = 1000) |
0 commit comments