Hello,
I met some problems when implementing a simple pairs trading algorithm, wondered if anyone could assist me with some of my codes. The algorithm is easy, I have detected sid(27809) and sid(28145) were high correlated for the former half year(Jan 1 - July 31). What I want to do contains 3 steps:
Step 1: normalized each stock's price, by dividing each day's price by the first day(Jan 1)'s price.
Step 2: get difference of these two stock's price difference, like diff(stock1 - stock2), let's call this line by diff-line
Step 3: get two Bollinger bands (one with 1 times variation, the other with 2 times variation) of the diff-line, when diff-line gets above the 2 times upper band, long stock2 short stock1 by same amount of money, and when abs-line touch the 1 times upper bank, end the investment. And use the same way when diff-line gets lower bands.
I have tried to implemented as follows, according to a former pairs trading strategy on this website, but unfortunately unfamiliar with the library in Quantopian. Hope someone could help me, thanks in advance.
def initialize(context):
context.stock1 = sid(27809)
context.stock2 = sid(28145)
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
diff = data[context.stock1]/data[context.stock1][0] - data[context.stock2]/data[context.stock2][0]
deviation = diff.stddev(5)
if(deviation != None):
mean = diff.mavg(5)
zscore = (diff.price - mean) / deviation
if(zscore > 2.0):
order(context.stock1, -100)
order(context.stock2, 200)
elif(zscore < -2.0):
order(context.stock1, 100)
order(context.stock2, -200)
elif(zscore > -1.0 or zscore < 1.0):
reduce_position(context.stock1, context.portfolio, 100)
reduce_position(context.stock1, context.portfolio, 200)
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)