Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/R/inverse.volatility.weight.R
1433 views
1
2
3
#' Create an inverse volatility weighted portfolio
4
#'
5
#' This function calculates objective measures for an equal weight portfolio.
6
#'
7
#' @details
8
#' This function is simply a wrapper around \code{\link{constrained_objective}}
9
#' to calculate the objective measures in the given \code{portfolio} object of
10
#' an inverse volatility weight portfolio. The portfolio object should include all objectives
11
#' to be calculated.
12
#'
13
#' @param R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
14
#' @param portfolio an object of type "portfolio" specifying the constraints and objectives for the optimization
15
#' @param \dots any other passthru parameters to \code{constrained_objective}
16
#' @return a list containing the returns, weights, objective measures, call, and portfolio object
17
#' @author Peter Carl
18
#' @export
19
inverse.volatility.weight <- function(R, portfolio, ...){
20
# Check for portfolio object passed in
21
if(!is.portfolio(portfolio)) stop("portfolio object passed in must be of class 'portfolio'")
22
23
# get asset information for equal weight portfolio
24
assets <- portfolio$assets
25
nassets <- length(assets)
26
27
# make sure the number of columns in R matches the number of assets
28
if(ncol(R) != nassets){
29
if(ncol(R) > nassets){
30
R <- R[, 1:nassets]
31
warning("number of assets is less than number of columns in returns object, subsetting returns object.")
32
} else {
33
stop("number of assets is greater than number of columns in returns object")
34
}
35
}
36
37
# Here, max_sum will be 1.0 if not explicitly set by caller
38
max_sum <- get_constraints(portfolio)$max_sum
39
40
invVol <- 1 / StdDev(R)
41
weights <- max_sum * as.vector(invVol / sum(invVol))
42
names(weights) <- names(assets)
43
44
tmpout <- constrained_objective(w=weights, R=R, portfolio=portfolio, trace=TRUE, ...)
45
return(structure(list(
46
R=R,
47
weights=weights,
48
out=tmpout$out,
49
objective_measures=tmpout$objective_measures,
50
call=match.call(),
51
portfolio=portfolio),
52
class=c("optimize.portfolio.invol", "optimize.portfolio"))
53
)
54
}
55
56
57
###############################################################################
58
# R (https://r-project.org/) Numeric Methods for Optimization of Portfolios
59
#
60
# Copyright (c) 2004-2021 Brian G. Peterson, Peter Carl, Ross Bennett, Kris Boudt
61
#
62
# This library is distributed under the terms of the GNU Public License (GPL)
63
# for full details see the file COPYING
64
#
65
# $Id$
66
#
67
###############################################################################
68
69