Get startedGet started for free

Define a custom moment function

In many cases for constrained optimization problems, the portfolio manager or analyst may want to estimate moments for a specific technique and/or further extend the idea of set.portfolio.moments(). A user defined custom moment function can have any arbitrary named arguments. However, arguments named R for the asset returns and portfolio for the portfolio object will be detected automatically and handled in an efficient manner. Because of this, it is strongly encouraged to use R for the asset returns object and portfolio for the portfolio object.

The custom moment function should return a named list where the elements represent the moments:

  • $mu: first moment (expected returns vector)
  • $sigma: second moment (variance-covariance matrix)
  • $m3: third moment (coskewness matrix)
  • $m4: fourth moment (cokurtosis matrix)

In this exercise, you will write a custom moment function to estimate the variance-covariance matrix using a robust method. We will use the cov.rob() function from the MASS package. The function signature should have arguments named R for the asset returns and portfolio for the specification object. The function should return a named list. Because you are only estimating the second moment, you only need to return a list with one element appropriately named. You can apply these rules to write custom moment functions for other models such as factor models, GARCH models, or any other class of models that theoretically should be a better estimate than the sample estimate.

This exercise is part of the course

Intermediate Portfolio Analysis in R

View Course

Exercise instructions

  • Define a function named moments_robust that estimates the variance-covariance matrix of the asset returns using the "mcd" method.
  • Estimate the portfolio moments you just defined. Assign it to a variable named moments. You are doing this as a check to ensure that your custom moment function is working as expected.
  • Compute the variance-covariance matrix directly using cov.rob() and check if it is equal to moments$sigma

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Define custom moment function
moments_robust <- function(R, portfolio){
  out <- list()
  out$___ <- cov.rob(R, method = ___)$cov
  out
}

# Estimate the portfolio moments using the function you just defined 
moments <- moments_robust(R = ___, portfolio = ___)

# Check the moment estimate
cov.rob(___, method = ___)$cov == moments$___
Edit and Run Code