Get startedGet started for free

Computing the efficient frontier using a grid of target returns

As you have seen, one approach to compute the efficient frontier is to first define the grid of target returns and then, for each target return, find the portfolio that has an expected return equal to the target return at the lowest possible variance.

But what is a reasonable grid of target returns? You will set the maximum target return to the maximum average return of the stocks. Ideally, you would set the minimum target return to the return of the minimum variance portfolio. Because you don't know this minimum variance portfolio return yet, you create a grid using the minimum of average returns from all stocks.

In this exercise, you will use a for loop to calculate your grid of potential portfolio means, deviations, and weights.

This exercise is part of the course

Introduction to Portfolio Analysis in R

View Course

Exercise instructions

  • Calculate the column means of returns (using colMeans()), and call this stockmu.
  • Create a sequence (seq()) of length 50, which begins at a risk-free rate of 1% and ends at the maximum value of stockmu called grid.
  • Initialize two empty vectors with the same length as grid using rep(), where you will store the portfolio means and standard deviations. Call these vpm and vpsd.
  • Initialize an empty matrix of 50 rows and 30 columns. Call this mweights. You can use the matrix() function to do so.
  • Create a for loop that starts on the first value of grid and ends on the last. The for-loop should create a portfolio called opt using returns and with a target return of grid.
  • With each iteration, the for loop should fill the vectors vpm ($pm), vpsd ($ps) with their respective values from opt.
  • Store the portfolio weights line by line in mweights ($pw).

Hands-on interactive exercise

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

# Calculate each stocks mean returns


# Create a grid of target values
grid <- seq(from = ___, to = ___, length.out = ___)

# Create empty vectors to store means and deviations
vpm <- vpsd <- 

# Create an empty matrix to store weights
mweights <- matrix(NA, 50, 30)

# Create your for loop
for(i in 1:length(grid)) {
  opt <- portfolio.optim(x = ___, pm = ___[i])
  vpm[i] <- ___$__
  vpsd[i] <- ___$__
  mweights[i, ] <- ___$__
}
Edit and Run Code