-
Notifications
You must be signed in to change notification settings - Fork 6
/
problem1_trading_params.py
517 lines (436 loc) · 24.8 KB
/
problem1_trading_params.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
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
from backtester.trading_system_parameters import TradingSystemParameters
from backtester.features.feature import Feature
from datetime import timedelta
from problem1_data_source import Problem1DataSource
from problem1_execution_system import Problem1ExecutionSystem
from backtester.timeRule.custom_time_rule import CustomTimeRule
from backtester.orderPlacer.backtesting_order_placer import BacktestingOrderPlacer
from backtester.trading_system import TradingSystem
from backtester.version import updateCheck
from backtester.constants import *
from backtester.features.feature import Feature
from backtester.logger import *
import pandas as pd
import numpy as np
import sys
from sklearn import linear_model
from sklearn import metrics as sm
## Make your changes to the functions below.
## SPECIFY the symbols you are modeling for in getSymbolsToTrade() below
## You need to specify features you want to use in getInstrumentFeatureConfigDicts() and getMarketFeatureConfigDicts()
## and create your predictions using these features in getPrediction()
## Don't change any other function
## The toolbox does the rest for you, from downloading and loading data to running backtest
class MyTradingParams(TradingSystemParameters):
'''
initialize class
place any global variables here
'''
def __init__(self, tradingFunctions):
self.__tradingFunctions = tradingFunctions
self.__dataSetId = self.__tradingFunctions.dataSetId
self.__instrumentIds = self.__tradingFunctions.instrumentIds
self.__targetVariable = self.__tradingFunctions.getTargetVariableKey()
self.__priceKey = self.__tradingFunctions.getTargetVariableKey()
self.__additionalInstrumentFeatureConfigDicts = []
self.__additionalMarketFeatureConfigDicts = []
self.__fees = {'brokerage': 0.00,'spread': 0.00}
self.__startDate = self.__tradingFunctions.startDate
self.__endDate = self.__tradingFunctions.endDate
super(MyTradingParams, self).__init__()
'''
Returns an instance of class DataParser. Source of data for instruments
'''
def getDataParser(self):
# instrumentIds = ['trainingData']
ds = self.__tradingFunctions.setDataParser()
ds.loadLiveUpdates()
return ds
# return Problem2DataSource(cachedFolderName='historicalData/',
# dataSetId=self.__dataSetId,
# instrumentIds=instrumentIds,
# downloadUrl = 'https://s3.us-east-2.amazonaws.com/qq10-data',
# targetVariableList=self.__targetVariableList,
# targetVariable = self.__tradingFunctions.getTargetVariableKey(),
# timeKey = 'time',
# timeStringFormat = '%Y-%m-%d',
# startDateStr=self.__startDate,
# endDateStr=self.__endDate,
# liveUpdates=True,
# pad=True)
'''
Returns an instance of class TimeRule, which describes the times at which
we should update all the features and try to execute any trades based on
execution logic.
For eg, for intra day data, you might have a system, where you get data
from exchange at a very fast rate (ie multiple times every second). However,
you might want to run your logic of computing features or running your execution
system, only at some fixed intervals (like once every 5 seconds). This depends on your
strategy whether its a high, medium, low frequency trading strategy. Also, performance
is another concern. if your execution system and features computation are taking
a lot of time, you realistically wont be able to keep upto pace.
'''
def getTimeRuleForUpdates(self):
return CustomTimeRule(startDate=self.__startDate, endDate=self.__endDate, frequency='S', sample='10', startTime='00:00', endTime='17:00')
'''
Returns a timedetla object to indicate frequency of updates to features
Any updates within this frequncy to instruments do not trigger feature updates.
Consequently any trading decisions that need to take place happen with the same
frequency
'''
def getFrequencyOfFeatureUpdates(self):
return timedelta(60, 0) # minutes, seconds
def getStartingCapital(self):
return 100*len(self.__instrumentIds)
'''
This is a way to use any custom features you might have made.
Returns a dictionary where
key: featureId to access this feature (Make sure this doesnt conflict with any of the pre defined feature Ids)
value: Your custom Class which computes this feature. The class should be an instance of Feature
Eg. if your custom class is MyCustomFeature, and you want to access this via featureId='my_custom_feature',
you will import that class, and return this function as {'my_custom_feature': MyCustomFeature}
'''
def getCustomFeatures(self):
customFeatures = {'prediction': TrainingPredictionFeature,
'fees_and_spread': FeesCalculator,
'ScoreCalculator' : ScoreCalculator,
'Pnl' : PnLCalculator,
'AccuracyCalculator' : AccuracyCalculator,
'TPCalculator' : TPCalculator,
'TNCalculator' : TNCalculator,
'FPCalculator' : FPCalculator,
'FNCalculator' : FNCalculator,
'PrecisionCalculator' : PrecisionCalculator,
'RecallCalculator' : RecallCalculator,
'F1Calculator' : F1Calculator}
customFeatures.update(self.__tradingFunctions.getCustomFeatures())
return customFeatures
def getInstrumentFeatureConfigDicts(self):
# ADD RELEVANT FEATURES HERE
predictionDict = {'featureKey': 'prediction',
'featureId': 'prediction',
'params': {'function': self.__tradingFunctions}}
feesConfigDict = {'featureKey': 'fees',
'featureId': 'fees_and_spread',
'params': {'feeDict': self.__fees,
'price': self.__priceKey,
'position' : 'position'}}
# profitlossConfigDict = {'featureKey': 'pnl',
# 'featureId': 'PnL',
# 'params': {'price': self.__priceKey,
# 'position' : 'position',
# 'fees': 'fees'}}
capitalConfigDict = {'featureKey': 'capital',
'featureId': 'capital',
'params': {'price': self.__priceKey,
'fees': 'fees',
'capitalReqPercent': 0.95}}
scoreDict = {'featureKey': 'score',
'featureId': 'ScoreCalculator',
'params': {'predictionKey': 'prediction',
'targetVariable' : self.__tradingFunctions.getTargetVariableKey()}}
accuracyDict = {'featureKey': 'accuracy',
'featureId': 'AccuracyCalculator',
'params': {'predictionKey': 'prediction',
'targetVariable' : self.__tradingFunctions.getTargetVariableKey(),
'threshold':self.__tradingFunctions.threshold}}
tpDict = {'featureKey': 'truePositive',
'featureId': 'TPCalculator',
'params': {'predictionKey': 'prediction',
'targetVariable' : self.__tradingFunctions.getTargetVariableKey(),
'threshold':self.__tradingFunctions.threshold}}
tnDict = {'featureKey': 'trueNegative',
'featureId': 'TNCalculator',
'params': {'predictionKey': 'prediction',
'targetVariable' : self.__tradingFunctions.getTargetVariableKey(),
'threshold':self.__tradingFunctions.threshold}}
fpDict = {'featureKey': 'falsePositive',
'featureId': 'FPCalculator',
'params': {'predictionKey': 'prediction',
'targetVariable' : self.__tradingFunctions.getTargetVariableKey(),
'threshold':self.__tradingFunctions.threshold}}
fnDict = {'featureKey': 'falseNegative',
'featureId': 'FNCalculator',
'params': {'predictionKey': 'prediction',
'targetVariable' : self.__tradingFunctions.getTargetVariableKey(),
'threshold':self.__tradingFunctions.threshold}}
precisionDict = {'featureKey': 'precision',
'featureId': 'PrecisionCalculator',
'params': {'predictionKey': 'prediction',
'truePositive':'truePositive',
'falsePositive':'falsePositive',
'targetVariable' : self.__tradingFunctions.getTargetVariableKey()}}
recallDict = {'featureKey': 'recall',
'featureId': 'RecallCalculator',
'params': {'predictionKey': 'prediction',
'truePositive':'truePositive',
'falseNegative':'falseNegative',
'targetVariable' : self.__tradingFunctions.getTargetVariableKey()}}
f1Dict = {'featureKey': 'f1',
'featureId': 'F1Calculator',
'params': {'predictionKey': 'prediction',
'precision':'precision',
'recall':'recall',
'targetVariable' : self.__tradingFunctions.getTargetVariableKey()}}
stockFeatureConfigs = self.__tradingFunctions.getInstrumentFeatureConfigDicts()
return {INSTRUMENT_TYPE_STOCK: stockFeatureConfigs + [predictionDict,
feesConfigDict,capitalConfigDict,scoreDict,
accuracyDict, tpDict, tnDict, fpDict, fnDict, precisionDict, recallDict, f1Dict]
+ self.__additionalInstrumentFeatureConfigDicts}
'''
Returns an array of market feature config dictionaries
market feature config Dictionary has the following keys:
featureId: a string representing the type of feature you want to use
featureKey: a string representing the key you will use to access the value of this feature.this
params: A dictionary with which contains other optional params if needed by the feature
'''
def getMarketFeatureConfigDicts(self):
# ADD RELEVANT FEATURES HERE
scoreDict = {'featureKey': 'score',
'featureId': 'score_ll',
'params': {'featureName': self.getPriceFeatureKey(),
'instrument_score_feature': 'score'}}
marketFeatureConfigs = self.__tradingFunctions.getMarketFeatureConfigDicts()
return marketFeatureConfigs + [scoreDict] +self.__additionalMarketFeatureConfigDicts
'''
Returns the type of execution system we want to use. Its an implementation of the class ExecutionSystem
It converts prediction to intended positions for different instruments.
'''
def getExecutionSystem(self):
return Problem1ExecutionSystem(enter_threshold=0.7,
exit_threshold=0.55,
longLimit=1,
shortLimit=1,
capitalUsageLimit=0.10 * self.getStartingCapital(),
enterlotSize=1, exitlotSize = 1,
limitType='L', price=self.__priceKey)
'''
Returns the type of order placer we want to use. its an implementation of the class OrderPlacer.
It helps place an order, and also read confirmations of orders being placed.
For Backtesting, you can just use the BacktestingOrderPlacer, which places the order which you want, and automatically confirms it too.
'''
def getOrderPlacer(self):
return BacktestingOrderPlacer()
'''
Returns the amount of lookback data you want for your calculations. The historical market features and instrument features are only
stored upto this amount.
This number is the number of times we have updated our features.
'''
def getLookbackSize(self):
return max(150, self.__tradingFunctions.getLookbackSize())
def getPriceFeatureKey(self):
return self.__priceKey
def setPriceFeatureKey(self, priceKey='Adj_Close'):
self.__priceKey = priceKey
def getDataSetId(self):
return self.__dataSetId
def setDataSetId(self, dataSetId):
self.__dataSetId = dataSetId
def getInstrumentsIds(self):
return self.__instrumentIds
def setInstrumentsIds(self, instrumentIds):
self.__instrumentIds = instrumentIds
def getDates(self):
return {'startDate':self.__startDate,
'endDate':self.__endDate}
def setDates(self, dateDict):
self.__startDate = dateDict['startDate']
self.__endDate = dateDict['endDate']
def getTargetVariableKey(self):
return self.__targetVariable
def setFees(self, feeDict={'brokerage': 0.00,'spread': 0.00}):
self.__fees = feeDict
def setAdditionalInstrumentFeatureConfigDicts(self, dicts = []):
self.__additionalInstrumentFeatureConfigDicts = dicts
def setAdditionalMarketFeatureConfigDicts(self, dicts = []):
self.__additionalMarketFeatureConfigDicts = dicts
class TrainingPredictionFeature(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
tf = featureParams['function']
val = 0.5
predictions = pd.Series(val, index = instrumentManager.getAllInstrumentsByInstrumentId())
predictions = tf.getPrediction(time, updateNum, instrumentManager, predictions)
return predictions
class FeesCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
return 0
# class BuyHoldPnL(Feature):
# @classmethod
# def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
# instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
# priceData = instrumentLookbackData.getFeatureDf(featureParams['price'])
# pnlData = instrumentLookbackData.getFeatureDf(featureKey)
# if len(priceData)>1:
# currentPrice = priceData.iloc[-1]
# previousPnl = pnlData.iloc[-1]
# else:
# currentPrice = 0
# previousPnl = 0
# bhpnl = pd.Series(0,index = instrumentManager.getAllInstrumentsByInstrumentId())
# if len(priceData)>1:
# # bhpnl += (100*(1+previousPnl)*(1+currentPrice) - 100)/100
# bhpnl += (100+previousPnl)*(1+currentPrice) - 100
# print('Buy Hold Pnl: %.3f'%bhpnl.iloc[0])
# # printdf = pd.DataFrame(index=instrumentManager.getAllInstrumentsByInstrumentId())
# # printdf['previousPnl'] = previousPnl
# # printdf['currentPrice'] = currentPrice
# # printdf['bhpnl'] = bhpnl
# # print(printdf)
# return bhpnl
class PnLCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
priceData = instrumentLookbackData.getFeatureDf(featureParams['price'])
positionData = instrumentLookbackData.getFeatureDf(featureParams['position'])
pnlData = instrumentLookbackData.getFeatureDf(featureKey)
currentPosition = positionData.iloc[-1]
previousPosition = 0 if updateNum < 2 else positionData.iloc[-2]
previousPnl = 0 if updateNum < 2 else pnlData.iloc[-1]
changeInPosition = currentPosition - previousPosition
feesData = instrumentLookbackData.getFeatureDf(featureParams['fees'])
if len(priceData)>2:
currentPrice = priceData.iloc[-1]
previousPrice = priceData.iloc[-2]
else:
currentPrice = 0
previousPrice = 0
zeroSeries = currentPrice * 0
cumulativePnl = zeroSeries
fees = feesData.iloc[-1]
tradePrice = pd.Series([instrumentManager.getInstrument(x).getLastTradePrice() for x in priceData.columns], index=priceData.columns)
tradeLoss = pd.Series([instrumentManager.getInstrument(x).getLastTradeLoss() for x in priceData.columns], index=priceData.columns)
# cumulativePnl += (100*(1+previousPnl)*(1+currentPosition*currentPrice) - 100)/100
cumulativePnl += (100+previousPnl)*(1+currentPosition*currentPrice) - (100)
return cumulativePnl
class ScoreCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
ids = list(instrumentManager.getAllInstrumentsByInstrumentId())
if updateNum <2 :
return pd.Series(0, index=ids)
predictionData = instrumentLookbackData.getFeatureDf(featureParams['predictionKey']).iloc[-1]
trueValue = instrumentLookbackData.getFeatureDf(featureParams['targetVariable']).iloc[-1]
previousValue = instrumentLookbackData.getFeatureDf(featureKey).iloc[-1]
currentScore = pd.Series(0.5, index=previousValue.index)
yp = 1-predictionData.values[0]
yp = 0.001 if yp<0.001 else yp
yp = 0.999 if yp>0.999 else yp
currentScore[predictionData!=0.5] = -(trueValue.values[0]*np.log(yp) + (1 - trueValue.values[0])*np.log(1 - yp))
score = (previousValue*(updateNum-1)+currentScore)/updateNum#sm.accuracy_score(predictionData, trueValue)
print('True Value: %i'%trueValue.values[0])
print('LogLoss: %.2f'%score.values[0])
return score
class AccuracyCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
ids = list(instrumentManager.getAllInstrumentsByInstrumentId())
if updateNum <2 :
return pd.Series(0, index=ids)
predictionData = instrumentLookbackData.getFeatureDf(featureParams['predictionKey']).iloc[-1]
trueValue = instrumentLookbackData.getFeatureDf(featureParams['targetVariable']).iloc[-1]
predictedValue = 0 if ((1-predictionData.values[0])<featureParams['threshold']) else 1
previousValue = instrumentLookbackData.getFeatureDf(featureKey).iloc[-1]
currentScore = pd.Series(0, index=previousValue.index)
currentScore[predictionData!=0.5] = currentScore +(1 - np.abs(predictedValue - trueValue))
score = (previousValue*(updateNum-1)+currentScore)/updateNum#sm.accuracy_score(predictionData, trueValue)
print('Accuracy: %.2f'%score.values[0])
return score
class TPCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
ids = list(instrumentManager.getAllInstrumentsByInstrumentId())
if updateNum <2 :
return pd.Series(0, index=ids)
predictionData = instrumentLookbackData.getFeatureDf(featureParams['predictionKey']).iloc[-1]
trueValue = instrumentLookbackData.getFeatureDf(featureParams['targetVariable']).iloc[-1]
previousValue = instrumentLookbackData.getFeatureDf(featureKey).iloc[-1]
currentScore = 1 if ((trueValue==1) & (predictionData<=featureParams['threshold'])).bool() else 0
score = (previousValue+currentScore)
print('Correct 1s (True Positive): %i'%score.values[0])
return score
class TNCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
ids = list(instrumentManager.getAllInstrumentsByInstrumentId())
if updateNum <2 :
return pd.Series(0, index=ids)
predictionData = instrumentLookbackData.getFeatureDf(featureParams['predictionKey']).iloc[-1]
trueValue = instrumentLookbackData.getFeatureDf(featureParams['targetVariable']).iloc[-1]
previousValue = instrumentLookbackData.getFeatureDf(featureKey).iloc[-1]
currentScore = 1 if ((trueValue==0) & (predictionData>featureParams['threshold'])).bool() else 0
score = (previousValue+currentScore)
print('Correct 0s(True Negative): %i'%score.values[0])
return score
class FPCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
ids = list(instrumentManager.getAllInstrumentsByInstrumentId())
if updateNum <2 :
return pd.Series(updateNum, index=ids)
predictionData = instrumentLookbackData.getFeatureDf(featureParams['predictionKey']).iloc[-1]
trueValue = instrumentLookbackData.getFeatureDf(featureParams['targetVariable']).iloc[-1]
previousValue = instrumentLookbackData.getFeatureDf(featureKey).iloc[-1]
currentScore = 1 if ((trueValue==0) & (predictionData<=featureParams['threshold'])).bool() else 0
score = (previousValue+currentScore)
print('Incorrect 1s(False Positive): %i'%score.values[0])
return score
class FNCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
ids = list(instrumentManager.getAllInstrumentsByInstrumentId())
if updateNum <2 :
return pd.Series(0, index=ids)
predictionData = instrumentLookbackData.getFeatureDf(featureParams['predictionKey']).iloc[-1]
trueValue = instrumentLookbackData.getFeatureDf(featureParams['targetVariable']).iloc[-1]
previousValue = instrumentLookbackData.getFeatureDf(featureKey).iloc[-1]
currentScore = 1 if ((trueValue==1) & (predictionData>featureParams['threshold'])).bool() else 0
score = (previousValue+currentScore)
print('Incorrect 0s(False Negative): %i'%score.values[0])
return score
class PrecisionCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
ids = list(instrumentManager.getAllInstrumentsByInstrumentId())
if updateNum <2 :
return pd.Series(0, index=ids)
# import pdb;pdb.set_trace()
tp = instrumentLookbackData.getFeatureDf(featureParams['truePositive']).iloc[-1]
fp = instrumentLookbackData.getFeatureDf(featureParams['falsePositive']).iloc[-1]
score = tp / (tp + fp)#sm.accuracy_score(predictionData, trueValue)
print('precision: %.2f'%score.values[0])
return score
class RecallCalculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
ids = list(instrumentManager.getAllInstrumentsByInstrumentId())
if updateNum <2 :
return pd.Series(0, index=ids)
tp = instrumentLookbackData.getFeatureDf(featureParams['truePositive']).iloc[-1]
fn = instrumentLookbackData.getFeatureDf(featureParams['falseNegative']).iloc[-1]
score = tp / (tp + fn)#sm.accuracy_score(predictionData, trueValue)
print('recall: %.2f'%score.values[0])
return score
class F1Calculator(Feature):
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatures()
ids = list(instrumentManager.getAllInstrumentsByInstrumentId())
if updateNum <2 :
return pd.Series(0, index=ids)
precision = instrumentLookbackData.getFeatureDf(featureParams['precision']).iloc[-1]
recall = instrumentLookbackData.getFeatureDf(featureParams['recall']).iloc[-1]
score = 2 * (precision * recall) / (precision + recall)
print('F1: %.2f'%score.values[0])
return score