-
Notifications
You must be signed in to change notification settings - Fork 17
/
SMA200.py
53 lines (48 loc) · 2.38 KB
/
SMA200.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
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
context.sids = [sid(8655), sid(5923), sid(7797), sid(8229), sid(5484), sid(7488), sid(3136), sid(438), sid(3806), sid(3499)]
context.long = {}
context.short = {}
context.stop_loss = 1
context.take_profit = 3
context.max_notional = 10000.1
context.min_notional = -10000.0
set_commission(commission.PerTrade(cost=7))
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
all_mavg = 0
all_price = 0
for stock in context.sids:
mavg=data[stock].mavg(200)
all_mavg += mavg
all_price += data[stock].price
notional = context.portfolio.positions[stock].amount * data[stock].price
if stock not in context.long and stock not in context.short and notional < context.max_notional and notional > context.min_notional:
if mavg < data[stock].price:
order(stock, 100)
log.info("Long %f, %s" %(data[stock].price, stock))
context.long[stock] = data[stock].price
else:
order(stock, -100)
log.info("Short %f, %s" %(data[stock].price, stock))
context.short[stock] = data[stock].price
if stock in context.long:
if context.long[stock] - data[stock].price > context.stop_loss:
order(stock, -100)
log.info("LONG Stop loss at %f, %s" %(data[stock].price, stock))
context.long.pop(stock)
elif data[stock].price - context.long[stock] > context.take_profit:
order(stock, -100)
log.info("LONG Take profit at %f, %s" %(data[stock].price, stock))
context.long.pop(stock)
elif stock in context.short:
if data[stock].price - context.short[stock] > context.stop_loss:
order(stock, 100)
log.info("SHORT Stop loss at %f, %s" %(data[stock].price, stock))
context.short.pop(stock)
elif context.short[stock] - data[stock].price > context.take_profit:
order(stock, 100)
log.info("SHORT Take profit at %f, %s" %(data[stock].price, stock))
context.short.pop(stock)
record(MovingAverage200=(all_mavg/10), Price=(all_price/10))