###############################################################################1# R (https://r-project.org/) Numeric Methods for Optimization of Portfolios2#3# Copyright (c) 2022-2032 Xinran Zhao4#5# This library is distributed under the terms of the GNU Public License (GPL)6# for full details see the file COPYING7#8# $Id$9#10###############################################################################111213#' extract the risk value when knowing the weights14#' @param R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns15#' @param w the weight of the portfolio16#' @param ES_alpha the default value is 0.05, but could be specified as any value between 0 and 117#' @param CSM_alpha the default value is 0.05, but could be specified as any value between 0 and 118#' @param moment_setting the default is NULL, should provide moment_setting=list(mu=, sigma=) if customize momentFUN19#' @export extract_risk20extract_risk <- function(R, w, ES_alpha = 0.05, CSM_alpha = 0.05, moment_setting = NULL){21res = list()22if(is.null(moment_setting$mu)) res$mean = mean(R %*% w) else res$mean = moment_setting$mu %*% w23if(is.null(moment_setting$sigma)) res$StdDev = sqrt(t(w) %*% cov(R) %*% w) else res$StdDev = sqrt(t(w) %*% moment_setting$sigma %*% w)2425if(ES_alpha > 0.5) ES_alpha <- (1 - ES_alpha)26if(CSM_alpha > 0.5) CSM_alpha <- (1 - CSM_alpha)2728# ES/CSM by CVXR29T <- dim(R)[1]30X <- as.matrix(R)31zeta <- CVXR::Variable(1)32z <- CVXR::Variable(T)3334## ES35obj_es <- zeta + (1/(T*ES_alpha)) * sum(z)36con_es <- list(z >= 0, z >= -X %*% w - zeta)37p_es <- CVXR::Problem(CVXR::Minimize(obj_es), constraints = con_es)38res_es = CVXR::solve(p_es, solver = "ECOS")39res$ES = res_es$value4041## CSM42obj_CSM <- zeta + (1/CSM_alpha) * CVXR::p_norm(z, p=2)43con_CSM = list(z >= 0, z >= -X %*% w - zeta)44p_CSM <- CVXR::Problem(CVXR::Minimize(obj_CSM), constraints = con_CSM)45res_CSM = CVXR::solve(p_CSM, solver = "ECOS")46res$CSM = res_CSM$value4748res49}50515253