I'm trying to make a portfolio construction model that only allows a set amount of equal weighted positions based on the total value of the portfolio. However, when a stock is shorted it adds money to the portfolio that then is included in the calculation for how many positions it can open that day, resulting in it trying to open more positions than it can. The code works great for only long positions, but I want to be able to open both short and long positions at the same time. Does anyone know of any way to solve this?

Here is my code:

import numpy as np

class MaximumPositionPortfolio(PortfolioConstructionModel):
def __init__(self, algorithm, positionLimit):
self.positionLimit = positionLimit
self.percent = 1/self.positionLimit

def CreateTargets(self, algorithm, insights):

targets = []

#calculates how big the position should be
positionSize = algorithm.Portfolio.TotalPortfolioValue*self.percent
#calculates how many positions to let through
openPositions = np.floor(algorithm.Portfolio.Cash/positionSize)

#counts how many positions have been opened
count = 0
for i in insights:

#closes positions with a flat insight
if i.Direction == InsightDirection.Flat:
targets.append(PortfolioTarget(i.Symbol, 0))

#opens long positions
elif i.Direction == InsightDirection.Up:
if count < openPositions:
count += 1
targets.append(PortfolioTarget.Percent(algorithm, i.Symbol, self.percent))

#opens short positions
elif i.Direction == InsightDirection.Down:
if count < openPositions:
count += 1
targets.append(PortfolioTarget.Percent(algorithm, i.Symbol, -self.percent))

return targets

def OnSecuritiesChanged(self, algorithm, changes):