Skip to content

Calculating Portfolio Standard deviation

2 messages · Amelia Vettori, Joshua Wiley

#
Dear Amelia,

I find it hard to believe I'm not reinventing the wheel here, but
here's a little function.  If no weights are specified it uses all 1s.

## Define function
lvar <- function(x, weights, na.rm = TRUE) {
  if (missing(weights)) {
    weights <- rep(1, ncol(x))
  }

  covmat <- var(x = x, na.rm = na.rm)
  utc <- upper.tri(covmat)
  wt.var <- sum(diag(covmat) * weights^2)
  wt.cov <- sum(weights[row(covmat)[utc]] *
                weights[col(covmat)[utc]] *
                covmat[utc])
  variance <- wt.var + 2 * wt.cov
  return(variance)
}

## example with weights
lvar(x = prices_df, weights = c(0.10, 0.25, 0.20, 0.45))

HTH,

Josh

On Mon, Jan 10, 2011 at 3:14 AM, Amelia Vettori
<amelia_vettori at yahoo.co.nz> wrote:
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/