1#' Calculates turnover given two vectors of weights.2#' This is used as an objective function and is called when the user adds an objective of type turnover with \code{\link{add.objective}}3#' @param weights vector of weights from optimization4#' @param wts.init vector of initial weights used to calculate turnover from5#' @author Ross Bennett6#' @export7turnover <- function(weights, wts.init=NULL) {8# turnover function from https://r-forge.r-project.org/scm/viewvc.php/pkg/PortfolioAnalytics/sandbox/script.workshop2012.R?view=markup&root=returnanalytics910N <- length(weights)1112# If wts.init is not given, then assume a vector of equal weights13if(is.null(wts.init)) {14wts.init <- rep(1/N, N)15}1617# Check that weights and wts.init are the same length18if(length(weights) != length(wts.init)) stop("weights and wts.init are not the same length")1920return(sum(abs(wts.init - weights)) / N)21}2223#' Calculate portfolio variance24#'25#' This function is used to calculate the portfolio variance via a call to26#' constrained_objective when var is an object for mean variance or quadratic27#' utility optimization.28#'29#' @param R xts object of asset returns30#' @param weights vector of asset weights31#' @return numeric value of the portfolio variance32#' @author Ross Bennett33#' @export34var.portfolio <- function(R, weights){35weights <- matrix(weights, ncol=1)36return(as.numeric(t(weights) %*% var(R) %*% weights))37}3839#' Concentration of weights40#'41#' This function computes the concentration of weights using the Herfindahl Hirschman Index42#'43#' @param weights set of portfolio weights44#' @param groups list of vectors of grouping45#' @author Ross Bennett46#' @export47HHI <- function(weights, groups=NULL){4849# calculate overall HHI50hhi <- sum(weights^2)5152# calculate group HHI53if(!is.null(groups)){54ngroups <- length(groups)55group_hhi <- rep(0, ngroups)56if(!is.null((names(groups)))) names(group_hhi) <- names(groups)57for(i in 1:ngroups){58group_hhi[i] <- sum(weights[groups[[i]]]^2)59}60return(list(HHI=hhi, Groups_HHI=group_hhi))61} else {62return(hhi)63}64}6566# portfolio mean return67port.mean <- function(weights, mu){68# t(weights) %*% moments$mu69as.numeric(crossprod(weights, mu))70}7172###############################################################################73# R (https://r-project.org/) Numeric Methods for Optimization of Portfolios74#75# Copyright (c) 2004-2021 Brian G. Peterson, Peter Carl, Ross Bennett, Kris Boudt76#77# This library is distributed under the terms of the GNU Public License (GPL)78# for full details see the file COPYING79#80# $Id$81#82###############################################################################838485