I tried to build a bollinger band buy-strategy with stop-loss 12% order, for one stock which seems to work.
def initialize(context):
context.azo = sid(693)
context.stop_loss_pct = 0.12
context.order_cost = 0
context.position = 0
schedule_function(check_bands,date_rules.every_day())
def check_bands(context, data):
price = data.history(context.azo,'price',1,'1d')
ytd_close = price.mean()
prices = data.history(context.azo,'price',20,'1d')
avg = prices.mean()
std = prices.std()
lower_band = avg - 2*std
upper_band = avg + 2*std
if context.position == 0:
if ytd_close <= lower_band:
context.order_cost = ytd_close
context.position = 1
order_target_percent(context.azo,1.0)
print('BUYING')
else:
pass
elif context.position == 1:
if ytd_close >= upper_band:
context.order_cost = 0
context.position = 0
order_target_percent(context.azo,0.0)
print('SELLING')
elif ytd_close <= context.order_cost * (1 - context.stop_loss_pct):
context.order_cost = 0
context.position = -1
order_target_percent(context.azo,0.0)
print('STOP LOSS')
else:
print('CONTINUE IN POSITION')
elif context.position == -1 and ytd_close >= upper_band:
context.position = 0
else:
pass
record(upper=upper_band,
lower=lower_band,
mavg_20 = avg,
price = ytd_close)
But when I tried to modify it to apply to a portfolio of 10 stocks, the stop-loss and sell function seems do not work.
See if anyone could help on it. Thanks.
def initialize(context):
context.stocks = [sid(693), sid(16178), sid(21935), sid(7792), sid(2170), sid(32146), sid(8857), sid(1787), sid(3496), sid(24873)]
context.stop_loss_pct = 0.12
context.order_cost = 0
context.position = 0
schedule_function(check_bands,date_rules.every_day())
def check_bands(context, data):
for stocks in context.stocks:
prices = data.history(stocks,'price',20,'1d')
price = data.history(stocks,'price',1,'1d')
ytd_close = price.mean()
avg = prices.mean()
std = prices.std()
lower_band = avg - 2*std
upper_band = avg + 2*std
if context.position == 0:
if ytd_close <= lower_band:
context.order_cost = ytd_close
context.position = 1
order_target_percent(stocks,0.1)
print('BUYING '+ str(stocks))
else:
pass
elif context.position == 1:
if ytd_close >= upper_band:
context.order_cost = 0
context.position = 0
order_target_percent(stocks,0.0)
print('SELLING '+ str(stocks))
elif ytd_close <= context.order_cost * (1 - context.stop_loss_pct):
context.order_cost = 0
context.position = -1
order_target_percent(stocks,0.0)
print('STOP LOSS '+ str(stocks))
else:
print('CONTINUE IN POSITION '+ str(stocks))
elif context.position == -1 and ytd_close >= upper_band:
context.position = 0
else:
pass
record(upper=upper_band,
lower=lower_band,
mavg_20 = avg,
price = ytd_close)