Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/R/extractrisk.R
1433 views
1
###############################################################################
2
# R (https://r-project.org/) Numeric Methods for Optimization of Portfolios
3
#
4
# Copyright (c) 2022-2032 Xinran Zhao
5
#
6
# This library is distributed under the terms of the GNU Public License (GPL)
7
# for full details see the file COPYING
8
#
9
# $Id$
10
#
11
###############################################################################
12
13
14
#' extract the risk value when knowing the weights
15
#' @param R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
16
#' @param w the weight of the portfolio
17
#' @param ES_alpha the default value is 0.05, but could be specified as any value between 0 and 1
18
#' @param CSM_alpha the default value is 0.05, but could be specified as any value between 0 and 1
19
#' @param moment_setting the default is NULL, should provide moment_setting=list(mu=, sigma=) if customize momentFUN
20
#' @export extract_risk
21
extract_risk <- function(R, w, ES_alpha = 0.05, CSM_alpha = 0.05, moment_setting = NULL){
22
res = list()
23
if(is.null(moment_setting$mu)) res$mean = mean(R %*% w) else res$mean = moment_setting$mu %*% w
24
if(is.null(moment_setting$sigma)) res$StdDev = sqrt(t(w) %*% cov(R) %*% w) else res$StdDev = sqrt(t(w) %*% moment_setting$sigma %*% w)
25
26
if(ES_alpha > 0.5) ES_alpha <- (1 - ES_alpha)
27
if(CSM_alpha > 0.5) CSM_alpha <- (1 - CSM_alpha)
28
29
# ES/CSM by CVXR
30
T <- dim(R)[1]
31
X <- as.matrix(R)
32
zeta <- CVXR::Variable(1)
33
z <- CVXR::Variable(T)
34
35
## ES
36
obj_es <- zeta + (1/(T*ES_alpha)) * sum(z)
37
con_es <- list(z >= 0, z >= -X %*% w - zeta)
38
p_es <- CVXR::Problem(CVXR::Minimize(obj_es), constraints = con_es)
39
res_es = CVXR::solve(p_es, solver = "ECOS")
40
res$ES = res_es$value
41
42
## CSM
43
obj_CSM <- zeta + (1/CSM_alpha) * CVXR::p_norm(z, p=2)
44
con_CSM = list(z >= 0, z >= -X %*% w - zeta)
45
p_CSM <- CVXR::Problem(CVXR::Minimize(obj_CSM), constraints = con_CSM)
46
res_CSM = CVXR::solve(p_CSM, solver = "ECOS")
47
res$CSM = res_CSM$value
48
49
res
50
}
51
52
53