Put any initialization logic here. The context object will be passed to
the other methods in your algorithm.
def initialize(context):
context.stock1 = sid(14848)
context.stock2 = sid(47740)
Will be called on every trade event for the securities you specify.
def handle_data(context, data):
deviation = data[context.stock1].stddev(30)
if(deviation != None):
mean = data[context.stock1].mavg(30)
zscore = (data[context.stock1].price - mean) / deviation
# for cash in context.portfolio.cash:
if context.portfolio.positions_value 4.0):
order_percent(context.stock1, -.5)
order_percent(context.stock2, .5)
elif(zscore < -4.0) and context.portfolio.positions_value<1.1*context.portfolio.starting_cash:
order_percent(context.stock1, .5)
order_percent(context.stock2, -.5)
def rebalance(context, data):
elif context.portfolio.returns>1.1:
order_target(context.stock1, 0)
order_target(context.stock2, 0)
elif(zscore > -4.0 or zscore < 4.0):
reduce_position(context.stock1, context.portfolio, all)
# reduce_position(context.stock1, context.portfolio, all)
# log.info("Positions reduced")
def reduce_position(stock, portfolio, abs_quantity):
"""
decrease exposure, regardless of position long/short.
buy for a short position, sell for a long.
"""
pos_amount = portfolio.positions[stock].amount
if pos_amount > 0:
order(stock, -1 * abs_quantity)
elif pos_amount < 0:
order(stock, abs_quantity)
I just fix the code. But the algo does not close the position. Do you know why? Thank you!