# Analyze Stock Price Data Using R, Part3

## Master R

When analyzing stock returns, we like to know if the average returns or volatilities are constant over time, or if the correlations between any two assets in our portfolio stay constant over time. Therefore, we need to pick a time windows and calculate the rolling means, volatilities or correlations. A common choice for a time window is 2 years. However, in practice, I often pick several time windows of different length (like 6 months, 1 year, 2 years, 5 years) and compare the results obtained under each time window. The function rollapply() in the zoo library allows us to calculate the rolling statistics easily.

Step 2. Download the monthly adjusted closing price data on VGENX and VTSMX since Sept 2005 from Yahoo.

Step 3. Change the class of the time index to yearmon.

Step 4. Merge both price series into one data frame and Calculate continuously compounded returns.

Step 5. Calculate and Chart the rolling mean of the cc returns.

Note that neither security has a constant monthly cc return.

Step 6. Calculate and Chart the rolling mean of the volatilities.

We see the volatilities of both securities are changing over time too.

Step 7. Calculate and Chart the rolling correlation between the two return series.

We see the correlations between the returns of VTSMX (all stocks) and VGENX (energy stocks) are NOT constant overtime. Between 2006 and 2007, their correlation is small, and sometimes is even close to zero, but during the financial crisis of 2007 - 2011, they are highly correlated. You’ll see this a lot in other pairs of securities. In general, assets are not correlated during normal time will become highly correlated during crisis. As my old finance professor liked to say, “Diversification helps except when the world is on fire. And some day, the world will be on fire.”