|
| 1 | +import process_data |
| 2 | +import pandas as pd |
| 3 | +import random |
| 4 | +import gym |
| 5 | +from gym import spaces |
| 6 | +from gym.utils import seeding |
| 7 | +import numpy as np |
| 8 | +import math |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +# position constant |
| 12 | +LONG = 0 |
| 13 | +SHORT = 1 |
| 14 | +FLAT = 2 |
| 15 | + |
| 16 | +# action constant |
| 17 | +BUY = 0 |
| 18 | +SELL = 1 |
| 19 | +HOLD = 2 |
| 20 | + |
| 21 | +class OhlcvEnv(gym.Env): |
| 22 | + |
| 23 | + def __init__(self, window_size, path, show_trade=True): |
| 24 | + self.show_trade = show_trade |
| 25 | + self.path = path |
| 26 | + self.actions = ["LONG", "SHORT", "FLAT"] |
| 27 | + self.fee = 0.0005 |
| 28 | + self.seed() |
| 29 | + self.file_list = [] |
| 30 | + # load_csv |
| 31 | + self.load_from_csv() |
| 32 | + |
| 33 | + # n_features |
| 34 | + self.window_size = window_size |
| 35 | + self.n_features = self.df.shape[1] |
| 36 | + self.shape = (self.window_size, self.n_features+4) |
| 37 | + |
| 38 | + # defines action space |
| 39 | + self.action_space = spaces.Discrete(len(self.actions)) |
| 40 | + self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=self.shape, dtype=np.float32) |
| 41 | + |
| 42 | + def load_from_csv(self): |
| 43 | + if(len(self.file_list) == 0): |
| 44 | + self.file_list = [x.name for x in Path(self.path).iterdir() if x.is_file()] |
| 45 | + self.file_list.sort() |
| 46 | + self.rand_episode = self.file_list.pop() |
| 47 | + raw_df= pd.read_csv(self.path + self.rand_episode) |
| 48 | + extractor = process_data.FeatureExtractor(raw_df) |
| 49 | + self.df = extractor.add_bar_features() # bar features o, h, l, c ---> C(4,2) = 4*3/2*1 = 6 features |
| 50 | + |
| 51 | + ## selected manual fetuares |
| 52 | + feature_list = [ |
| 53 | + 'bar_hc', |
| 54 | + 'bar_ho', |
| 55 | + 'bar_hl', |
| 56 | + 'bar_cl', |
| 57 | + 'bar_ol', |
| 58 | + 'bar_co', 'close'] |
| 59 | + self.df.dropna(inplace=True) # drops Nan rows |
| 60 | + self.closingPrices = self.df['close'].values |
| 61 | + self.df = self.df[feature_list].values |
| 62 | + |
| 63 | + def render(self, mode='human', verbose=False): |
| 64 | + return None |
| 65 | + |
| 66 | + def seed(self, seed=None): |
| 67 | + self.np_random, seed = seeding.np_random(seed) |
| 68 | + return [seed] |
| 69 | + |
| 70 | + def step(self, action): |
| 71 | + |
| 72 | + if self.done: |
| 73 | + return self.state, self.reward, self.done, {} |
| 74 | + self.reward = 0 |
| 75 | + |
| 76 | + # action comes from the agent |
| 77 | + # 0 buy, 1 sell, 2 hold |
| 78 | + # single position can be opened per trade |
| 79 | + # valid action sequence would be |
| 80 | + # LONG : buy - hold - hold - sell |
| 81 | + # SHORT : sell - hold - hold - buy |
| 82 | + # invalid action sequence is just considered hold |
| 83 | + # (e.g.) "buy - buy" would be considred "buy - hold" |
| 84 | + self.action = HOLD # hold |
| 85 | + if action == BUY: # buy |
| 86 | + if self.position == FLAT: # if previous position was flat |
| 87 | + self.position = LONG # update position to long |
| 88 | + self.action = BUY # record action as buy |
| 89 | + self.entry_price = self.closingPrice # maintain entry price |
| 90 | + elif self.position == SHORT: # if previous position was short |
| 91 | + self.position = FLAT # update position to flat |
| 92 | + self.action = BUY # record action as buy |
| 93 | + self.exit_price = self.closingPrice |
| 94 | + self.reward += ((self.entry_price - self.exit_price)/self.exit_price + 1)*(1-self.fee)**2 - 1 # calculate reward |
| 95 | + self.krw_balance = self.krw_balance * (1.0 + self.reward) # evaluate cumulative return in krw-won |
| 96 | + self.entry_price = 0 # clear entry price |
| 97 | + self.n_short += 1 # record number of short |
| 98 | + elif action == 1: # vice versa for short trade |
| 99 | + if self.position == FLAT: |
| 100 | + self.position = SHORT |
| 101 | + self.action = 1 |
| 102 | + self.entry_price = self.closingPrice |
| 103 | + elif self.position == LONG: |
| 104 | + self.position = FLAT |
| 105 | + self.action = 1 |
| 106 | + self.exit_price = self.closingPrice |
| 107 | + self.reward += ((self.exit_price - self.entry_price)/self.entry_price + 1)*(1-self.fee)**2 - 1 |
| 108 | + self.krw_balance = self.krw_balance * (1.0 + self.reward) |
| 109 | + self.entry_price = 0 |
| 110 | + self.n_long += 1 |
| 111 | + |
| 112 | + # [coin + krw_won] total value evaluated in krw won |
| 113 | + if(self.position == LONG): |
| 114 | + temp_reward = ((self.closingPrice - self.entry_price)/self.entry_price + 1)*(1-self.fee)**2 - 1 |
| 115 | + new_portfolio = self.krw_balance * (1.0 + temp_reward) |
| 116 | + elif(self.position == SHORT): |
| 117 | + temp_reward = ((self.entry_price - self.closingPrice)/self.closingPrice + 1)*(1-self.fee)**2 - 1 |
| 118 | + new_portfolio = self.krw_balance * (1.0 + temp_reward) |
| 119 | + else: |
| 120 | + temp_reward = 0 |
| 121 | + new_portfolio = self.krw_balance |
| 122 | + |
| 123 | + self.portfolio = new_portfolio |
| 124 | + self.current_tick += 1 |
| 125 | + if(self.show_trade and self.current_tick%100 == 0): |
| 126 | + print("Tick: {0}/ Portfolio (USD): {1}".format(self.current_tick, self.portfolio)) |
| 127 | + print("Long: {0}/ Short: {1}".format(self.n_long, self.n_short)) |
| 128 | + self.history.append((self.action, self.current_tick, self.closingPrice, self.portfolio, self.reward)) |
| 129 | + self.updateState() |
| 130 | + if (self.current_tick > (self.df.shape[0]) - self.window_size-1): |
| 131 | + self.done = True |
| 132 | + self.reward = self.get_profit() # return reward at end of the game |
| 133 | + return self.state, self.reward, self.done, {'portfolio':np.array([self.portfolio]), |
| 134 | + "history":self.history, |
| 135 | + "n_trades":{'long':self.n_long, 'short':self.n_short}} |
| 136 | + |
| 137 | + def get_profit(self): |
| 138 | + if(self.position == LONG): |
| 139 | + profit = ((self.closingPrice - self.entry_price)/self.entry_price + 1)*(1-self.fee)**2 - 1 |
| 140 | + elif(self.position == SHORT): |
| 141 | + profit = ((self.entry_price - self.closingPrice)/self.closingPrice + 1)*(1-self.fee)**2 - 1 |
| 142 | + else: |
| 143 | + profit = 0 |
| 144 | + return profit |
| 145 | + |
| 146 | + def reset(self): |
| 147 | + # self.current_tick = random.randint(0, self.df.shape[0]-1000) |
| 148 | + self.current_tick = 0 |
| 149 | + print("start episode ... {0} at {1}" .format(self.rand_episode, self.current_tick)) |
| 150 | + |
| 151 | + # positions |
| 152 | + self.n_long = 0 |
| 153 | + self.n_short = 0 |
| 154 | + |
| 155 | + # clear internal variables |
| 156 | + self.history = [] # keep buy, sell, hold action history |
| 157 | + self.krw_balance = 1000 # initial balance, u can change it to whatever u like |
| 158 | + self.portfolio = float(self.krw_balance) # (coin * current_price + current_krw_balance) == portfolio |
| 159 | + self.profit = 0 |
| 160 | + |
| 161 | + self.action = HOLD |
| 162 | + self.position = FLAT |
| 163 | + self.done = False |
| 164 | + |
| 165 | + self.updateState() # returns observed_features + opened position(LONG/SHORT/FLAT) + profit_earned(during opened position) |
| 166 | + return self.state |
| 167 | + |
| 168 | + |
| 169 | + def updateState(self): |
| 170 | + def one_hot_encode(x, n_classes): |
| 171 | + return np.eye(n_classes)[x] |
| 172 | + self.closingPrice = float(self.closingPrices[self.current_tick]) |
| 173 | + prev_position = self.position |
| 174 | + one_hot_position = one_hot_encode(prev_position,3) |
| 175 | + profit = self.get_profit() |
| 176 | + # append two |
| 177 | + self.state = np.concatenate((self.df[self.current_tick], one_hot_position, [profit])) |
| 178 | + return self.state |
0 commit comments