Hello Adam and Peter,
I don't have time now, but there is a better way to handle this. Here's a function that may be of interest:
def capital_invested(context, data):
# get a sum total of capital spent or borrowed for all current positions
capital = 0.0 # initialize to zero
# check every stock in current positions (also works with set_universe)
for stock in context.portfolio.positions:
# get amount of shares in current position for this stock
amount = context.portfolio.positions[stock].amount
# get the cost basis of the shares (how much we spent on average per share)
cost_basis = context.portfolio.positions[stock].cost_basis
# check if position is a short trade (negative amount)
amount = max(amount, -amount) # change amount to a positive number
# add dollar amount to the 'spent' total
capital += amount * cost_basis
# return amount of capital tied up in positions
return capital
The max_notional and min_notional can work, but sometimes the algo can run off the tracks if you end up buying/selling large amounts.
Grant