Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/R/equal.weight.R
1433 views
1
2
3
#' Create an equal weight 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 equal 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 Ross Bennett
18
#' @export
19
equal.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
max_sum <- get_constraints(portfolio)$max_sum
24
25
# get asset information for equal weight portfolio
26
assets <- portfolio$assets
27
nassets <- length(assets)
28
weights <- rep(max_sum / nassets, nassets)
29
names(weights) <- names(assets)
30
31
# make sure the number of columns in R matches the number of assets
32
if(ncol(R) != nassets){
33
if(ncol(R) > nassets){
34
R <- R[, 1:nassets]
35
warning("number of assets is less than number of columns in returns object, subsetting returns object.")
36
} else {
37
stop("number of assets is greater than number of columns in returns object")
38
}
39
}
40
41
tmpout <- constrained_objective(w=weights, R=R, portfolio=portfolio, trace=TRUE, ...)
42
return(structure(list(
43
R=R,
44
weights=weights,
45
out=tmpout$out,
46
objective_measures=tmpout$objective_measures,
47
call=match.call(),
48
portfolio=portfolio),
49
class=c("optimize.portfolio.eqwt", "optimize.portfolio"))
50
)
51
}
52
53
54
###############################################################################
55
# R (https://r-project.org/) Numeric Methods for Optimization of Portfolios
56
#
57
# Copyright (c) 2004-2021 Brian G. Peterson, Peter Carl, Ross Bennett, Kris Boudt
58
#
59
# This library is distributed under the terms of the GNU Public License (GPL)
60
# for full details see the file COPYING
61
#
62
# $Id$
63
#
64
###############################################################################
65
66