<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/introduction-to-volatility/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rviews.rstudio.com/2017/07/12/introduction-to-volatility/"> R Views</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p> <br>
</p>
<p><br>
</p>
<p>This is the beginning of a series on portfolio volatility, variance, and standard deviation. I realize that it’s a lot more fun to <strong>fantasize about</strong> analyzing stock returns, which is why television shows and websites constantly update the daily market returns and give them snazzy green and red colors. But good ol’ volatility is quite important in its own right, especially to finance geeks, aspiring finance geeks, and institutional investors. If you are, might become, or might ever work with/for any of those, this series should at least serve as a jumping-off point.</p>
<p>Briefly, our volatility project will proceed as follows:</p>
<div>
<h3>Part 1</h3>
<ol>
<li>
<p>Portfolio Volatility Intro: by-hand, matrix algebra, built-in and compare to SPY</p>
</li>
<li>
<p>Visualizing Volatility Intro: chart portfolio sd over time – will have to roll apply</p>
</li>
<li>
<p>Shiny app to test different portfolios</p>
</li>
</ol>
</div>
<div>
<h3>Part 2</h3>
<ol>
<li>
<p>Asset Contributions to Volatility: by-hand, matrix algebra, built-in and visualize snapshot with bar graph</p>
</li>
<li>
<p>Chart contributions over time: flag any asset that surpasses a threshold</p>
</li>
<li>
<p>Shiny app to test different portfolios</p>
</li>
</ol>
</div>
<div>
<h3>Part 3</h3>
<ol>
<li>
<p>Minimum Variance Portfolio: find minimum variance portfolio weights</p>
</li>
<li>
<p>Shiny app to test different portfolios</p>
</li>
</ol>
<p>A quick word of warning: this series begins at the beginning with portfolio standard deviation, builds up to a more compelling data visualization in the next post, and finally a nice Shiny app after that. R users with experience in the world of volatility may wish to skip this post and wait for the visualizations in the next one. That said, I would humbly offer a couple of benefits to the R code that awaits us.</p>
<p>First, volatility is important, possibly more important than returns. I don’t think any investment professional looks back on hours spent pondering volatility as a waste of time. Plus, today we’ll look at a new way to convert daily prices to monthly using the <code>tidyquant</code> package, and that might offer enough new substance.</p>
<p>Second, as always, we have an eye on making our work reproducible and reusable. This Notebook makes it exceedingly clear how we derive our final data visualizations on portfolio volatility. It’s a good template for other visualization derivations, even if standard deviation is old hat for you.</p>
<p>Okay, without further ado, here’s where we are headed today:</p>
<ol>
<li>
<p>Import prices and calculate returns for 5 assets and construct a portfolio.</p>
</li>
<li>Calculate the standard deviation of monthly portfolio returns using three methods:</li>
</ol>
<ul>
<li>the old-fashioned equation
</li>
<li>matrix algebra
</li>
<li>a built-in function from <code>performanceAnalytics</code></li>
</ul>
<ol start="3">
<li>Compare those to the standard deviation of monthly SPY returns.</li>
</ol>
<p>On to step 1, wherein we import prices and calculate returns for the 5 ETFs to be used in our portfolio. Those are AGG (a US bond fund), DBC (a commodities fund), EFA (a non-US equities fund), SPY (an S&amp;P500 ETF), VGT (a technology fund).</p>
<p>Let’s import prices and save them to an <code>xts</code> object.</p>
<pre><code># A vector of symbol for our ETFs.
symbols &lt;- sort(c(&quot;SPY&quot;,&quot;VGT&quot;,&quot;EFA&quot;,&quot;DBC&quot;,&quot;AGG&quot;))

# Pipe them to getSymbols, extract the closing prices, and merge to one xts object. 
# Take a look at result before moving on to calculate the returns.
# Notice that we are only grabbing prices from 2013 to present, but that is 
# only to keep the loading time shorter for the post. 
prices &lt;- 
  getSymbols(symbols, src = 'google', from = &quot;2013-01-01&quot;, 
             auto.assign = TRUE, warnings = FALSE) %>% 
  map(~Cl(get(.))) %>%
  reduce(merge) %>% 
  `colnames&lt;-`(symbols)</code></pre>
<p>Next we want to turn those daily prices into monthly returns. We will pipe the <code>prices</code> object to the <code>tq_transmute()</code> function from the <a rel="nofollow" href="https://cran.r-project.org/web/packages/tidyquant/index.html" target="_blank">tidyquant</a> package, but we can’t do that directly. First we need to transform our <code>xts</code> object to a <code>tibble</code> using a call to <code>as_tibble(preserve_row_names = TRUE)</code> from <code>tidyquant</code>. There’s probably a more efficient way to set this up (check out the tidyquant <a rel="nofollow" href="http://www.business-science.io/blog/index.html" target="_blank">articles</a> to learn more) than this whole piped construct, but I derive a certain pleasure from toggling between <code>tibble</code> and <code>xts</code> objects.</p>
<pre><code># We are going to make heavy use of the tidyquant package to get monthly returns.
portfolio_component_monthly_returns_xts &lt;- 
  prices %>%  
  # Convert to tibble so can stay in the tidyquant/verse.
  as_tibble(preserve_row_names = TRUE) %>%
  # Add a date column. 
  mutate(date = ymd(row.names)) %>% 
  # Remove the row.names column; it's not needed anymore.
  select(-row.names) %>% 
  # I like to have the date column as the first column. 
  select(date, everything()) %>% 
  # We need to gather into long format in order to use tq_transmute().
  gather(asset, return, -date) %>%
  group_by(asset) %>% 
  # Use the function from tidyquant; note how easily we could change to
  # a different time period like weekly or yearly.
  tq_transmute(mutate_fun = periodReturn, period = &quot;monthly&quot;) %>%
  # Put the results back to wide format.
  spread(asset, monthly.returns) %>% 
  # Convert back to an xts, so we can use the cov() and StdDev() functions.
  as_xts(date_col = date)

head(portfolio_component_monthly_returns_xts)</code></pre>
<pre><code>##                      AGG          DBC         EFA         SPY          VGT
## 2013-01-31 -0.0050473186  0.021162123  0.02147558  0.02492127 -0.008422235
## 2013-02-28  0.0039858683 -0.047067088 -0.01288572  0.01275885  0.005237826
## 2013-03-28 -0.0009022828  0.006634722  0.01305393  0.03337511  0.026615970
## 2013-04-30  0.0073150908 -0.038081289  0.05018650  0.01921236  0.005349794
## 2013-05-31 -0.0217859064 -0.015607156 -0.03019051  0.02354709  0.042434166
## 2013-06-28 -0.0174136193 -0.028228925 -0.04611287 -0.01847773 -0.031675393</code></pre>
<p>Take a quick look at the monthly returns above, to make sure things appear to be in order.</p>
<p>Now, on to constructing a portfolio and calculating volatility. To turn these five ETFs into a portfolio, we need to assign them weights. Let’s first create a weights vector.</p>
<pre><code>weights &lt;- c(0.10, 0.10, 0.15, 0.40, 0.15)</code></pre>
<p>Before we use the weights in our calculations, we perform a quick sanity check in the next code chunk. This might not be necessary with five assets as we have today, but it is good practice because if we had 50 assets, it could save us a lot of grief to catch a mistake early.</p>
<pre><code># Make sure the weights line up with assets.
asset_weights_sanity_check &lt;- tibble(weights, symbols)

asset_weights_sanity_check</code></pre>
<pre><code>## # A tibble: 5 x 2
##   weights symbols
##     </code></pre></div>