# R语言玩转资产组合计算

 This post was kindly contributed by 数据科学与R语言 - go there to comment and to read the full post.

`library(quadprog)library(fPortfolio)data <- SMALLCAP.RET[, c("BKE", "GG", "GYMB", "KRON")]# 计算得到收益率数据的协方差矩阵和期望sigma <- covEstimator(data)\$Sigmamu <- covEstimator(data)\$mu# 计算给定期望收益率为0.03条件下的最优组合，且不可作空A <- cbind(rep(1, 4), mu,diag(rep(1, 4))) #约束系数D <- sigma # 协方差矩阵x <- mu # 期望收益b <- c(1, 0.03, 0,0,0,0) #约束的右侧值res <- solve.QP(2 * D, x, A, b, meq=2)round(res\$solution,2)`

`# 设定组合的期望收益率为0.03spec <- portfolioSpec(portfolio=list                       (targetReturn=0.03))# 设定组合的约束不许做空cons <- 'LongOnly'# 求解res <- efficientPortfolio(data, spec = spec,                           constraints = cons)summary(res)`

`# 设定计算出前沿上的100个最优组合，无风险资产收益率为0.01spec <- portfolioSpec(portfolio=list                       (nFrontierPoints = 100,                        riskFreeRate=0.01))# 计算有效前沿，并不许做空frontier <- portfolioFrontier(data,spec=spec,                             constraints = cons)# 有效前沿绘图frontierPlot(frontier,              pch = 19,             cex = 0.5,             xlim=c(0,0.25),             ylim=c(0,0.035))grid()abline(h = 0, col = "grey30")abline(v = 0, col = "grey30")minvariancePoints(frontier, pch = 19, col = "red")tangencyPoints(frontier, pch = 19, col = "blue")tangencyLines(frontier, col = "darkblue",lwd=3)singleAssetPoints(frontier, pch = 19, cex = 1.5, col = topo.colors(6))front <- frontierPoints(frontier)monteCarloPoints(frontier, mcSteps = 500, pch = 19,cex = 0.3)lines(front, col = "red4", lwd = 3)`