-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathtradingEnv.py
More file actions
executable file
·424 lines (354 loc) · 20.4 KB
/
tradingEnv.py
File metadata and controls
executable file
·424 lines (354 loc) · 20.4 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# coding=utf-8
"""
Goal: Implement a trading environment compatible with OpenAI Gym.
Authors: Thibaut Théate and Damien Ernst
Institution: University of Liège
"""
###############################################################################
################################### Imports ###################################
###############################################################################
import os
import gym
import math
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None
from matplotlib import pyplot as plt
from dataDownloader import AlphaVantage
from dataDownloader import YahooFinance
from dataDownloader import CSVHandler
from fictiveStockGenerator import StockGenerator
###############################################################################
################################ Global variables #############################
###############################################################################
# Boolean handling the saving of the stock market data downloaded
saving = True
# Variable related to the fictive stocks supported
fictiveStocks = ('LINEARUP', 'LINEARDOWN', 'SINUSOIDAL', 'TRIANGLE')
###############################################################################
############################## Class TradingEnv ###############################
###############################################################################
class TradingEnv(gym.Env):
"""
GOAL: Implement a custom trading environment compatible with OpenAI Gym.
VARIABLES: - data: Dataframe monitoring the trading activity.
- state: RL state to be returned to the RL agent.
- reward: RL reward to be returned to the RL agent.
- done: RL episode termination signal.
- t: Current trading time step.
- marketSymbol: Stock market symbol.
- startingDate: Beginning of the trading horizon.
- endingDate: Ending of the trading horizon.
- stateLength: Number of trading time steps included in the state.
- numberOfShares: Number of shares currently owned by the agent.
- transactionCosts: Transaction costs associated with the trading
activity (e.g. 0.01 is 1% of loss).
METHODS: - __init__: Object constructor initializing the trading environment.
- reset: Perform a soft reset of the trading environment.
- step: Transition to the next trading time step.
- render: Illustrate graphically the trading environment.
"""
def __init__(self, marketSymbol, startingDate, endingDate, money, stateLength=30,
transactionCosts=0, startingPoint=0):
"""
GOAL: Object constructor initializing the trading environment by setting up
the trading activity dataframe as well as other important variables.
INPUTS: - marketSymbol: Stock market symbol.
- startingDate: Beginning of the trading horizon.
- endingDate: Ending of the trading horizon.
- money: Initial amount of money at the disposal of the agent.
- stateLength: Number of trading time steps included in the RL state.
- transactionCosts: Transaction costs associated with the trading
activity (e.g. 0.01 is 1% of loss).
- startingPoint: Optional starting point (iteration) of the trading activity.
OUTPUTS: /
"""
# CASE 1: Fictive stock generation
if(marketSymbol in fictiveStocks):
stockGeneration = StockGenerator()
if(marketSymbol == 'LINEARUP'):
self.data = stockGeneration.linearUp(startingDate, endingDate)
elif(marketSymbol == 'LINEARDOWN'):
self.data = stockGeneration.linearDown(startingDate, endingDate)
elif(marketSymbol == 'SINUSOIDAL'):
self.data = stockGeneration.sinusoidal(startingDate, endingDate)
else:
self.data = stockGeneration.triangle(startingDate, endingDate)
# CASE 2: Real stock loading
else:
# Check if the stock market data is already present in the database
csvConverter = CSVHandler()
csvName = "".join(['Data/', marketSymbol, '_', startingDate, '_', endingDate])
exists = os.path.isfile(csvName + '.csv')
# If affirmative, load the stock market data from the database
if(exists):
self.data = csvConverter.CSVToDataframe(csvName)
# Otherwise, download the stock market data from Yahoo Finance and save it in the database
else:
downloader1 = YahooFinance()
downloader2 = AlphaVantage()
try:
self.data = downloader1.getDailyData(marketSymbol, startingDate, endingDate)
except:
self.data = downloader2.getDailyData(marketSymbol, startingDate, endingDate)
if saving == True:
csvConverter.dataframeToCSV(csvName, self.data)
# Interpolate in case of missing data
self.data.replace(0.0, np.nan, inplace=True)
self.data.interpolate(method='linear', limit=5, limit_area='inside', inplace=True)
self.data.fillna(method='ffill', inplace=True)
self.data.fillna(method='bfill', inplace=True)
self.data.fillna(0, inplace=True)
# Set the trading activity dataframe
self.data['Position'] = 0
self.data['Action'] = 0
self.data['Holdings'] = 0.
self.data['Cash'] = float(money)
self.data['Money'] = self.data['Holdings'] + self.data['Cash']
self.data['Returns'] = 0.
# Set the RL variables common to every OpenAI gym environments
self.state = [self.data['Close'][0:stateLength].tolist(),
self.data['Low'][0:stateLength].tolist(),
self.data['High'][0:stateLength].tolist(),
self.data['Volume'][0:stateLength].tolist(),
[0]]
self.reward = 0.
self.done = 0
# Set additional variables related to the trading activity
self.marketSymbol = marketSymbol
self.startingDate = startingDate
self.endingDate = endingDate
self.stateLength = stateLength
self.t = stateLength
self.numberOfShares = 0
self.transactionCosts = transactionCosts
self.epsilon = 0.1
# If required, set a custom starting point for the trading activity
if startingPoint:
self.setStartingPoint(startingPoint)
def reset(self):
"""
GOAL: Perform a soft reset of the trading environment.
INPUTS: /
OUTPUTS: - state: RL state returned to the trading strategy.
"""
# Reset the trading activity dataframe
self.data['Position'] = 0
self.data['Action'] = 0
self.data['Holdings'] = 0.
self.data['Cash'] = self.data['Cash'][0]
self.data['Money'] = self.data['Holdings'] + self.data['Cash']
self.data['Returns'] = 0.
# Reset the RL variables common to every OpenAI gym environments
self.state = [self.data['Close'][0:self.stateLength].tolist(),
self.data['Low'][0:self.stateLength].tolist(),
self.data['High'][0:self.stateLength].tolist(),
self.data['Volume'][0:self.stateLength].tolist(),
[0]]
self.reward = 0.
self.done = 0
# Reset additional variables related to the trading activity
self.t = self.stateLength
self.numberOfShares = 0
return self.state
def computeLowerBound(self, cash, numberOfShares, price):
"""
GOAL: Compute the lower bound of the complete RL action space,
i.e. the minimum number of share to trade.
INPUTS: - cash: Value of the cash owned by the agent.
- numberOfShares: Number of shares owned by the agent.
- price: Last price observed.
OUTPUTS: - lowerBound: Lower bound of the RL action space.
"""
# Computation of the RL action lower bound
deltaValues = - cash - numberOfShares * price * (1 + self.epsilon) * (1 + self.transactionCosts)
if deltaValues < 0:
lowerBound = deltaValues / (price * (2 * self.transactionCosts + (self.epsilon * (1 + self.transactionCosts))))
else:
lowerBound = deltaValues / (price * self.epsilon * (1 + self.transactionCosts))
return lowerBound
def step(self, action):
"""
GOAL: Transition to the next trading time step based on the
trading position decision made (either long or short).
INPUTS: - action: Trading decision (1 = long, 0 = short).
OUTPUTS: - state: RL state to be returned to the RL agent.
- reward: RL reward to be returned to the RL agent.
- done: RL episode termination signal (boolean).
- info: Additional information returned to the RL agent.
"""
# Stting of some local variables
t = self.t
numberOfShares = self.numberOfShares
customReward = False
# CASE 1: LONG POSITION
if(action == 1):
self.data['Position'][t] = 1
# Case a: Long -> Long
if(self.data['Position'][t - 1] == 1):
self.data['Cash'][t] = self.data['Cash'][t - 1]
self.data['Holdings'][t] = self.numberOfShares * self.data['Close'][t]
# Case b: No position -> Long
elif(self.data['Position'][t - 1] == 0):
self.numberOfShares = math.floor(self.data['Cash'][t - 1]/(self.data['Close'][t] * (1 + self.transactionCosts)))
self.data['Cash'][t] = self.data['Cash'][t - 1] - self.numberOfShares * self.data['Close'][t] * (1 + self.transactionCosts)
self.data['Holdings'][t] = self.numberOfShares * self.data['Close'][t]
self.data['Action'][t] = 1
# Case c: Short -> Long
else:
self.data['Cash'][t] = self.data['Cash'][t - 1] - self.numberOfShares * self.data['Close'][t] * (1 + self.transactionCosts)
self.numberOfShares = math.floor(self.data['Cash'][t]/(self.data['Close'][t] * (1 + self.transactionCosts)))
self.data['Cash'][t] = self.data['Cash'][t] - self.numberOfShares * self.data['Close'][t] * (1 + self.transactionCosts)
self.data['Holdings'][t] = self.numberOfShares * self.data['Close'][t]
self.data['Action'][t] = 1
# CASE 2: SHORT POSITION
elif(action == 0):
self.data['Position'][t] = -1
# Case a: Short -> Short
if(self.data['Position'][t - 1] == -1):
lowerBound = self.computeLowerBound(self.data['Cash'][t - 1], -numberOfShares, self.data['Close'][t-1])
if lowerBound <= 0:
self.data['Cash'][t] = self.data['Cash'][t - 1]
self.data['Holdings'][t] = - self.numberOfShares * self.data['Close'][t]
else:
numberOfSharesToBuy = min(math.floor(lowerBound), self.numberOfShares)
self.numberOfShares -= numberOfSharesToBuy
self.data['Cash'][t] = self.data['Cash'][t - 1] - numberOfSharesToBuy * self.data['Close'][t] * (1 + self.transactionCosts)
self.data['Holdings'][t] = - self.numberOfShares * self.data['Close'][t]
customReward = True
# Case b: No position -> Short
elif(self.data['Position'][t - 1] == 0):
self.numberOfShares = math.floor(self.data['Cash'][t - 1]/(self.data['Close'][t] * (1 + self.transactionCosts)))
self.data['Cash'][t] = self.data['Cash'][t - 1] + self.numberOfShares * self.data['Close'][t] * (1 - self.transactionCosts)
self.data['Holdings'][t] = - self.numberOfShares * self.data['Close'][t]
self.data['Action'][t] = -1
# Case c: Long -> Short
else:
self.data['Cash'][t] = self.data['Cash'][t - 1] + self.numberOfShares * self.data['Close'][t] * (1 - self.transactionCosts)
self.numberOfShares = math.floor(self.data['Cash'][t]/(self.data['Close'][t] * (1 + self.transactionCosts)))
self.data['Cash'][t] = self.data['Cash'][t] + self.numberOfShares * self.data['Close'][t] * (1 - self.transactionCosts)
self.data['Holdings'][t] = - self.numberOfShares * self.data['Close'][t]
self.data['Action'][t] = -1
# CASE 3: PROHIBITED ACTION
else:
raise SystemExit("Prohibited action! Action should be either 1 (long) or 0 (short).")
# Update the total amount of money owned by the agent, as well as the return generated
self.data['Money'][t] = self.data['Holdings'][t] + self.data['Cash'][t]
self.data['Returns'][t] = (self.data['Money'][t] - self.data['Money'][t-1])/self.data['Money'][t-1]
# Set the RL reward returned to the trading agent
if not customReward:
self.reward = self.data['Returns'][t]
else:
self.reward = (self.data['Close'][t-1] - self.data['Close'][t])/self.data['Close'][t-1]
# Transition to the next trading time step
self.t = self.t + 1
self.state = [self.data['Close'][self.t - self.stateLength : self.t].tolist(),
self.data['Low'][self.t - self.stateLength : self.t].tolist(),
self.data['High'][self.t - self.stateLength : self.t].tolist(),
self.data['Volume'][self.t - self.stateLength : self.t].tolist(),
[self.data['Position'][self.t - 1]]]
if(self.t == self.data.shape[0]):
self.done = 1
# Same reasoning with the other action (exploration trick)
otherAction = int(not bool(action))
customReward = False
if(otherAction == 1):
otherPosition = 1
if(self.data['Position'][t - 1] == 1):
otherCash = self.data['Cash'][t - 1]
otherHoldings = numberOfShares * self.data['Close'][t]
elif(self.data['Position'][t - 1] == 0):
numberOfShares = math.floor(self.data['Cash'][t - 1]/(self.data['Close'][t] * (1 + self.transactionCosts)))
otherCash = self.data['Cash'][t - 1] - numberOfShares * self.data['Close'][t] * (1 + self.transactionCosts)
otherHoldings = numberOfShares * self.data['Close'][t]
else:
otherCash = self.data['Cash'][t - 1] - numberOfShares * self.data['Close'][t] * (1 + self.transactionCosts)
numberOfShares = math.floor(otherCash/(self.data['Close'][t] * (1 + self.transactionCosts)))
otherCash = otherCash - numberOfShares * self.data['Close'][t] * (1 + self.transactionCosts)
otherHoldings = numberOfShares * self.data['Close'][t]
else:
otherPosition = -1
if(self.data['Position'][t - 1] == -1):
lowerBound = self.computeLowerBound(self.data['Cash'][t - 1], -numberOfShares, self.data['Close'][t-1])
if lowerBound <= 0:
otherCash = self.data['Cash'][t - 1]
otherHoldings = - numberOfShares * self.data['Close'][t]
else:
numberOfSharesToBuy = min(math.floor(lowerBound), numberOfShares)
numberOfShares -= numberOfSharesToBuy
otherCash = self.data['Cash'][t - 1] - numberOfSharesToBuy * self.data['Close'][t] * (1 + self.transactionCosts)
otherHoldings = - numberOfShares * self.data['Close'][t]
customReward = True
elif(self.data['Position'][t - 1] == 0):
numberOfShares = math.floor(self.data['Cash'][t - 1]/(self.data['Close'][t] * (1 + self.transactionCosts)))
otherCash = self.data['Cash'][t - 1] + numberOfShares * self.data['Close'][t] * (1 - self.transactionCosts)
otherHoldings = - numberOfShares * self.data['Close'][t]
else:
otherCash = self.data['Cash'][t - 1] + numberOfShares * self.data['Close'][t] * (1 - self.transactionCosts)
numberOfShares = math.floor(otherCash/(self.data['Close'][t] * (1 + self.transactionCosts)))
otherCash = otherCash + numberOfShares * self.data['Close'][t] * (1 - self.transactionCosts)
otherHoldings = - self.numberOfShares * self.data['Close'][t]
otherMoney = otherHoldings + otherCash
if not customReward:
otherReward = (otherMoney - self.data['Money'][t-1])/self.data['Money'][t-1]
else:
otherReward = (self.data['Close'][t-1] - self.data['Close'][t])/self.data['Close'][t-1]
otherState = [self.data['Close'][self.t - self.stateLength : self.t].tolist(),
self.data['Low'][self.t - self.stateLength : self.t].tolist(),
self.data['High'][self.t - self.stateLength : self.t].tolist(),
self.data['Volume'][self.t - self.stateLength : self.t].tolist(),
[otherPosition]]
self.info = {'State' : otherState, 'Reward' : otherReward, 'Done' : self.done}
# Return the trading environment feedback to the RL trading agent
return self.state, self.reward, self.done, self.info
def render(self):
"""
GOAL: Illustrate graphically the trading activity, by plotting
both the evolution of the stock market price and the
evolution of the trading capital. All the trading decisions
(long and short positions) are displayed as well.
INPUTS: /
OUTPUTS: /
"""
# Set the Matplotlib figure and subplots
fig = plt.figure(figsize=(10, 8))
ax1 = fig.add_subplot(211, ylabel='Price', xlabel='Time')
ax2 = fig.add_subplot(212, ylabel='Capital', xlabel='Time', sharex=ax1)
# Plot the first graph -> Evolution of the stock market price
self.data['Close'].plot(ax=ax1, color='blue', lw=2)
ax1.plot(self.data.loc[self.data['Action'] == 1.0].index,
self.data['Close'][self.data['Action'] == 1.0],
'^', markersize=5, color='green')
ax1.plot(self.data.loc[self.data['Action'] == -1.0].index,
self.data['Close'][self.data['Action'] == -1.0],
'v', markersize=5, color='red')
# Plot the second graph -> Evolution of the trading capital
self.data['Money'].plot(ax=ax2, color='blue', lw=2)
ax2.plot(self.data.loc[self.data['Action'] == 1.0].index,
self.data['Money'][self.data['Action'] == 1.0],
'^', markersize=5, color='green')
ax2.plot(self.data.loc[self.data['Action'] == -1.0].index,
self.data['Money'][self.data['Action'] == -1.0],
'v', markersize=5, color='red')
# Generation of the two legends and plotting
ax1.legend(["Price", "Long", "Short"])
ax2.legend(["Capital", "Long", "Short"])
plt.savefig(''.join(['Figures/', str(self.marketSymbol), '_Rendering', '.png']))
#plt.show()
def setStartingPoint(self, startingPoint):
"""
GOAL: Setting an arbitrary starting point regarding the trading activity.
This technique is used for better generalization of the RL agent.
INPUTS: - startingPoint: Optional starting point (iteration) of the trading activity.
OUTPUTS: /
"""
# Setting a custom starting point
self.t = np.clip(startingPoint, self.stateLength, len(self.data.index))
# Set the RL variables common to every OpenAI gym environments
self.state = [self.data['Close'][self.t - self.stateLength : self.t].tolist(),
self.data['Low'][self.t - self.stateLength : self.t].tolist(),
self.data['High'][self.t - self.stateLength : self.t].tolist(),
self.data['Volume'][self.t - self.stateLength : self.t].tolist(),
[self.data['Position'][self.t - 1]]]
if(self.t == self.data.shape[0]):
self.done = 1