Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help Limiting Losses

Hello everyone,
I was just wondering if it is possible to somehow check every minute whether the price of the security
bought has gone below the price it was bought at, and then sell it off?
Sorry if this is a stupid question, I have been wondering about it for a while.
Cheers

5 responses

yes it's possible. Just use the following code in your handle_data function:

stock_prices = data.current(context.portfolio.positions, 'price')  
for stock in context.portfolio.positions:  
    if get_open_order(stock): return  
    if stock_prices[stock] < context.portfolio.positions[stock].cost_basis:  
        order_target_percent(stock, 0.0)  

I didn't test it but it should work

Thank you for your help!

Hmmm I get an error for this line of code:
stock_prices = data.current(context.portfolio.positions, 'price')
with the error being TypeError: Expected assets argument to be of type or iterable of type Asset, ContinuousFuture, basestring
If you know what's happening help would be greatly appreciated.
Thanks

Try this:

def handle_data(context, data):  
    for stock in context.portfolio.positions:  
        stock_prices = data.current([stock], 'price')  
        if get_open_orders(stock):  
            return  
        if stock_prices[stock] < context.portfolio.positions[stock].cost_basis:  
            order_target_percent(stock, 0.0)  
            print 'Exiting position, price has fallen below cost'  

Cheers for the help that worked!