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

Hi,

How would I set a constant and hold that constant?

For example. If I buy a stock at $50 and I want to sell it at 0.9 * 50.

You can't do something like

price_bought = data[context.security].price  

because it will constantly set price_bought to the newest current price.

1 response

Hi Luke,
You can put variables that you need across handle_data calls as variables in context
So you could do something like

    if (buy_signal):  
        context.order_id = order_value(context.security, amount_to_buy)  
        # Check the order to make sure that it has bought.  
        stock_order = get_order(context.order_id)  
        # The check below shows if the object exists. Only if it exists, should you  
        # refer to it. Otherwise you will get a runtime error  
        if stock_order:  
            context.price_bought = data[context.security].price  


Quantopian also provides you the average cost you bought the stock at inside the portfolio details

context.portfolio.positions[stock].cost_basis