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):
pass
Simon Koeman
Found the solution. If anyone stumbles across this post with a similar question, Portfolio.MarginRemaining is the amount of money available for trades, not Portfolio.Cash
Simon Koeman
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!