forked from jasonswearingen/QuantShim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquantShim.py
1658 lines (1333 loc) · 70.6 KB
/
quantShim.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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
TL;DR:
1) jump to the end of this file
2) replace/extend "ExampleFramework" (around line 1601)
3) copy/paste this file to quantopian
4) backtest
-------------
@summary: An intraday algorithmic trading framework for use with quantopian.com
Primary use is to support multiple algorithms cooperating
@license: gpl v3
@author: JasonS@Novaleaf.com https://PhantomJsCloud.com
@disclaimer: I'm not a fan of python so sorry that this isn't PEP compliant.
"""
# Import the libraries we will use here
import datetime
import pytz
import math
import numpy
import pandas
import scipy
import scipy.stats
import zipline
import functools
import collections
import sklearn
import sklearn.naive_bayes
#import sklearn.naive_bayes.BernoulliNB
import sklearn.linear_model
import sklearn.ensemble
import talib
is_offline_Zipline = False
#quantopian shims
class WorstSpreadSlippage(slippage.SlippageModel):
'''will trade at the worst value of the order minute. high if long, low if short.
additionally, supports 'VolumeShareSlippage' functionality, which further biases price/volume'''
def __init__(this, volume_limit=.25, price_impact=0.1, ohlcWeighted=False):
this.volume_limit = volume_limit
this.price_impact = price_impact
this.ohlcWeighted = ohlcWeighted
pass
def __processVolumeShareSlippage(self,event,order, targetPrice):
'''coppied implementation from VolumeShareSlippage.process_order(), found here: https://github.com/quantopian/zipline/blob/4860a966b3a3102fa80d43f393155e53015cc349/zipline/finance/slippage.py
modification: we return the final (price,volume) tuple for our main .process_order() to use, instead of executing the order
RETURNS: final (price,volume) tuple'''
########
max_volume = self.volume_limit * event.volume
# price impact accounts for the total volume of transactions
# created against the current minute bar
remaining_volume = max_volume - self.volume_for_bar
if remaining_volume < 1:
# we can't fill any more transactions
return (0.0,0)
# the current order amount will be the min of the
# volume available in the bar or the open amount.
cur_volume = int(min(remaining_volume, abs(order.open_amount)))
if cur_volume < 1:
return (0.0,0)
# tally the current amount into our total amount ordered.
# total amount will be used to calculate price impact
total_volume = self.volume_for_bar + cur_volume
volume_share = min(total_volume / event.volume,
self.volume_limit)
simulated_impact = volume_share ** 2 \
* math.copysign(self.price_impact, order.direction) \
* targetPrice
#return create_transaction(
# event,
# order,
# # In the future, we may want to change the next line
# # for limit pricing
# event.price + simulated_impact,
# math.copysign(cur_volume, order.direction)
return (targetPrice + simulated_impact,int(math.copysign(cur_volume, order.direction)))
def process_order(this,trade_bar,order):
#worst spread
if order.amount < 0:
targetPrice = trade_bar.low
else:
targetPrice = trade_bar.high
#trade at the open
#targetPrice = trade_bar.open_price
if this.ohlcWeighted:
#midpoint, ohlc weighted
targetPrice = (targetPrice + trade_bar.open_price + trade_bar.high + trade_bar.low + trade_bar.close_price) / 5
pass
price, volume = this.__processVolumeShareSlippage(trade_bar,order,targetPrice)
priceSlippage = trade_bar.close_price - price
volumeSlippage = order.amount - volume
if price == 0.0 or volume == 0:
return
#logger.info(price)
logger.info("ORDER_COMMITTED: {0} shares {1} @ {2} \n\t v={8} o={4} h={5} l={6} c={7} \t (WorstSpreadSlippage: vol= -{9} price= {3:.2f})"
.format(volume,trade_bar.sid.symbol,price,priceSlippage, trade_bar.open_price, trade_bar.high, trade_bar.low, trade_bar.close_price, trade_bar.volume,volumeSlippage))
return slippage.create_transaction(trade_bar,
order,
price,
order.amount)
class TradeAtTheOpenSlippageModel_Simple(slippage.SlippageModel):
def __init__(self, fractionOfOpenCloseRange):
self.fractionOfOpenCloseRange = fractionOfOpenCloseRange
def process_order(self, trade_bar, order):
openPrice = trade_bar.open_price
closePrice = trade_bar.price
ocRange = closePrice - openPrice
ocRange = ocRange * self.fractionOfOpenCloseRange
targetExecutionPrice = openPrice + ocRange
# Create the transaction using the new price we've calculated.
return slippage.create_transaction(
trade_bar,
order,
targetExecutionPrice,
order.amount
)
class TradeAtTheOpenSlippage(slippage.SlippageModel):
'''will trade at the open, good for daily use, kind of not good otherwise.'''
def __init__(this, volume_limit=.25, price_impact=0.1):
this.volume_limit = volume_limit
this.price_impact = price_impact
pass
def __processVolumeShareSlippage(self,event,order, targetPrice):
'''coppied implementation from VolumeShareSlippage.process_order(), found here: https://github.com/quantopian/zipline/blob/4860a966b3a3102fa80d43f393155e53015cc349/zipline/finance/slippage.py
modification: we return the final (price,volume) tuple for our main .process_order() to use, instead of executing the order
RETURNS: final (price,volume) tuple'''
########
max_volume = self.volume_limit * event.volume
# price impact accounts for the total volume of transactions
# created against the current minute bar
remaining_volume = max_volume - self.volume_for_bar
if remaining_volume < 1:
# we can't fill any more transactions
return (0.0,0)
# the current order amount will be the min of the
# volume available in the bar or the open amount.
cur_volume = int(min(remaining_volume, abs(order.open_amount)))
if cur_volume < 1:
return (0.0,0)
# tally the current amount into our total amount ordered.
# total amount will be used to calculate price impact
total_volume = self.volume_for_bar + cur_volume
volume_share = min(total_volume / event.volume,
self.volume_limit)
simulated_impact = volume_share ** 2 \
* math.copysign(self.price_impact, order.direction) \
* targetPrice
#return create_transaction(
# event,
# order,
# # In the future, we may want to change the next line
# # for limit pricing
# event.price + simulated_impact,
# math.copysign(cur_volume, order.direction)
return (targetPrice + simulated_impact,int(math.copysign(cur_volume, order.direction)))
def process_order(this,trade_bar,order):
#if order.amount < 0:
# targetPrice = trade_bar.low
#else:
# targetPrice = trade_bar.high
targetPrice = trade_bar.open_price
price, volume = this.__processVolumeShareSlippage(trade_bar,order,targetPrice)
priceSlippage = trade_bar.close_price - price
volumeSlippage = order.amount - volume
if price == 0.0 or volume == 0:
return
#logger.info(price)
logger.info("ORDER_COMMITTED: {0} shares {1} @ {2} \n\t v={8} o={4} h={5} l={6} c={7} \t (TradeAtTheOpenSlippage: vol= -{9} price= {3:.2f})"
.format(volume,trade_bar.sid.symbol,price,priceSlippage, trade_bar.open_price, trade_bar.high, trade_bar.low, trade_bar.close_price, trade_bar.volume,volumeSlippage))
return slippage.create_transaction(trade_bar,
order,
price,
order.amount)
class CustomSlippage(slippage.SlippageModel):
''' allows customizing slippage if desired, though mostly used for logging your order details to the console'''
def __init__(this, volume_limit=.25, price_impact=0.1, ohlcWeighted=False):
this.volume_limit = volume_limit
this.price_impact = price_impact
this.ohlcWeighted = ohlcWeighted
pass
def __processVolumeShareSlippage(self,event,order, targetPrice):
'''coppied implementation from VolumeShareSlippage.process_order(), found here: https://github.com/quantopian/zipline/blob/4860a966b3a3102fa80d43f393155e53015cc349/zipline/finance/slippage.py
modification: we return the final (price,volume) tuple for our main .process_order() to use, instead of executing the order
RETURNS: final (price,volume) tuple'''
########
max_volume = self.volume_limit * event.volume
# price impact accounts for the total volume of transactions
# created against the current minute bar
remaining_volume = max_volume - self.volume_for_bar
if remaining_volume < 1:
# we can't fill any more transactions
return (0.0,0)
# the current order amount will be the min of the
# volume available in the bar or the open amount.
cur_volume = int(min(remaining_volume, abs(order.open_amount)))
if cur_volume < 1:
return (0.0,0)
# tally the current amount into our total amount ordered.
# total amount will be used to calculate price impact
total_volume = self.volume_for_bar + cur_volume
volume_share = min(total_volume / event.volume,
self.volume_limit)
simulated_impact = volume_share ** 2 * math.copysign(self.price_impact, order.direction) * targetPrice
#return create_transaction(
# event,
# order,
# # In the future, we may want to change the next line
# # for limit pricing
# event.price + simulated_impact,
# math.copysign(cur_volume, order.direction)
return (targetPrice + simulated_impact,int(math.copysign(cur_volume, order.direction)))
def process_order(this,trade_bar,order):
####worst spread
#if order.amount < 0:
# targetPrice = trade_bar.low
#else:
# targetPrice = trade_bar.high
####trade at the open
#targetPrice = trade_bar.open_price
####trade at the close
targetPrice = trade_bar.close_price
if this.ohlcWeighted:
#midpoint, ohlc weighted
targetPrice = (targetPrice + trade_bar.open_price + trade_bar.high + trade_bar.low + trade_bar.close_price) / 5
pass
price, volume = this.__processVolumeShareSlippage(trade_bar,order,targetPrice)
priceSlippage = trade_bar.close_price - price
volumeSlippage = order.amount - volume
if price == 0.0 or volume == 0:
return
#construct our pnl once this transaction is comitted (logged below)
pnl = _g.context.portfolio.pnl + (price * order.amount) - (trade_bar.close_price * order.amount)
#logger.info(price)
logger.info("ORDER_COMMITTED: {0} shares {1} @ {2} \n\t v={8} o={4} h={5} l={6} c={7} \t (Slippage: vol= -{9} price= {3:.2f})\n\tpnl={10}"
.format(volume,trade_bar.sid.symbol,price,priceSlippage, trade_bar.open_price, trade_bar.high, trade_bar.low, trade_bar.close_price, trade_bar.volume,volumeSlippage, pnl))
return slippage.create_transaction(trade_bar,
order,
price,
order.amount)
class Logger():
'''shim for exposing the same logging definitions to visualstudio intelisence'''
def __init__(this, logErrors=True, logInfos=True, logWarns=True, logDebugs=True):
this.__logErrors = logErrors
this.__logInfos = logInfos
this.__logWarns = logWarns
this.__logDebugs = logDebugs
this.__recordHistory = {}
this.__lastKnownDay = None
pass
def error(this, message):
if not this.__logErrors: return
log.error(this.__wrapMessage(message))
pass
def info(this, message):
if not this.__logInfos: return
log.info(this.__wrapMessage(message))
pass
def warn(this, message):
if not this.__logWarns: return
log.warn(this.__wrapMessage(message))
pass
def debug(this, message):
if not this.__logDebugs: return
log.debug(this.__wrapMessage(message))
pass
def __wrapMessage(this,message):
this.__trySpamDailyLogs()
timestamp = _g.context.framework._getDatetime()
#return str(timestamp) + message
time = timestamp.strftime("%H:%M")
#if timestamp.second!=0:
# time += ":{0}".format(timestamp.second)
return str(time) + ": " + str(message)
pass
def debugAccumulateDaily(this,key,message):
'''writes the log once a day to avoid spam. includes timestamp automatically'''
if not this.__logDebugs: return
msg = this.__wrapMessage(message)
this.__storeToDailyLog(key,msg)
def debugOnceDaily(this,key,message):
if not this.__logDebugs: return
this.__storeToDailyLog(key,message)
this.__recordHistory[key] = this.__recordHistory[key][0:1]
this.__trySpamDailyLogs()
pass
def __storeToDailyLog(this,key,message):
if not this.__recordHistory.has_key(key):
this.__recordHistory[key] = []
this.__recordHistory[key].append(message)
pass
def __trySpamDailyLogs(this):
if _g.context.framework.thisFrameDay != this.__lastKnownDay:
#new day, dump our previous logs
this.__lastKnownDay = _g.context.framework.thisFrameDay
for key,values in this.__recordHistory.items():
this.debug("YD_RECORD@{0}=\n{1}".format(key,",".join(values)))
values[:] = [] #clear it
pass
def record(this, name,value, logDaily=False):
this.__trySpamDailyLogs()
if(logDaily == True):
this.__storeToDailyLog(name,"%0.4f" % value)
record(**{name:value})
def recordNormalized(this, name,value,baseline=1,subtract=0, logDaily=False):
'''normalize values to a 0 to 1 range'''
if value - subtract == 0 or baseline == 0:
toRecord = 0
else:
toRecord = (value - subtract) / baseline
this.record(name,toRecord,logDaily=logDaily)
#def getLastRecord(this,name):
# '''returns the last recorded value. only exists if doing daily
# outputs, and during the day. returns None if name not found'''
# return this.__recordHistory.get(name)
pass
global logger
logger = Logger() #(logDebugs=False)
class Shims():
'''SHIM OF QUANTOPIAN INTERNAL REPRESENTATION. here for intelisence only. you SHOULD NOT actually instantiate these.'''
class Position:
'''
The position object represents a current open position, and is contained inside the positions dictionary.
For example, if you had an open AAPL position, you'd access it using context.portfolio.positions[sid(24)].
The position object has the following properties:
amount = 0 #Integer: Whole number of shares in this position.
cost_basis = 0.0 #Float: The volume-weighted average price paid per share in this position.
last_sale_price = 0.0 #Float: Price at last sale of this security.
sid = 0 #Integer: The ID of the security.
'''
def __init__(this):
this.amount = 0 #Integer: Whole number of shares in this position.
this.cost_basis = 0.0 #Float: The volume-weighted average price paid per share in this position.
this.last_sale_price = 0.0 #Float: Price at last sale of this security.
this.sid = 0 #Integer: The ID of the security.
class Context():
def __init__(this , portfolio=zipline.protocol.Portfolio()): #, tradingAlgorithm = zipline.TradingAlgorithm()):
this.portfolio = portfolio
#this.tradingAlgorithm = tradingAlgorithm
pass
pass
class _TradingAlgorithm_QuantopianShim:
'''shim of zipline.TradingAlgorithm for use on quantopian '''
def __init__(this):
#this.logger = Shims._Logger()
#this.logger = log
pass
def order(this,sid,amount,limit_price=None, stop_price=None):
'''
Places an order for the specified security of the specified number of shares. Order type is inferred from the parameters used. If only sid and amount are used as parameters, the order is placed as a market order.
Parameters
sid: A security object.
amount: The integer amount of shares. Positive means buy, negative means sell.
limit_price: (optional) The price at which the limit order becomes active. If used with stop_price, the price where the limit order becomes active after stop_price is reached.
stop_price: (optional) The price at which the order converts to a market order. If used with limit_price, the price where the order converts to a limit order.
Returns
An order id.
'''
if sid is Security:
security = sid
else:
security = this.context.framework.allSecurities[sid]
#logger.info("{0} ordering {1}".format(security.qsec,amount))
orderId = order(security.qsec,amount,limit_price,stop_price)
return orderId
pass
def order_percent(self, sid, percent, limit_price=None, stop_price=None):
"""
Place an order in the specified security corresponding to the given
percent of the current portfolio value.
Note that percent must expressed as a decimal (0.50 means 50\%).
"""
value = self.context.portfolio.portfolio_value * percent
return self.order_value(sid, value, limit_price, stop_price)
def order_target(self, sid, target, limit_price=None, stop_price=None):
"""
Place an order to adjust a position to a target number of shares. If
the position doesn't already exist, this is equivalent to placing a new
order. If the position does exist, this is equivalent to placing an
order for the difference between the target number of shares and the
current number of shares.
"""
if sid in self.context.portfolio.positions:
current_position = self.context.portfolio.positions[sid].amount
req_shares = target - current_position
return self.order(sid, req_shares, limit_price, stop_price)
else:
return self.order(sid, target, limit_price, stop_price)
def order_target_value(self, sid, target, limit_price=None,
stop_price=None):
"""
Place an order to adjust a position to a target value. If
the position doesn't already exist, this is equivalent to placing a new
order. If the position does exist, this is equivalent to placing an
order for the difference between the target value and the
current value.
"""
if sid in self.context.portfolio.positions:
current_position = self.context.portfolio.positions[sid].amount
current_price = self.context.portfolio.positions[sid].last_sale_price
current_value = current_position * current_price
req_value = target - current_value
return self.order_value(sid, req_value, limit_price, stop_price)
else:
return self.order_value(sid, target, limit_price, stop_price)
def order_target_percent(self, sid, target, limit_price=None,
stop_price=None):
"""
Place an order to adjust a position to a target percent of the
current portfolio value. If the position doesn't already exist, this is
equivalent to placing a new order. If the position does exist, this is
equivalent to placing an order for the difference between the target
percent and the current percent.
Note that target must expressed as a decimal (0.50 means 50\%).
"""
if sid in self.context.portfolio.positions:
current_position = self.context.portfolio.positions[sid].amount
current_price = self.context.portfolio.positions[sid].last_sale_price
current_value = current_position * current_price
else:
current_value = 0
target_value = self.context.portfolio.portfolio_value * target
req_value = target_value - current_value
return self.order_value(sid, req_value, limit_price, stop_price)
pass
#class _TradingAlgorithm_ZiplineShim(zipline.TradingAlgorithm):
# '''auto-generates a context to use'''
# def initialize(this):
# #delay initialize until start of first handle-data, so our
# #portfolio object is available
# #this.__isInitialized = False;
# this.context = Shims.Context()
# this.context.tradingAlgorithm = this
# #this.context.portfolio = this.portfolio
# pass
# def handle_data(this,data):
# this.context.portfolio = this.portfolio
# #if not this.__isInitialized:
# # this.__isInitialized=True
# # this.context.portfolio=this.portfolio
# this.context.framework._update(data)
# pass
# pass
class FrameHistory:
def __init__(this,parent,framework, data):
this.parent = parent
this.framework = framework
this.state = []
this.isActive = this.parent.isActive
#this.maxHistoryFrames = this.framework.maxHistoryFrames
#assert(this.framework.simFrame == this.parent.simFrame, "parent frame
#does not match")
this.initialize(data)
def initialize(this, data):
'''overridable'''
logger.error("FrameHistory.initialize() invoked. You should override this method.")
pass
def constructFrameState(this,data):
'''override and return the frame state, this will be prepended to history
if you return NONE, the frame state (history) is not modified.'''
logger.error("FrameHistory.constructFrameState() invoked. You should override this method.")
pass
def _update(this,data):
this.isActive = this.parent.isActive
if not this.isActive:
return
currentState = this.constructFrameState(data)
if(currentState != None):
currentState.datetime = this.framework._getDatetime()
currentState.simFrame = this.framework.simFrame
this.state.insert(0,currentState)
del this.state[this.framework.maxHistoryFrames:]
class StrategyPosition:
'''allows two or more stratgies to controll their own positions (orders) for securities they care about,
without interfering with the orders of other strategies.
To use: each strategy should set security.myStrategyPositon.targetCapitalSharePercent, which is a percentage of your entire portfolio's value
then execute the order (and/or rebalance) by invoking security.myStrategyPosition.processOrder()
'''
def __init__(this, security, strategyName):
this._security = security
this._strategyName = strategyName
this._lastOrderId = 0
this._lastStopOrderId = 0
this._currentCapitalSharePercent = 0.0
this._currentShares = 0
#for the last trade roundtrip, the aproximate returns. set every time our percent changes to zero
this._lastRoundtripReturns = 0.0
#this is editable
this.targetCapitalSharePercent = 0.0
#price when we decided to order, not actually the fulfillment price
this.__lastOrderPrice = 0.0
this.__currentPeakGains = 0.0
this.__currentPeakGainsDecay = 0.0
this._currentReturns = 0.0 #returns of current open position.
this._totalTrades = 0 #total trades we execute via this strategyPosition. note that due to partial fills, this may be less than actual trades
def processOrder(this, data, rebalanceThreshholdPercent=0.05, maxLosses=None, maxGainsAdditionalDrawdown=None, maxGainsDecay=0.01): #, OBSOLETE_stopLimitPercent=0.0, OBSOLETE_momentumStopLimit = True, OBSOLETE_decayMomentum = 0.001):
''' set rebalanceThreshholdPercent to zero (0.0) to cause the position to readjust even if the targetPercentage doesn't change. this is useful for reinvesting divideds / etc
but is set to 0.05 (5 percent) so we don't spam orders
maxLosses: close if our open position suffers a loss of this percent or more
maxGainsAdditionalDrawdown : close if our open position's gains suffer a decrease of this+maxLosses or more.
maxGainsDecay : over time this will reduce the acceptable gains drawdown (specified by maxGainsAdditionalDrawdown) so that on long-running gains we don't incur such a large drawdown before closing.
'''
#if momentumStopLimit == True (the default) we will stopLimitPercent based on the peak gains, not based on the original purchase price (this is generally a good ideas as it will maximize your gains)
#decayMomentum : = if == 0.01 and using momentumStopLimit==True, we will decay the position's survival chances by 1% per tick until it's finally closed.
if this._currentCapitalSharePercent == 0.0 and this.targetCapitalSharePercent == 0.0:
#no work to do
return 0
currentPrice = data[this._security.qsec].close_price
if this._currentCapitalSharePercent == this.targetCapitalSharePercent and this._currentCapitalSharePercent != 0.0:
#update current returns
this._currentReturns = (currentPrice - this.__lastOrderPrice) / this.__lastOrderPrice * math.copysign(1.0,this._currentCapitalSharePercent)
else:
#target is different so reset our returns as we are about to change our order
this._currentReturns = 0.0
if this._currentCapitalSharePercent == this.targetCapitalSharePercent and maxGainsAdditionalDrawdown != None:
##handle maxGains stoplimits
gainsPercent = this._currentReturns - this.__currentPeakGainsDecay
#if gainsPercent < -maxLosses:
# #loosing, so close out
# logger.debug("loosing, so close out. gainsPercent={0}, maxLosses={1}".format(gainsPercent, maxLosses))
# this.targetCapitalSharePercent = 0.0
#else:
if this._currentReturns > this.__currentPeakGains:
this.__currentPeakGains = this._currentReturns
this.__currentPeakGainsDecay = 0.0 #reset decay
else:
#need to see if our gain exceed our stoplimitGains threshhold
gainsFloorThreshhold = this.__currentPeakGains * maxGainsAdditionalDrawdown
if gainsPercent < gainsFloorThreshhold:
lossesFromPeak = this.__currentPeakGains - gainsPercent
if maxLosses != None and lossesFromPeak < maxLosses:
#we are not yet exceeding maxLosses (from our peak) so don't close out yet
logger.debug("we are not yet exceeding maxLosses (from our peak) so don't close out yet. \t {0} @ {1}, gains={2}".format(this._security.symbol,currentPrice,this._currentReturns))
pass
else:
#loosing from our peak, so close out
logger.debug("loosing from our peak, so close out. gainsPercent={0:.4f}, \t gainsFloorThreshhold={1:.4f}, \t lossesFromPeak={2:.4f}, \t maxLosses={3:.4f} \t this._currentReturns={4:.4f}".format(gainsPercent, gainsFloorThreshhold, lossesFromPeak, maxLosses,this._currentReturns))
this.targetCapitalSharePercent = 0.0
this.__currentPeakGainsDecay += (this.__currentPeakGains * maxGainsDecay)
else:
this.__currentPeakGains = 0.0
this.__currentPeakGainsDecay = 0.0
if this._currentCapitalSharePercent == this.targetCapitalSharePercent and this._currentCapitalSharePercent != 0.0:
#handle maxlosses stoplimit
if maxLosses != None and this._currentReturns < -maxLosses:
logger.debug("maxlosses stoplimit. this._currentReturns={0}, maxLosses={1}".format(this._currentReturns, maxLosses))
this.targetCapitalSharePercent = 0.0
if this.targetCapitalSharePercent == 0.0 and this._currentCapitalSharePercent != 0.0:
#record our expected PnL
this._lastRoundtripReturns = this._currentReturns
this._currentCapitalSharePercent = this.targetCapitalSharePercent
#determine value of percent
targetSharesValue = this._security.framework.context.portfolio.portfolio_value * this._currentCapitalSharePercent
targetSharesTotal = int(math.copysign(math.floor(abs(targetSharesValue / currentPrice)),targetSharesValue))
targetSharesDelta = targetSharesTotal - this._currentShares
if targetSharesTotal != 0:
if abs(targetSharesDelta / (targetSharesTotal * 1.0)) < rebalanceThreshholdPercent:
#logger.debug("{0} ORDER SKIPPED! {1} (change to small) : {2} + {3} => {4} shares".format(this.strategyName,this.security.symbol, this.currentShares, targetSharesDelta, targetSharesTotal))
#our position change was too small so we skip rebalancing
return
#do actual order
if(abs(targetSharesDelta) >= 1): #can not perform an order on less than 1 share
####cancel previous open order, if any #doesn't really work, as even when canceling, some shares may be filled so you'll be left in an uncomplete state
###lastOrder = get_order(this.lastOrderId)
###unfilled = lastOrder.amount - l
###cancel_order(this.lastOrderId)
logger.info("{0} order {1} : {2} + {3} => {4} shares \t \t decisionPrice={5} ".format(this._strategyName,this._security.symbol, this._currentShares, targetSharesDelta, targetSharesTotal,currentPrice))
this._lastOrderId = this._security.framework.tradingAlgorithm.order(this._security.sid,targetSharesDelta,None,None)
this._currentShares = targetSharesTotal
this.__lastOrderPrice = currentPrice
this._totalTrades += 1
this._security.framework._totalTrades += 1
return this._lastOrderId
else:
return 0
class Security:
isDebug = False
class QSecurity:
'''
Quantopian internal security object
If you have a reference to a security object, there are several properties that might be useful:
sid = 0 #Integer: The id of this security.
symbol = "" #String: The ticker symbol of this security.
security_name = "" #String: The full name of this security.
security_start_date = datetime.datetime() #Datetime: The date when this security first started trading.
security_end_date = datetime.datetime() #Datetime: The date when this security stopped trading (= yesterday for securities that are trading normally, because that's the last day for which we have historical price data).
'''
def __init__(this):
this.sid = 0 #Integer: The id of this security.
this.symbol = "" #String: The ticker symbol of this security.
this.security_name = "" #String: The full name of this security.
this.security_start_date = datetime.datetime(1990,1,1) #Datetime: The date when this security first started trading.
this.security_end_date = datetime.datetime(1990,1,1) #Datetime: The date when this security stopped trading (= yesterday for securities that are trading normally, because that's the last day for which we have historical price data).
def __init__(this,sid, framework):
this.sid = sid
this.isActive = False
this.framework = framework
this.security_start_date = datetime.datetime.utcfromtimestamp(0)
this.security_end_date = datetime.datetime.utcfromtimestamp(0)
this.simFrame = -1
this.security_start_price = 0.0
this.security_end_price = 0.0
#this.daily_open_price = [0.0]
#this.daily_close_price = [0.0]
this.symbol = "??? Not yet active so symbol not known"
def getCurrentPosition(this):
if this.simFrame == -1:
return Shims.Position()
return this.framework.context.portfolio.positions[this.qsec]
def update(this,qsec, data):
'''qsec is only given when it's in scope, and it can actually change each timestep
what it does:
- construct new state for this frame
- update qsec to most recent (if any)
'''
#update our tickcounter, mostly for debug
this.simFrame = this.framework.simFrame
#assert(this.simFrame >= 0,"security.update() frame not set")
#update qsec to most recent (if any) 67
this.qsec = qsec
if qsec:
this.isActive = True
this.symbol = qsec.symbol
#assert(qsec.sid == this.sid,"security.update() sids do not match")
if this.security_start_price == 0.0:
this.security_start_price = data[this.sid].close_price
this.security_end_price = data[this.sid].close_price
this.security_start_date = qsec.security_start_date
this.security_end_date = qsec.security_end_date
else:
this.isActive = False
#try:
# this.daily_close_price =
# this.framework.daily_close_price[this.qsec]
# this.daily_open_price = this.framework.daily_open_price[this.qsec]
#except:
# this.daily_close_price = []
# this.daily_open_price = []
#if len(this.daily_close_price) == 0 or len(this.daily_open_price) ==
#0:
# this.isActive = False
class FrameworkBase():
def __init__(this, context, data, maxHistoryFrames=60): #5 days of history
this.maxHistoryFrames = maxHistoryFrames
this.__isFirstTimestepRun = False
this.context = context
this.tradingAlgorithm = Shims._TradingAlgorithm_QuantopianShim() #prepopulate to allow intelisence
this.tradingAlgorithm = context.tradingAlgorithm
this.simFrame = -1 #the current timestep of the simulation
this.framesToday = -1 #number of frames executed today
this.allSecurities = {} #dictionary of all securities, including those not targeted
this.activeSecurities = {}
this.thisFrameDay = 0
this.lastFrameDay = 0
this._totalTrades = 0 #total trades we execute via all strategyPositions. note that due to partial fills, this may be less than actual trades
this.isIntradayRunDetected = False #if we are running in intraday, this will be set to true on frame 2. the 2nd bar will be in the same day as the first bar. no better way to detect unfortunately.
#for storing quantopian history
#this.daily_close_price = pandas.DataFrame()
#this.daily_open_price = pandas.DataFrame()
this._initialize(data)
pass
def ensureMinHistory(this, minFrames):
'''increases the history frames if the current is less than your required min.
this is a good way to set your history, as too much history will slow down your sim, and can crash it due to out-of-memory'''
if this.maxHistoryFrames < minFrames:
this.maxHistoryFrames = minFrames
def _initialize(this, data):
'''starts initialiation of the framework
do not override this, or any other method starting with an underscore.
methods without an underscore prefix can and should be overridden.'''
#do init here
this.initialize(data)
pass
def initialize(this, data):
'''override this to do your init'''
logger.error("You should override FrameworkBase.initialize()")
pass
def initializeFirstUpdate(this,data):
'''override this. called the first timestep, before update.
provides access to the 'data' object which normal .initialize() does not'''
logger.error("You should override FrameworkBase.initializeFirstUpdate()")
pass
def _update(this,data):
'''invoked by the tradingAlgorithm shim every update. internally we will call abstract_update_timestep_handle_data()
DO NOT OVERRIDE THIS OR ANY METHODS STARTING WITH AN UNDERSCORE
override methods without underscores.
'''
#frame updates
#this.data = data
this.simFrame+=1
this.lastFrameDay = this.thisFrameDay
this.thisFrameDay = this._getDatetime().day
#supdating our history once per day
if(this.thisFrameDay != this.lastFrameDay):
#only update this once per day, hopefully improving performance...
#this.daily_close_price = history(bar_count=180, frequency='1d',
#field='close_price')
#this.daily_open_price = history(bar_count=180, frequency='1d',
#field='open_price')
this.framesToday = 0
else:
this.framesToday += 1
this.isIntradayRunDetected = True
this.__updateSecurities(data)
if not this.__isFirstTimestepRun:
this.__isFirstTimestepRun = True
this.initializeFirstUpdate(data)
this.update(data)
pass
def update(this,data):
'''override and update your usercode here'''
logger.error("You should override FrameworkBase.update()")
pass
def __updateSecurities(this,data):
'''get all qsecs from data, then update the targetedSecurities accordingly'''
#logger.debug("FrameworkBase.__updateSecurities() start.
#allSecLength={0}".format(len(this.allSecurities)))
#convert our data into a dictionary
currentQSecs = {}
newQSecs = {}
for qsec in data:
#if online, qsec is a securities object
sid = qsec.sid
#logger.debug("FrameworkBase.__updateSecurities() first loop, found
#{0}, sid={1}. exists={2}".format(qsec,
#sid,this.allSecurities.has_key(sid) ))
currentQSecs[sid] = qsec
#determine new securities found in data
if not this.allSecurities.has_key(sid):
logger.debug("FrameworkBase.__updateSecurities() new security detected. will construct our security object for it: {0}".format(qsec))
newQSecs[sid] = qsec
#construct new Security objects for our newQSecs
for sid, qsec in newQSecs.items():
#assert(not
#this.allSecurities.has_key(sid),"frameworkBase.updateSecurities
#key does not exist")
#logger.debug("FrameworkBase.__updateSecurities() new security
#found {0}".format(qsec))
this.allSecurities[sid] = this._getOrCreateSecurity(qsec, data)
newQSecs.clear()
#update all security objects, giving a null qsec if one doesn't exist
#in our data dictionary
for sid, security in this.allSecurities.items():
qsec = currentQSecs.get(sid)
security.update(qsec, data)
## determine active securities set.
this.activeSecurities.clear()
for sid,security in this.allSecurities.items():
if not security.isActive:
#logger.debug("FrameworkBase.__updateSecurities() NOT ACTIVE
#{0}".format(security.qsec))
continue
#logger.debug("FrameworkBase.__updateSecurities() ACTIVE
#{0}".format(security.qsec))
this.activeSecurities[sid] = security
pass
pass
def initializeSecurity(this,security, data):
'''override to do custom init logic on each security.
if you wish to use your own security, return it (it will replace the existing)'''
logger.error("You should override FrameworkBase.initializeSecurity()")
pass
def _getOrCreateSecurities(this,qsecArray, data):
'''pass in an array of quantopian sid/sec tuples (ex: [(24,sid(24)),(3113,sid(3113))])
and returns an array of unique security objects wrapping them. duplicate sids are ignored'''
securities = {}
for qsec in qsecArray:
security = this._getOrCreateSecurity(qsec, data)
securities[security.sid] = security
pass
return securities.values()
def _getOrCreateSecurity(this, qsec, data):
'''pass in a quantopian sec (ex: sid(24)) and returns our security object wrapping it
if the security object
'''
sid = qsec.sid
if this.allSecurities.has_key(sid):
return this.allSecurities[sid]
#does not exist, have to create
newSecurity = Security(sid,this)
#new, so do our framework's custom init logic on this security
maybeNewSec = this.initializeSecurity(newSecurity, data)
if maybeNewSec is not None:
#framework replaced newSec with a different sec
newSecurity = maybeNewSec
this.allSecurities[sid] = newSecurity
return newSecurity
pass
def _getDatetime(this):
'''returns current market time, using US/Eastern timezone'''
#if is_offline_Zipline:
# if len(this.allSecurities) == 0:
# #return datetime.datetime.fromtimestamp(0,pytz.UTC)
# return
# pandas.Timestamp(datetime.datetime.fromtimestamp(0,pytz.UTC)).tz_convert('US/Eastern')
# else:
# assert(False,"need to fix this to return something valid. all
# securities isn't good enough. probably search for first
# active")
# return this.allSecurities.values()[0].datetime
#else:
# return get_datetime()
#pass
return pandas.Timestamp(pandas.Timestamp(get_datetime()).tz_convert('US/Eastern'))
#entrypoints