Louisinator
Louisinator

Reputation: 67

How to allow shorts in PortfolioAnalytics - R

I need to allow shorts in my portfolio optimization workflow. This is the code I have:

library(quantmod)

symbol_list = c('AAPL','MSFT','GOOGL','AMZN','TSLA','BRK-A','META', 'UNH','NVDA', 'JNJ')

maxDate <- "2017-10-27"
minDate <- "2022-10-26"
getSymbols(symbol_list,from = maxDate, to = minDate)
getSymbols("^GSPC",from = maxDate, to = minDate)

# Var y covars -------------------------------------------------------

library(PerformanceAnalytics)

securities_matrix = NULL

for( sym in symbol_list){
  securities_matrix = merge.xts(securities_matrix,Return.calculate(Ad(get(paste(sym))),method='discrete'))
}

securities_matrix=securities_matrix[complete.cases(securities_matrix)]
SPYReturn=Return.calculate(Ad(GSPC),method='discrete')
SPYReturn[1]<- 0

library(PortfolioAnalytics)
library(DEoptim)

fund.names <- colnames(securities_matrix)

# MinimumVariancePortfolio ------------------------------------------------

MinimumVariancePortfolio=portfolio.spec(assets=fund.names)

#full_investment
MinimumVariancePortfolio=add.constraint(
  portfolio = MinimumVariancePortfolio,
  type="full_investment")

MinimumVariancePortfolio=add.constraint(
  portfolio = MinimumVariancePortfolio,
  type="long_only")

# Add objetive 
MinimumVariancePortfolio=add.objective(
  portfolio=MinimumVariancePortfolio,
  type="risk", name="StdDev")

.storage <<- new.env()
OptimizedPortfolioMinVariance=optimize.portfolio(
  R=securities_matrix,
  portfolio=MinimumVariancePortfolio, trace=TRUE)

chart.Weights(OptimizedPortfolioMinVariance)

It works perfectly, but it does not allow shorts.

I tried changing this fragment:

MinimumVariancePortfolio=add.constraint(
  portfolio = MinimumVariancePortfolio,
  type="long_only")

to this:

# Shorts and longs
MinimumVariancePortfolio=add.constraint(
  portfolio = MinimumVariancePortfolio,
  type="box", min=-1, max=1)

Since there is a box constrain called 'long_only' I thought changing that box constrain to (type="box", min=-1, max=1) would allow shorts, but the resulting graph does not make sense because it says that every asset should have a weight of 0.

enter image description here

Upvotes: 0

Views: 57

Answers (1)

Louisinator
Louisinator

Reputation: 67

Due to the initialization, the optimizer does not converge, you have to play a little with the restrictions. As an example, for the shorts, you can move the limits to min=-0.9 max=0.9 and so on.

Upvotes: 0

Related Questions