Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Rookie error - selling

Hi all, I can't seem to make this code work. I'm trying to buy shares when the price increases and sell when it decreases. However, I cannot make the code sell shares when I want. Any solutions?

def initialize(context):  
    context.security = sid(24)

def handle_data(context, data):  
    prices = data.history(context.security, "price", 5, '1m')  
    last_min = prices.iloc[-1] # get the price 1 min ago  

    # We also get the stock's current price.  
    current_price = data.current(context.security, 'price')  
    money = context.portfolio.cash  
    sell = context.portfolio.positions[sid(24)].amount  
    # If our stock is currently listed on a major exchange  
    if data.can_trade(context.security):  
     if current_price > last_min:  
            # Place the buy order  
       order_value(context.security, money)  
       log.info("Buying %s" % (context.security.symbol))  
    elif current_price < last_min:  
            # Sell all of our shares  
       order_percent(context.security, -1)  
       log.info("Selling %s" % (context.security.symbol))  

    print current_price


3 responses

Indent the elif so it matches the second if.

Currently, you would only attempt to sell if your security "can't trade" and current_price < last_min.

Thanks, that worked! I also noticed there was another slight error. For anyone wondering this was the solution:

def initialize(context):  
    context.security = sid(24)

def handle_data(context, data):  
    prices = data.history(context.security, "price", 5, '1m')  
    last_min = prices.iloc[-2] # get the price 1 min ago  

    # We also get the stock's current price.  
    current_price = data.current(context.security, 'price')  
    money = context.portfolio.cash  
    sell = context.portfolio.positions[sid(24)].amount  
    # If our stock is currently listed on a major exchange  
    if data.can_trade(context.security):  
       if current_price > last_min:  
            # Place the buy order  
         order_value(context.security, money)  
         log.info("Buying %s" % (context.security.symbol))  
      elif current_price < last_min:  
            # Sell all of our shares  
         order_percent(context.security, -sell)  
         log.info("Selling %s" % (context.security.symbol))  

    print current_price

This won't work because now the elif has no matching if.

Another thing: the .amount field is incorrectly named. It represents the number of shares, not the (monetary) amount of anything. To sell all the shares of a security you have, you should either order(..., -sell) or order_target_percent(..., 0.0).