This is just a general question regarding the maximum number of stocks I can use in the r performanceanalytics optimizer function.
My code works fine for optimizing anything up to around 110 assets but anything exceeding that gives an error. I couldn't find any documentation regarding limits around the actual number of assets. Any help is appreciated.
Further to the above, I have added reproducible code example below:
library(xts)
library(PortfolioAnalytics)
num_stocks = 300
num_periods = 200
rets = replicate(num_stocks, rnorm(num_periods))
colnames(rets) = paste0('stock', 1:num_stocks)
dates = seq(as.Date('2000-01-01'), by = 'month', length.out = num_periods) - 1
#100 stocks, returns optimal weights
equity.data = xts(rets, order.by = dates)[,1:100]
stocks <- colnames(equity.data)
# Specify an initial portfolio
portf.init <- portfolio.spec(stocks)
# Add constraints
# weights sum to 1
portf.minvar <- add.constraint(portf.init, type="full_investment")
# box constraints
portf.minvar <- add.constraint(portf.minvar, type="box", min=0.00, max=0.10)
# Add objective
# objective to minimize portfolio variance
portf.minvar <- add.objective(portf.minvar, type="risk", name="var")
optimize.portfolio(equity.data,
portfolio=portf.minvar,
optimize_method="ROI",
trace=TRUE)
## 200 stocks, optimizer returns N/As for optimizes weights
equity.data = xts(rets, order.by = dates)[,1:200]
stocks <- colnames(equity.data)
# Specify an initial portfolio
portf.init <- portfolio.spec(stocks)
# Add constraints
# weights sum to 1
portf.minvar <- add.constraint(portf.init, type="full_investment")
# box constraints
portf.minvar <- add.constraint(portf.minvar, type="box", min=0.00, max=0.10)
# Add objective
# objective to minimize portfolio variance
portf.minvar <- add.objective(portf.minvar, type="risk", name="var")
optimize.portfolio(equity.data,
portfolio=portf.minvar,
optimize_method="ROI",
trace=TRUE)
I think the problem arises because of issues with calculating covariance matrices where (num_stocks = 300) > (num_periods = 200).
If I increase the number of periods to say 1000, there is no error when optimizing for 200 stocks.
Thanks all for your time