Get Started

Rolling annualized mean and volatility

In previous exercises, you have already familiarized yourself with the Return.annualized() and StdDev.annualized() functions. In this exercise, you will also use the function SharpeRatio.annualized() to calculate the annualized Sharpe Ratio. This function takes the arguments R, and Rf. The R argument takes an xts, vector, matrix, data.frame, timeSeries, or zoo object of asset returns. The Rf argument is necessary in SharpeRatio.annualized(), as it takes into account the risk-free rate in the same period of your returns. For this example, you can use the object rf to fulfill the Rf argument.

The function chart.RollingPerformance() makes it easy to visualize the rolling estimates of performance in R. Familiarize yourself first with the syntax of this function. It requires you to specify the time series of portfolio returns (by setting the argument R), the length of the window (width), and the function used to compute the performance (argument FUN). To see all three plots together, PerformanceAnalytics provides a shortcut function charts.RollingPerformance(). Note the charts instead of chart. This function creates all of the previous charts at once and does not use the argument FUN!

This is a part of the course

“Introduction to Portfolio Analysis in R”

View Course

Exercise instructions

  • Calculate the annualized returns, volatility, and Sharpe Ratio for sp500_returns. Assign these values to returns_ann, sd_ann, and sharpe_ann respectively. Remember to supply the risk-free rate to the Rf argument when calculating the Sharpe Ratio.
  • We provided the code for a plot of a rolling 12-month estimate of the annualized mean. Use this to help with the other plots!
  • Plot the rolling 12-month estimates of the annualized volatility of the S&P 500 returns.
  • Plot the rolling 12-month estimates of the annualized Sharpe ratio of the S&P 500 returns.

Hands-on interactive exercise

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

# Calculate the mean, volatility, and Sharpe ratio of sp500_returns
returns_ann <- ___
sd_ann <- ___
sharpe_ann <- ___

# Plotting the 12-month rolling annualized mean
chart.RollingPerformance(R = sp500_returns, width = 12, FUN = "Return.annualized")

# Plotting the 12-month rolling annualized standard deviation
___

# Plotting the 12-month rolling annualized Sharpe ratio
___
Edit and Run Code