Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Unexpected behaviour with context.portfolio.positions[sid].amount

Hello,

I'm trying to calculate how many shares to buy or sell based on context.portfolio.positions[sid].amount but I'm getting unexpected behaviour.

Here's my code:

def stock_quantity(sid, close, context):  
    number_of_stocks = context.portfolio.positions[sid].amount  
    message = '1> {s}: number_of_stocks = {n}, portfolio.pos = {p}'  
    log.debug( message.format( s=sid, n=number_of_stocks, p=context.portfolio.positions[sid].amount ))  
    if ( context.portfolio.positions[sid].amount < 0 ):  
        number_of_stocks = abs( number_of_stocks )  
    if ( context.portfolio.positions[sid].amount == 0 ):  
        cash = context.portfolio.cash  
        number_of_stocks = int( cash/close )

    message = '2> {s}: number_of_stocks = {n}, portfolio.pos = {p}'  
    log.debug( message.format( s=sid, n=number_of_stocks, p=context.portfolio.positions[sid].amount ))           

    return number_of_stocks  

The first time though the stock quantity is calculated correctly using the line
number_of_stocks = int( cash/close ) Lets say it equates to 14055 stocks but the next time through I'm expecting to retrieve the same number of stocks (14055) instead I get -1350 from the line
number_of_stocks = context.portfolio.positions[sid].amount Why doesn't context.portfolio.positions[sid].amount contain 14055 as I expect?

Just for your information after I calculate the number of shares I pass the order command which I assumed would update context.portfolio.positions[sid].amount but doesn't seem to.

Any help appreciated.
Andrew

4 responses

Hi Andrew,

Can you share more of your code to give more context about how the orders are being placed? If you don't want to share it publicly, you can add me as a collaborator ([email protected]) and I can take a look in the IDE. Looking over the code snippet you pasted, the syntax and commands look correct.

An observation is the code doesn't have logic to handle the case when context.portfolio.positions[sid].amount > 0. Could this be playing into the rest of the behavior?

Also, another aspect to think about is slippage - by default orders are filled up to 25% of the transacted volume per bar. If you have a large order, this may get filled over several bars in the backtest to simulate real-market conditions. You can change the parameter to any value, including turning it off completely for testing.

Hope that gives you a push in the right direction

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hi Alisa,

Thanks for your response.

I think you're right, slippage is my problem (plus some bugs unfortunately). Could you tell me how I obtain the number of shares that remain unsold in a given timeframe please and the price the order went through as? Haven't seem anything detailing that - I've probably missed it if there is!!

Thanks again,
Andrew

Sure, to track the open orders in your algorithm you can use the get_open_orders function.

By default it will return all open orders in the algorithm:

# retrieve all the open orders and log the total open amount  
    # for each order  
    open_orders = get_open_orders()  
    # open_orders is a dictionary keyed by sid, with values that are lists of orders.  
    if open_orders:  
        # iterate over the dictionary  
        for security, orders in open_orders.iteritems():  
            # iterate over the orders  
            for oo in orders:  
                message = 'Open order for {amount} shares in {stock}'  
                message = message.format(amount=oo.amount, stock=security)  
                log.info(message)  

If you want to see the open orders for a specific stock, you can specify the security like: get_open_orders(sid=sid). Here is an example that iterates over open orders in one stock:

# retrieve all the open orders and log the total open amount  
    # for each order  
    open_aapl_orders = get_open_orders(context.aapl)  
    # open_aapl_orders is a list of order objects.  
    # iterate over the orders in aapl  
    for oo in open_aapl_orders:  
        message = 'Open order for {amount} shares in {stock}'  
        message = message.format(amount=oo.amount, stock=security)  
        log.info(message)  

You can't get the fill price exactly in the backtest, but you can retrieve the cost basis and commissions.

# place an order if we don't own any shares  
 if context.shares_bought == 0:  
        context.order_a = order(sid(24), 5)  
        context.shares_bought = 1  
    # track the order ID (we need to save it because it gets discarded at the end of each run of handle_data  
    order_data = get_order(context.order_a)

    # get the information when the order is filled  
    if order_data['status'] == 1:  
        log.info("Order is filled.")  
        log.info('Total commission: '+str(order_data['commission']))  
        log.info('Commission per share: '+str(order_data['commission']/order_data['filled']))  
        log.info('Cost basis: '+str(context.portfolio.positions[sid(24)].cost_basis))  
    else:  
        log.info("Order isn't filled yet.")  
    log.info('-------------------------------')  

While you're working through the bugs and errors in the code, have you tried using the debugger? It's a feature we recently released in the IDE to inspect the code. Check out the announcement (and gif!) and you can read more details in the help doc. Good luck!

Hi Alisa,

Thanks very much for this, it helps a lot. I'll have a play around with it.

On another subject, I've invited you to collaborate on another script I'm having difficulties with. Hope you don't mind having a look at it for me!

Thanks again for your response.
Andrew