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])