-
Notifications
You must be signed in to change notification settings - Fork 0
/
rq_parllel_test-1.py
443 lines (347 loc) · 15.3 KB
/
rq_parllel_test-1.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
from rq import Queue
import redis
import time
import datetime
from utils import util
import dateutil.parser
import operator
import csv
import sys
sys.path.append('/home/parallels/Code/heroku-envbased/roboquant/strategies')
#print sys.path
from xiQuant_strategies import xiQuantStrategyUtil, xiquantStrategyParams
listStr = 'CUSTOM'
#listStr = 'xiQuant-100'
#listStr = 'xiQuant-50'
#tickerList = util.getTickerList(listStr)
tickerList = ['AAPL']
def run_singlestock_analysis():
# Tell RQ what Redis connection to use
redis_conn = util.get_redis_conn()
q = Queue(connection=redis_conn) # no args implies the default queue
import dateutil.parser
startdate = dateutil.parser.parse('2005-06-30T08:00:00.000Z')
enddate = dateutil.parser.parse('2014-12-31T08:00:00.000Z')
for ticker in tickerList:
orders = []
job = q.enqueue(xiQuantStrategyUtil.run_strategy_redis,20, ticker, 100000, startdate, enddate, indicators=False)
print "Currently processing job id: ", ticker
sleep = True
while(sleep):
time.sleep(1)
if job.get_status() == 'failed' or job.get_status()=='finished':
sleep = False
if job.get_status() == 'finished' and any(job.result):
orders.append(job.result)
########### Iterate master orders file.... #############
dataRows = []
for k in range(len(orders)):
for key, value in orders[k].iteritems():
row = []
row.append(key)
row.append(value[0][0])
row.append(value[0][1])
row.append(value[0][2])
row.append(value[0][3]) ##### this is for Order ID
row.append(value[0][4]) ##### this is for adjRatio
row.append(value[0][5]) #### added for rank
dataRows.append(row)
fake_csv = util.make_fake_csv(dataRows)
print "Successfully created orders fake_csv file....", ticker
reader = csv.DictReader(fake_csv, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
with open('Orders_' + xiquantStrategyParams.BB_SPREAD_LONG_OR_SHORT +"_" +ticker+'.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
for row in reader:
row["stopPrice"] = round(float(row["stopPrice"]),2)
writer.writerow(row)
print "Successfully created orders file for ticker: ", ticker
def test_parallel_strategy():
# Tell RQ what Redis connection to use
redis_conn = util.get_redis_conn()
q = Queue(connection=redis_conn, default_timeout=1500) # no args implies the default queue
import dateutil.parser
startdate = dateutil.parser.parse('2010-06-30T08:00:00.000Z')
enddate = dateutil.parser.parse('2014-12-31T08:00:00.000Z')
#startdate = dateutil.parser.parse('2012-06-30T08:00:00.000Z')
#enddate = dateutil.parser.parse('2015-08-31T08:00:00.000Z')
jobList = []
for ticker in tickerList:
#jobList.append(q.enqueue(xiQuantStrategyUtil.run_strategy_redis,20, ticker, 100000, startdate, enddate, indicators=False))
jobList.append(q.enqueue(xiQuantStrategyUtil.run_strategy_redis_debug,20, ticker, 100000, startdate, enddate))
master_orders = [] #### populate master list of orders dictionary...
jobID = 1
for job in jobList:
try:
print "Currently processing job id: ", jobID
sleep = True
while(sleep):
time.sleep(1)
if job.get_status() == 'failed' or job.get_status()=='finished':
sleep = False
if job.get_status() == 'finished' and any(job.result):
master_orders.append(job.result)
#master_orders.append(job.result.getOrdersFilteredByMomentumRank(filterCriteria=rank))
#master_orders.append(job.result.getOrdersFilteredByRules())
jobID +=1
except Exception,e:
print "Entered into exception block while processing:...", str(e)
pass ### Make sure you move on with other job...
print "successfully processed tickers"
for result in master_orders:
print result
'''
#### Wait in loop until all of them are successfull
master_orders = [] #### populate master list of orders dictionary...
jobID = 1
for job in jobList:
try:
print "Currently processing job id: ", jobID
sleep = True
while(sleep):
time.sleep(1)
if job.get_status() == 'failed' or job.get_status()=='finished':
sleep = False
if job.get_status() == 'finished' and any(job.result):
master_orders.append(job.result)
#master_orders.append(job.result.getOrdersFilteredByMomentumRank(filterCriteria=rank))
#master_orders.append(job.result.getOrdersFilteredByRules())
jobID +=1
except Exception,e:
print "Entered into exception block while processing:...", str(e)
pass ### Make sure you move on with other job...
print "successfully processed tickers"
########### Iterate master orders file.... #############
dataRows = []
for k in range(len(master_orders)):
for timeStamp, orderList in master_orders[k].iteritems():
for order in orderList:
row = []
row.append(timeStamp)
row.append(order[0])
row.append(order[1])
row.append(order[2])
row.append(order[3])
row.append(order[4])
row.append(order[5])
dataRows.append(row)
######### before passing let's sort orders based on moneyness rank
#####################################################################
#sorted_datarows = sorted(dataRows, key = lambda x: (int(x[1]), int(x[3])))
dataRows.sort(key = operator.itemgetter(0, 5))
fake_csv = util.make_fake_csv(dataRows)
print "Successfully created master_orders fake_csv file...."
reader = csv.DictReader(fake_csv, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
with open('MasterOrders_' + xiquantStrategyParams.BB_SPREAD_LONG_OR_SHORT +"_" +listStr+'.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
for row in reader:
row["stopPrice"] = round(float(row["stopPrice"]),2)
writer.writerow(row)
print "Successfully created master_orders file for processing..."
'''
def run_parallel_BBSMAXOverMTM():
# Tell RQ what Redis connection to use
redis_conn = util.get_redis_conn()
q = Queue(connection=redis_conn, default_timeout=1500) # no args implies the default queue
import dateutil.parser
startdate = dateutil.parser.parse('2005-06-30T08:00:00.000Z')
enddate = dateutil.parser.parse('2014-12-31T08:00:00.000Z')
jobList = []
for ticker in tickerList:
jobList.append(q.enqueue(xiQuantStrategyUtil.run_strategy_BBSMAXOverMTM,20, ticker, 100000, startdate, enddate, indicators=False))
#### Wait in loop until all of them are successfull
master_orders = [] #### populate master list of orders dictionary...
jobID = 1
for job in jobList:
try:
print "Currently processing job id: ", jobID
sleep = True
while(sleep):
time.sleep(1)
if job.get_status() == 'failed' or job.get_status()=='finished':
sleep = False
if job.get_status() == 'finished' and any(job.result):
master_orders.append(job.result)
#master_orders.append(job.result.getOrdersFilteredByMomentumRank(filterCriteria=rank))
#master_orders.append(job.result.getOrdersFilteredByRules())
jobID +=1
except Exception,e:
print "Entered into exception block while processing:...", str(e)
pass ### Make sure you move on with other job...
print "successfully processed tickers"
########### Iterate master orders file.... #############
dataRows = []
for k in range(len(master_orders)):
for key, value in master_orders[k].iteritems():
row = []
row.append(key)
row.append(value[0][0])
row.append(value[0][1])
row.append(value[0][2])
row.append(value[0][3]) #### this is for order id
row.append(value[0][4]) ##### this is for adj factor....
row.append(value[0][5]) #### added for rank
dataRows.append(row)
######### before passing let's sort orders based on moneyness rank
#####################################################################
#sorted_datarows = sorted(dataRows, key = lambda x: (int(x[1]), int(x[3])))
dataRows.sort(key = operator.itemgetter(0, 5))
fake_csv = util.make_fake_csv(dataRows)
print "Successfully created master_orders fake_csv file...."
reader = csv.DictReader(fake_csv, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
with open('MasterOrders_BBSMAXOverMTM_' + xiquantStrategyParams.BB_SPREAD_LONG_OR_SHORT +"_" +listStr+'.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
for row in reader:
row["stopPrice"] = round(float(row["stopPrice"]),2)
writer.writerow(row)
print "Successfully created master_orders file for processing..."
def run_parallel_EMABreachMTM():
# Tell RQ what Redis connection to use
redis_conn = util.get_redis_conn()
q = Queue(connection=redis_conn, default_timeout=1500) # no args implies the default queue # no args implies the default queue
import dateutil.parser
startdate = dateutil.parser.parse('2005-06-30T08:00:00.000Z')
enddate = dateutil.parser.parse('2014-12-31T08:00:00.000Z')
jobList = []
for ticker in tickerList:
jobList.append(q.enqueue(xiQuantStrategyUtil.run_strategy_EMABreachMTM,20, ticker, 100000, startdate, enddate, indicators=False))
#### Wait in loop until all of them are successfull
master_orders = [] #### populate master list of orders dictionary...
jobID = 1
for job in jobList:
try:
print "Currently processing job id: ", jobID
sleep = True
while(sleep):
time.sleep(1)
if job.get_status() == 'failed' or job.get_status()=='finished':
sleep = False
if job.get_status() == 'finished' and any(job.result):
master_orders.append(job.result)
#master_orders.append(job.result.getOrdersFilteredByMomentumRank(filterCriteria=rank))
#master_orders.append(job.result.getOrdersFilteredByRules())
jobID +=1
except Exception,e:
print "Entered into exception block while processing:...", str(e)
pass ### Make sure you move on with other job...
print "successfully processed tickers"
########### Iterate master orders file.... #############
dataRows = []
for k in range(len(master_orders)):
for key, value in master_orders[k].iteritems():
row = []
row.append(key)
row.append(value[0][0])
row.append(value[0][1])
row.append(value[0][2])
row.append(value[0][3]) ### this is for order id...
row.append(value[0][4]) ##### this is for adj factor....
row.append(value[0][5]) #### added for rank
dataRows.append(row)
######### before passing let's sort orders based on moneyness rank
#####################################################################
#sorted_datarows = sorted(dataRows, key = lambda x: (int(x[1]), int(x[3])))
dataRows.sort(key = operator.itemgetter(0, 5))
fake_csv = util.make_fake_csv(dataRows)
print "Successfully created master_orders fake_csv file...."
reader = csv.DictReader(fake_csv, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
with open('MasterOrders_EMABreachMTM_' + xiquantStrategyParams.BB_SPREAD_LONG_OR_SHORT +"_" +listStr+'.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
for row in reader:
row["stopPrice"] = round(float(row["stopPrice"]),2)
writer.writerow(row)
print "Successfully created master_orders file for processing..."
def run_parallel_EMATrend():
# Tell RQ what Redis connection to use
redis_conn = util.get_redis_conn()
q = Queue(connection=redis_conn, default_timeout=1500) # no args implies the default queue # no args implies the default queue
import dateutil.parser
startdate = dateutil.parser.parse('2005-06-30T08:00:00.000Z')
enddate = dateutil.parser.parse('2014-12-31T08:00:00.000Z')
jobList = []
for ticker in tickerList:
jobList.append(q.enqueue(xiQuantStrategyUtil.run_strategy_EMATrend,20, ticker, 100000, startdate, enddate, indicators=False))
#### Wait in loop until all of them are successfull
master_orders = [] #### populate master list of orders dictionary...
jobID = 1
for job in jobList:
try:
print "Currently processing job id: ", jobID
sleep = True
while(sleep):
time.sleep(1)
if job.get_status() == 'failed' or job.get_status()=='finished':
sleep = False
if job.get_status() == 'finished' and any(job.result):
master_orders.append(job.result)
#master_orders.append(job.result.getOrdersFilteredByMomentumRank(filterCriteria=rank))
#master_orders.append(job.result.getOrdersFilteredByRules())
jobID +=1
except Exception,e:
print "Entered into exception block while processing:...", str(e)
pass ### Make sure you move on with other job...
print "successfully processed tickers"
########### Iterate master orders file.... #############
dataRows = []
for k in range(len(master_orders)):
for key, value in master_orders[k].iteritems():
row = []
row.append(key)
row.append(value[0][0])
row.append(value[0][1])
row.append(value[0][2])
row.append(value[0][3]) ### this is for order id...
row.append(value[0][4]) ##### this is for adj factor....
row.append(value[0][5]) #### added for rank
dataRows.append(row)
######### before passing let's sort orders based on moneyness rank
#####################################################################
#sorted_datarows = sorted(dataRows, key = lambda x: (int(x[1]), int(x[3])))
dataRows.sort(key = operator.itemgetter(0, 5))
fake_csv = util.make_fake_csv(dataRows)
print "Successfully created master_orders fake_csv file...."
reader = csv.DictReader(fake_csv, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
with open('MasterOrders_EMATrend_' + xiquantStrategyParams.BB_SPREAD_LONG_OR_SHORT +"_" +listStr+'.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=["timeSinceEpoch", "symbol", "action", "stopPrice", "orderID", "adjRatio", "rank"])
for row in reader:
row["stopPrice"] = round(float(row["stopPrice"]),2)
writer.writerow(row)
print "Successfully created master_orders file for processing..."
def process_Options_History():
redis_conn = util.get_redis_conn()
q = Queue(connection=redis_conn) # no args implies the default queue
dt = dateutil.parser.parse('2013-11-01T08:00:00.000Z')
jobList = []
jobID = []
print "Initializing options filter processing"
while dt <= dateutil.parser.parse('2013-11-30T08:00:00.000Z'):
#try:
dtStr = dt.strftime('%Y%m%d')
currentDir = util.getCurrentDir()
inputfilepath = currentDir + '/options/'
inputfile = inputfilepath + 'L3_options_'+ dtStr +'.csv'
outputfilepath = currentDir + '/filteredoptions/'
outputfile = outputfilepath +'filteredOptions_'+ dtStr + '.csv'
jobList.append(q.enqueue(xiQuantStrategyUtil.processOptionsFile, inputfile, outputfile))
jobID.append(inputfile)
print "Added to queue JOB ID: ", inputfile
#xiQuantStrategyUtil.processOptionsFile(inputfile, outputfile)
if dt.date().weekday() == 4 :
dt = dt + datetime.timedelta(days=3)
else:
dt = dt + datetime.timedelta(days=1)
#except :
#pass #### Files are missing due to holidays...
#### Wait in loop until all of them are successfull
i = 0
for job in jobList:
print "Currently processing file: ", jobID[i]
while (job.result is None):
time.sleep(1)
i +=1
print "Successfully processed...."
test_parallel_strategy()
#run_parallel_BBSMAXOverMTM()
#run_parallel_EMABreachMTM()
#run_parallel_EMATrend()
#run_singlestock_analysis()
#process_Options_History()