Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/R/opt.outputMvo.R
1433 views
1
#' @title Optimal Portfolio Weights and Performance Values
2
#'
3
#' @description Converts output of `optimize.portfolio` to a list of the
4
#' portfolio weights, mean, volatility and Sharpe Ratio.
5
#'
6
#' @param opt List output of `optimize.portfolio`
7
#' @param returns Multivariate xts object of portfolio assets returns
8
#' @param digits Integer number of significant digits with default NULL
9
#' @param annualize Logical with default TRUE
10
#' @param frequency Returns frequency: "monthly", "weekly" or "daily"
11
#' @param rf Numeric value with default 0.0
12
#'
13
#' @details This function uses the weights returned by optimize.portfolio,
14
#' along with the portfolio assets returns, and a risk-free rate, to
15
#' to compute the portfolio mean return, volatility, and Sharpe Ratio.
16
#'
17
#' @return A list containing the portfolio numeric weights, mean value,
18
#' volatility and Sharpe Ratio.
19
#'
20
#' @author R. Douglas Martin
21
#' @export
22
#'
23
#' @examples
24
#' args(opt.outputMvo)
25
opt.outputMvo <- function(opt, returns, digits = NULL, annualize = TRUE,
26
frequency = "monthly", rf = 0.0)
27
{
28
if(class(returns)[1] == "xts"){
29
returns <- coredata(returns)
30
}
31
Wgts <- opt$weights
32
sigmasq <- as.numeric(t(Wgts) %*% var(returns) %*% Wgts)
33
StdDev <- sqrt(sigmasq)
34
mu.ret <- apply(returns, 2, mean)
35
Mean <- as.numeric(t(Wgts) %*% mu.ret)
36
SR <- (Mean - rf)/StdDev
37
a <- 1; b <- 1
38
if(annualize){
39
if(frequency == "monthly"){
40
a <- 12; b <- sqrt(12)
41
} else if(frequency == "weekly"){
42
a <- 52; b <- sqrt(52)
43
} else {
44
a <- 260; b <- sqrt(260)
45
}
46
}
47
Mean <- a*Mean
48
StdDev <- b*StdDev
49
SR <- b*SR
50
51
output <- list(Wgts = Wgts, Mean = Mean, StdDev = StdDev, SR = SR)
52
if (!is.null(digits)) {
53
output <- lapply(output, round, digits)
54
}
55
output
56
}
57
58
59
###############################################################################
60
# R (https://r-project.org/) Numeric Methods for Optimization of Portfolios
61
#
62
# Copyright (c) 2004-2023 R. Douglas Martin
63
#
64
# This library is distributed under the terms of the GNU Public License (GPL)
65
# for full details see the file COPYING
66
#
67
# $Id$
68
#
69
###############################################################################
70