|
| 1 | +#================================================================ |
| 2 | +# |
| 3 | +# File name : RL-Bitcoin-trading-bot_2.py |
| 4 | +# Author : PyLessons |
| 5 | +# Created date: 2020-12-12 |
| 6 | +# Website : https://pylessons.com/ |
| 7 | +# GitHub : https://github.com/pythonlessons/RL-Bitcoin-trading-bot |
| 8 | +# Description : Trading Crypto with Reinforcement Learning #2 |
| 9 | +# |
| 10 | +#================================================================ |
| 11 | +import pandas as pd |
| 12 | +import numpy as np |
| 13 | +import random |
| 14 | +from collections import deque |
| 15 | +from utils import TradingGraph, Write_to_file |
| 16 | + |
| 17 | +class CustomEnv: |
| 18 | + # A custom Bitcoin trading environment |
| 19 | + def __init__(self, df, initial_balance=1000, lookback_window_size=50, Render_range = 100): |
| 20 | + # Define action space and state size and other custom parameters |
| 21 | + self.df = df.dropna().reset_index() |
| 22 | + self.df_total_steps = len(self.df)-1 |
| 23 | + self.initial_balance = initial_balance |
| 24 | + self.lookback_window_size = lookback_window_size |
| 25 | + self.Render_range = Render_range # render range in visualization |
| 26 | + |
| 27 | + # Action space from 0 to 3, 0 is hold, 1 is buy, 2 is sell |
| 28 | + self.action_space = np.array([0, 1, 2]) |
| 29 | + |
| 30 | + # Orders history contains the balance, net_worth, crypto_bought, crypto_sold, crypto_held values for the last lookback_window_size steps |
| 31 | + self.orders_history = deque(maxlen=self.lookback_window_size) |
| 32 | + |
| 33 | + # Market history contains the OHCL values for the last lookback_window_size prices |
| 34 | + self.market_history = deque(maxlen=self.lookback_window_size) |
| 35 | + |
| 36 | + # State size contains Market+Orders history for the last lookback_window_size steps |
| 37 | + self.state_size = (self.lookback_window_size, 10) |
| 38 | + |
| 39 | + # Reset the state of the environment to an initial state |
| 40 | + def reset(self, env_steps_size = 0): |
| 41 | + self.visualization = TradingGraph(Render_range=self.Render_range) # init visualization |
| 42 | + self.trades = deque(maxlen=self.Render_range) # limited orders memory for visualization |
| 43 | + |
| 44 | + self.balance = self.initial_balance |
| 45 | + self.net_worth = self.initial_balance |
| 46 | + self.prev_net_worth = self.initial_balance |
| 47 | + self.crypto_held = 0 |
| 48 | + self.crypto_sold = 0 |
| 49 | + self.crypto_bought = 0 |
| 50 | + if env_steps_size > 0: # used for training dataset |
| 51 | + self.start_step = random.randint(self.lookback_window_size, self.df_total_steps - env_steps_size) |
| 52 | + self.end_step = self.start_step + env_steps_size |
| 53 | + else: # used for testing dataset |
| 54 | + self.start_step = self.lookback_window_size |
| 55 | + self.end_step = self.df_total_steps |
| 56 | + |
| 57 | + self.current_step = self.start_step |
| 58 | + |
| 59 | + for i in reversed(range(self.lookback_window_size)): |
| 60 | + current_step = self.current_step - i |
| 61 | + self.orders_history.append([self.balance, self.net_worth, self.crypto_bought, self.crypto_sold, self.crypto_held]) |
| 62 | + self.market_history.append([self.df.loc[current_step, 'Open'], |
| 63 | + self.df.loc[current_step, 'High'], |
| 64 | + self.df.loc[current_step, 'Low'], |
| 65 | + self.df.loc[current_step, 'Close'], |
| 66 | + self.df.loc[current_step, 'Volume'] |
| 67 | + ]) |
| 68 | + |
| 69 | + state = np.concatenate((self.market_history, self.orders_history), axis=1) |
| 70 | + return state |
| 71 | + |
| 72 | + # Get the data points for the given current_step |
| 73 | + def _next_observation(self): |
| 74 | + self.market_history.append([self.df.loc[self.current_step, 'Open'], |
| 75 | + self.df.loc[self.current_step, 'High'], |
| 76 | + self.df.loc[self.current_step, 'Low'], |
| 77 | + self.df.loc[self.current_step, 'Close'], |
| 78 | + self.df.loc[self.current_step, 'Volume'] |
| 79 | + ]) |
| 80 | + obs = np.concatenate((self.market_history, self.orders_history), axis=1) |
| 81 | + return obs |
| 82 | + |
| 83 | + # Execute one time step within the environment |
| 84 | + def step(self, action): |
| 85 | + self.crypto_bought = 0 |
| 86 | + self.crypto_sold = 0 |
| 87 | + self.current_step += 1 |
| 88 | + |
| 89 | + # Set the current price to a random price between open and close |
| 90 | + current_price = random.uniform( |
| 91 | + self.df.loc[self.current_step, 'Open'], |
| 92 | + self.df.loc[self.current_step, 'Close']) |
| 93 | + Date = self.df.loc[self.current_step, 'Date'] # for visualization |
| 94 | + High = self.df.loc[self.current_step, 'High'] # for visualization |
| 95 | + Low = self.df.loc[self.current_step, 'Low'] # for visualization |
| 96 | + |
| 97 | + if action == 0: # Hold |
| 98 | + pass |
| 99 | + |
| 100 | + elif action == 1 and self.balance > self.initial_balance/100: |
| 101 | + # Buy with 100% of current balance |
| 102 | + self.crypto_bought = self.balance / current_price |
| 103 | + self.balance -= self.crypto_bought * current_price |
| 104 | + self.crypto_held += self.crypto_bought |
| 105 | + self.trades.append({'Date' : Date, 'High' : High, 'Low' : Low, 'total': self.crypto_bought, 'type': "buy"}) |
| 106 | + |
| 107 | + elif action == 2 and self.crypto_held>0: |
| 108 | + # Sell 100% of current crypto held |
| 109 | + self.crypto_sold = self.crypto_held |
| 110 | + self.balance += self.crypto_sold * current_price |
| 111 | + self.crypto_held -= self.crypto_sold |
| 112 | + self.trades.append({'Date' : Date, 'High' : High, 'Low' : Low, 'total': self.crypto_sold, 'type': "sell"}) |
| 113 | + |
| 114 | + self.prev_net_worth = self.net_worth |
| 115 | + self.net_worth = self.balance + self.crypto_held * current_price |
| 116 | + |
| 117 | + self.orders_history.append([self.balance, self.net_worth, self.crypto_bought, self.crypto_sold, self.crypto_held]) |
| 118 | + #Write_to_file(Date, self.orders_history[-1]) |
| 119 | + |
| 120 | + # Calculate reward |
| 121 | + reward = self.net_worth - self.prev_net_worth |
| 122 | + |
| 123 | + if self.net_worth <= self.initial_balance/2: |
| 124 | + done = True |
| 125 | + else: |
| 126 | + done = False |
| 127 | + |
| 128 | + obs = self._next_observation() |
| 129 | + |
| 130 | + return obs, reward, done |
| 131 | + |
| 132 | + # render environment |
| 133 | + def render(self, visualize = False): |
| 134 | + #print(f'Step: {self.current_step}, Net Worth: {self.net_worth}') |
| 135 | + if visualize: |
| 136 | + Date = self.df.loc[self.current_step, 'Date'] |
| 137 | + Open = self.df.loc[self.current_step, 'Open'] |
| 138 | + Close = self.df.loc[self.current_step, 'Close'] |
| 139 | + High = self.df.loc[self.current_step, 'High'] |
| 140 | + Low = self.df.loc[self.current_step, 'Low'] |
| 141 | + Volume = self.df.loc[self.current_step, 'Volume'] |
| 142 | + |
| 143 | + # Render the environment to the screen |
| 144 | + self.visualization.render(Date, Open, High, Low, Close, Volume, self.net_worth, self.trades) |
| 145 | + |
| 146 | + |
| 147 | +def Random_games(env, visualize, train_episodes = 50, training_batch_size=500): |
| 148 | + average_net_worth = 0 |
| 149 | + for episode in range(train_episodes): |
| 150 | + state = env.reset(env_steps_size = training_batch_size) |
| 151 | + while True: |
| 152 | + env.render(visualize) |
| 153 | + |
| 154 | + action = np.random.randint(3, size=1)[0] |
| 155 | + |
| 156 | + state, reward, done = env.step(action) |
| 157 | + |
| 158 | + if env.current_step == env.end_step: |
| 159 | + average_net_worth += env.net_worth |
| 160 | + print("net_worth:", env.net_worth) |
| 161 | + break |
| 162 | + |
| 163 | + print("average_net_worth:", average_net_worth/train_episodes) |
| 164 | + |
| 165 | + |
| 166 | +df = pd.read_csv('./pricedata.csv') |
| 167 | +df = df.sort_values('Date') |
| 168 | + |
| 169 | +lookback_window_size = 50 |
| 170 | +train_df = df[:-720-lookback_window_size] |
| 171 | +test_df = df[-720-lookback_window_size:] # 30 days |
| 172 | + |
| 173 | +train_env = CustomEnv(train_df, lookback_window_size=lookback_window_size) |
| 174 | +test_env = CustomEnv(test_df, lookback_window_size=lookback_window_size) |
| 175 | + |
| 176 | +Random_games(test_env, visualize=True, train_episodes = 1, training_batch_size=300) |
0 commit comments