Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trading on Golden Cross - Please Help

Hi guys,

I'm a newbie on this site. Was trying to code a textbook example to get things started,
(buying on golden cross and closing position when gain/lose 5 %, repeat ad infinitum) but the backtest results show that I messed up somewhere - could someone point out the error?
Should be easy for experienced members.. would be much appreciated.

# want to code an algorithm to test a simple trading strategy based on moving  
#averages. Buy if golden cross appears, sell if death cross appears. close position  
#if gain or lose 5% after placing the order. Use 50 and 100 day moving averages. 

def initialize(context):  
    context.aapl = sid(24)  
    context.max_notional = 1000000.1  
    context.min_notional = -1000000.0  

def handle_data(context, data):  

    MAVG1 = data[sid(24)].mavg(50)  
    MAVG2 = data[sid(24)].mavg(100)  
    price = data[context.aapl].price  
    notional = context.portfolio.positions[context.aapl].amount*price  
    orderGoldenPrice = 0  
    orderDeathPrice = 0  
    counter = 0  
    if MAVG1 > MAVG2*1.001 and notional < context.max_notional and counter == 0:  
        order(context.aapl, 100)  
        orderGoldenPrice = price  
        counter = 1  
        log.info(counter)  
        log.info(price)  
        log.info(orderGoldenPrice)  
        log.info("  ")  
    if (price > (1.05*orderGoldenPrice and counter == 1)  
    or (price < 0.95*orderGoldenPrice and counter == 1)):  
        order(context.aapl, -100)  
        counter = 0  
        log.info(counter)  
        log.info(price)  
        log.info(orderGoldenPrice)  

    #elif MAVG1 < MAVG2*0.999 and notional > context.min_notional:  
      #  order(context.aapl, -100)  
2 responses

Hello Leo,

I don't think this is what you had in mind but I had a play. I made the starting capital $100,000 as the algo is only ever short or long 100 shares which peaked at $70,000 or so.

P.

Hi Peter,

This is great. More or less what I wanted to code in the first place - thanks for the help!