Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trying to return the weight of a stock in the portfolio adds it into the portfolio
API

I wanted to make a function that given an Equity, returns 0 if it's not in the current portfolio, else, returns the current weight that it holds in the portfolio. However, for some reason whenever I check to see if it's in the portfolio, it adds the Equity to the actual portfolio (but without any shares). I'm not sure why this is doing this, and clearly there must be a better way. Any suggestions?

Function:

def getAssetWeight(context, name):  
    """  
    Returns the weight of an asset in the portfolio  
    """  
    print "before get asset weight: {0} with iteration at stock {1}".format(context.portfolio.positions, name)  
    if not context.portfolio.positions[name]:  
        print "if not in get asset weight: {0} with iteration at stock {1}".format(context.portfolio.positions, name)  
        return 0  
    else:  
        print "else, before everything get asset weight: {0} with iteration at stock {1}".format(context.portfolio.positions, name)  
        position = context.portfolio.positions[name]  
        weight = (position.amount * position.last_sale_price) / float(context.portfolio.portfolio_value)  
    print "leaving get asset weight: {0} with iteration at stock {1}".format(context.portfolio.positions, name)  
    return weight  

Logs from the function

2011-01-04PRINTbefore get asset weight: {} with iteration at stock Equity(5641 [CAPS])  
2011-01-04PRINTelse, before everything get asset weight: {Equity(5641, symbol=u'CAPS', asset_name=u'CAPSTONE THERAPEUTICS CORP', exchange=u'NASDAQ CAPITAL MARKET', start_date=Timestamp('1993-01-28 00:00:00+0000', tz='UTC'), end_date=Timestamp('2011-07-20 00:00:00+0000', tz='UTC'), first_traded=None): Position({'amount': 0, 'last_sale_price': 0.0, 'cost_basis': 0.0, 'sid': Equity(5641, symbol=u'CAPS', asset_name=u'CAPSTONE THERAPEUTICS CORP', exchange=u'NASDAQ CAPITAL MARKET', start_date=Timestamp('1993-01-28 00:00:00+0000', tz='UTC'), end_date=Timestamp('2011-07-20 00:00:00+0000', tz='UTC'), first_traded=None)})} with iteration at stock Equity(5641 [CAPS])  
2 responses

Solved by using positions.has_key(stock) instead positions[key]

Hi Alexander,

I'm glad to see you solved this issue. In case you were still curious, context.portfolio.positions is a defaultdict so if you try to access a key,value pair from it with a key not already in it, it will create that pair, assigning the value a default value of 0. Using positions.has_key(stock) is a good way to check without adding the default entry. You can also use stock in positions.

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.