Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How do you exit/close a long position only?

When you have a long and short positions open and just want to close out the short position only how do you do that? Is there a way to say "If position is long/if position is short"?

5 responses

Hassan,

I usually do something like this:

long_stocks = []  # empty list to store long positions  
for position in context.portfolio.positions: # iterate through all positions in portfolio  
        Shares_Owned = context.portfolio.positions[position].amount # obtain the quantity of shares owned  
        if Shares_Owned > 0: # determine if shares owned is positive (i.e. a long position)  
                long_stocks.append(position) # append the long stock to the long stock list  
for stock in long_stocks: # iterate through the list of long stocks  
       order_target_percent(stock, 0) # close position in long stock




Doesn't seem to work. When I debug and step through line by line this line of code for position in context.portfolio.positions: the back-tester skips all the code below it/doesn't go through.

Have you ensured that your portfolio has at least 1 open position before running these lines of code?

Yes I have here's the code, am buying a long and short position but it won't sell.

hassan,

I cloned the algorithm and ran a backtest. The algo just sends an order to buy and also sell SPY every day in the morning. This is being done in the following function:

def buy_open(context, data):  
    open_price = data.current(context.spy, 'open')  
    open_orders = get_open_orders()  
    context.exit_price = int(open_price) + 1  
    context.exit_short = int(open_price) - 1  
    if context.spy not in open_orders:  
        order_target_percent(context.spy, .50)  
        print "Bought LONG At: Open is: %.2f And Exit is: %.2f" %(open_price, context.exit_price)  
        order_target_percent(context.spy, -.50)  
        print "Bought SHORT At: Open is: %.2f And Exit is: %.2f" %(open_price, context.exit_short)  

if you comment out the order to sell, it will begin to take on long positions every morning.