我是R中的Portfolio Optimization的新手。当我向我的投资组合添加超过25个资产(每个资产有大约25个观察值)时,optimize.portfolio找不到任何解决方案。当我运行25个或更少资产的程序时,它可以正常工作并绘制有效边界。对此有任何帮助非常感谢。
library(data.table)
library(readxl)
library(PerformanceAnalytics)
library(PortfolioAnalytics)
library(ROI)
library(foreach)
library(DEoptim)
library(iterators)
library(fGarch)
library(Rglpk)
library(quadprog)
library(ROI.plugin.glpk)
library(ROI.plugin.quadprog)
library(ROI.plugin.symphony)
library(pso)
library(GenSA)
library(corpcor)
library(testthat)
library(nloptr)
library(MASS)
library(robustbase)
library(ggplot2)
setwd("~/R")
#BRING IN DATA
returns.data <- read_excel("portfolio_sample_4asset.xlsx", sheet = "portfolio")
returns.data <- data.frame(returns.data)
row.names(returns.data) <- (returns.data$year)
returns.data$year <- NULL
meanReturns <- colMeans(returns.data)
#GENERATE COVARIANCE AND CORRELATION TABLES
cov.pop <- function(x,y=NULL) {
cov(x,y)*(NROW(x)-1)/NROW(x)
}
covMat <- cov.pop(returns.data)
corMat <- cor(returns.data)
#SPECIFY PORTFOLIO OBJECT
port <- portfolio.spec(assets = colnames(returns.data))
#CONSTRAINTS
port <- add.constraint(port,type="weight_sum",min=0.99, max=1.01)
#rportfolios <- random_portfolios(port, permutations = 500, rp_method = "sample", eliminate = TRUE)
#OPTIMIZATION SETUP
minreturnLimit <- min(colMeans(returns.data))
maxreturnLimit <- max(colMeans(returns.data))
minret <- minreturnLimit
maxret <- maxreturnLimit
vec <- seq(minret, maxret, length.out = 100)
eff.frontier <- data.frame(Risk = rep(NA, length(vec)), Return = rep(NA, length(vec)))
frontier.weights <- mat.or.vec(nr = length(vec), nc = ncol(returns.data))
colnames(frontier.weights) <- colnames(returns.data)
#GENERATE EFFICIENT FRONTIER
#In add.constraint...the type is return, as in, it is targeting a specific return specified by vec
#Subsequently, it looks for the portfolio that minimizes StdDev for that return constraint...this is the objective
for(i in 1:length(vec)){
eff.port <- add.constraint(port, type = "return", name = "mean", return_target = vec[i])
eff.port <- add.objective(eff.port, type = "risk", name = "var")
# eff.port <- add.objective(eff.port, type = "weight_concentration", name = "HHI",
# conc_aversion = 0.001)
eff.port <- optimize.portfolio(returns.data, eff.port, optimize_method = "ROI")
eff.frontier$Risk[i] <- sqrt(t(eff.port$weights) %*% covMat %*% eff.port$weights)
eff.frontier$Return[i] <- eff.port$weights %*% meanReturns
eff.frontier$Sharperatio[i] <- eff.port$Return[i] / eff.port$Risk[i]
frontier.weights[i,] = eff.port$weights
print(paste(round(i/length(vec) * 100, 0), "% done..."))
}
#PLOT EFFICIENT FRONTIER
ggplot(eff.frontier, aes(x=eff.frontier$Risk, y=eff.frontier$Return)) + geom_point(shape = 18, color = "limegreen", size = 2) + ggtitle("Portfolio Optimization") + labs(x="Risk",y="Return")
eff.frontier$Sharpe <- eff.frontier$Return / eff.frontier$Risk
答案 0 :(得分:1)
我弄清楚为什么我的优化不起作用 - 我的数据集包含一个无法解决的排名不足的矩阵(列数多于行数)。