Get Started

Finding the mean-variance efficient portfolio

A mean-variance efficient portfolio can be obtained as the solution of minimizing the portfolio variance under the constraint that the portfolio expected return equals a target return. A convenient R function for doing so is the function portfolio.optim() in the R package tseries. Its default implementation finds the mean-variance efficient portfolio weights under the constraint that the portfolio return equals the return on the equally-weighted portfolio. The only argument needed is the monthly return data on the portfolio components for which the weights need to be determined.

The variable returns containing the monthly returns of the DJIA stocks is already loaded in the console.

This is a part of the course

“Introduction to Portfolio Analysis in R”

View Course

Exercise instructions

  • Load the library tseries.
  • Create a mean-variance efficient portfolio of monthly returns using the default of portfolio.optim() targeting the equally-weighted portfolio return, and assign the output to the variable opt.
  • Create a vector of weights from your optimized portfolio. Portfolio weights can be found in opt$pw. Call this pf_weights.
  • Assign the names to the assets using the provided code.
  • Select the optimum weights from pf_weights that are greater than or equal to 1%, call this opt_weights.
  • Use barplot() to visualize the distribution of opt_weights.
  • Print the expect portfolio return (opt$pm) and volatility (opt$ps) of the optimized portfolio.

Hands-on interactive exercise

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

# Load tseries


# Create an optimized portfolio of returns
opt <- portfolio.optim(___)

# Create pf_weights
pf_weights <- ___$pw

# Assign asset names
names(pf_weights) <- colnames(returns)

# Select optimum weights opt_weights
opt_weights <- pf_weights[___ >= 0.01]

# Bar plot of opt_weights


# Print expected portfolio return and volatility
___$pm
___$ps
 
Edit and Run Code