Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Statistical Arbitrage Try

Hi guys,

So I am in the process of creating my first code and I am really having some trouble. I am trying to use statistical arbitrage and sell when one airline stock falls below the average of other airline stocks. If anyone could help me out in making this successful that would be really amazing. Thanks.

def initialize(context):

    set_slippage(slippage.FixedSlippage(spread=.05))  
    set_commission(commission.PerTrade(cost=7))  
    context.jblu = sid(23599)  
    context.dal = sid(33729)  
    context.luv = sid(4589)  
    context.ual = sid(28051)  
    context.current_stock = sid(23599)

    context.max_notional = 100000.1  
    context.min_notional = -100000.0

def handle_data(context, data):  
    pavg = ((((data[context.jblu].close_price)-(data[context.jblu].open_price))/(data[context.jblu].open_price))*100)  
    pavg2 = ((((data[context.dal].close_price)-(data[context.dal].open_price))/(data[context.dal].open_price))*100)  
    pavg3 = ((((data[context.luv].close_price)-(data[context.luv].open_price))/(data[context.luv].open_price))*100)  
    pavg4 = ((((data[context.ual].close_price)-(data[context.ual].open_price))/(data[context.ual].open_price))*100)

    price = ((((data[context.jblu].close_price)-(data[context.jblu].open_price))/data[context.jblu].open_price)*100)

    average = ((pavg + pavg2 + pavg3 + pavg4)/4)  
    #record(Cash=context.portfolio.cash)  
    record(Average=average)  
    record(Price=price)

    notional = context.portfolio.positions[context.jblu].amount * price

    if price < (average) and notional > context.min_notional:  
        message = context.portfolio.positions[context.jblu].amount  
        log.info(message)  
        message = context.portfolio.cash  
        log.info(message)  
        message = 'Buy'  
        log.info(message)  
        order(context.jblu, +10)  
    elif price >= (average) and context.portfolio.positions[context.jblu].amount > 1 and notional < context.max_notional:  
        message = context.portfolio.positions[context.jblu].amount  
        log.info(message)  
        message = context.portfolio.cash  
        log.info(message)  
        message = 'Sell'  
        log.info(message)  
        order_target_percent(context.jblu, 0)  
2 responses

Here is a backtest of my algorithm right now

I am really looking for a way to buy once and hold until the price goes above the average, then sell once it does, and then buy again. Some of my problem is that it continuously shorts when the price is below the average; I want it to hold longer.