<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/visualizing-the-capital-asset-pricing-model/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rviews.rstudio.com/2018/03/02/capm-and-visualization/"> R Views</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p> <br>
<br>


<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>



</p>
<p>In a <a rel="nofollow" href="https://rviews.rstudio.com/2018/02/08/capm-beta/" target="_blank">previous post</a>, we covered how to calculate CAPM beta for our usual portfolio consisting of:</p>
<pre><code>+ SPY (S&amp;P500 fund) weighted 25%
+ EFA (a non-US equities fund) weighted 25%
+ IJS (a small-cap value fund) weighted 20%
+ EEM (an emerging-mkts fund) weighted 20%
+ AGG (a bond fund) weighted 10%</code></pre>
<p>Today, we will move on to visualizing the CAPM beta and explore some <code>ggplot</code> and <code>highcharter</code> functionality, along with the <code>broom</code> package.</p>
<p>Before we can do any of this CAPM work, we need to calculate the portfolio returns, covered in <a rel="nofollow" href="https://rviews.rstudio.com/2017/10/11/from-asset-to-portfolio-returns/" target="_blank">this post</a>, and then calculate the CAPM beta for the portfolio and the individual assets covered in <a rel="nofollow" href="https://rviews.rstudio.com/2018/02/08/capm-beta/" target="_blank">this post</a>.</p>
<p>I will not present that code or logic again but we will utilize four data objects from that previous work:</p>
<pre><code>+ portfolio_returns_tq_rebalanced_monthly (a tibble of portfolio monthly returns)
+ market_returns_tidy (a tibble of SP500 monthly returns)
+ beta_dplyr_byhand (a tibble of market betas for our 5 individual assets)
+ asset_returns_long (a tibble of returns for our 5 individual assets)</code></pre>
<p>Let’s get to it.</p>
<div>
<h3>Visualizing the Relationship between Portfolio Returns, Risk and Market Returns</h3>
<p>The CAPM beta number is telling us about the linear relationship between our portfolio returns and the market returns. It’s also telling us about the riskiness of our portfolio – how volatile the portfolio is relative to the market. Before we get to beta itself, let’s take a look at expected monthly returns of our assets scattered against monthly risk of our individual assets.</p>
<pre><code>library(tidyquant)
library(tidyverse)
library(timetk)
library(tibbletime)
library(scales)

# This theme_update will center your ggplot titles
theme_update(plot.title = element_text(hjust = 0.5))

asset_returns_long %>% 
  group_by(asset) %>% 
  summarise(expected_return = mean(returns),
            stand_dev = sd(returns)) %>% 
  ggplot(aes(x = stand_dev, y = expected_return, color = asset)) +
  geom_point(size = 2) +
  ylab(&quot;expected return&quot;) +
  xlab(&quot;standard deviation&quot;) +
  ggtitle(&quot;Expected Monthly Returns v. Risk&quot;) +
  scale_y_continuous(label = function(x){ paste0(x, &quot;%&quot;)}) </code></pre>
<p><img src="https://i2.wp.com/rviews.rstudio.com/post/2018-02-28-capm-and-visualization_files/figure-html/unnamed-chunk-1-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Where does our portfolio fit on this scatter plot? Let’s add it to the <code>ggplot()</code> flow with <code>geom_point(aes(x = sd(portfolio_returns_tq_rebalanced_monthly$returns), y = mean(portfolio_returns_tq_rebalanced_monthly$returns)), color = &quot;cornflowerblue&quot;, size = 3)</code>.</p>
<pre><code>asset_returns_long %>% 
  group_by(asset) %>% 
  summarise(expected_return = mean(returns),
            stand_dev = sd(returns)) %>% 
  ggplot(aes(x = stand_dev, y = expected_return, color = asset)) +
  geom_point(size = 2) +
  geom_point(aes(x = sd(portfolio_returns_tq_rebalanced_monthly$returns),  
                 y = mean(portfolio_returns_tq_rebalanced_monthly$returns)), 
             color = &quot;cornflowerblue&quot;, 
             size = 3) +
  geom_text(
            aes(x = sd(portfolio_returns_tq_rebalanced_monthly$returns) * 1.09, 
                y = mean(portfolio_returns_tq_rebalanced_monthly$returns), 
                label = &quot;portfolio&quot;)) +
  ylab(&quot;expected return&quot;) +
  xlab(&quot;standard deviation&quot;) +
  ggtitle(&quot;Expected Monthly Returns v. Risk&quot;) +
  scale_y_continuous(labels = function(x){ paste0(x, &quot;%&quot;)}) </code></pre>
<p><img src="https://i0.wp.com/rviews.rstudio.com/post/2018-02-28-capm-and-visualization_files/figure-html/unnamed-chunk-2-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Our portfolio return/risk looks all right, though the SP500 has a higher expected return for just a bit more risk. It’s been tough to beat the market the last five years. EEM and EFA have a higher risk and lower expected return (no rational investor wants that!) and IJS has a higher risk and a higher expected return (some rational investors do want that!).</p>
<p>In general, the scatter is providing some return-risk context for our portfolio. It’s not directly part of CAPM, but I like to start here to get in the return-risk mindset.</p>
<p>Next, let’s turn to CAPM more directly and visualize the relationship between our portfolio and the market with a scatter plot of market returns on the x-axis and portfolio returns on the y-axis. First, we will add the market returns to our portfolio tibble by calling <code>mutate(market_returns = market_returns_tidy$returns)</code>. Then, we set our x- and y-axis with <code>ggplot(aes(x = market_returns, y = returns))</code>.</p>
<pre><code>portfolio_returns_tq_rebalanced_monthly %>% 
  mutate(market_returns = market_returns_tidy$returns) %>% 
  ggplot(aes(x = market_returns, y = returns)) + 
  geom_point(color = &quot;cornflowerblue&quot;) +
  ylab(&quot;portfolio returns&quot;) +
  xlab(&quot;market returns&quot;) +
  ggtitle(&quot;Scatterplot of portfolio returns v. market returns&quot;)</code></pre>
<p><img src="https://i0.wp.com/rviews.rstudio.com/post/2018-02-28-capm-and-visualization_files/figure-html/unnamed-chunk-3-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>This scatter plot is communicating the same strong linear relationship as our numeric beta calculation from the previous post. We can add a simple regression line to it with <code>geom_smooth(method = &quot;lm&quot;, se = FALSE, color = &quot;green&quot;, size = .5)</code>.</p>
<pre><code>portfolio_returns_tq_rebalanced_monthly %>% 
  mutate(market_returns = market_returns_tidy$returns) %>% 
  ggplot(aes(x = market_returns, y = returns)) + 
  geom_point(color = &quot;cornflowerblue&quot;) +
  geom_smooth(method = &quot;lm&quot;, se = FALSE, color = &quot;green&quot;, size = .5) +
  ylab(&quot;portfolio returns&quot;) +
  xlab(&quot;market returns&quot;) + 
  ggtitle(&quot;Scatterplot with regression line&quot;)</code></pre>
<p><img src="https://i2.wp.com/rviews.rstudio.com/post/2018-02-28-capm-and-visualization_files/figure-html/unnamed-chunk-4-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>The green line is produced by the call to <code>geom_smooth(method = 'lm')</code>. Under the hood, <code>ggplot</code> fits a linear model of the relationship between market returns and portfolio returns. The slope of that green line is the CAPM beta that we calculated earlier. To confirm that we can add a line to the scatter that has a slope equal to our beta calculation and a y-intercept equal to what I labeled as alpha in the <code>beta_dplyr_byhand</code> object.</p>
<p>To add the line, we invoke <code>geom_abline(aes(intercept = beta_dplyr_byhand$estimate[1], slope = beta_dplyr_byhand$estimate[2]), color = &quot;purple&quot;)</code>.</p>
<pre><code>portfolio_returns_tq_rebalanced_monthly %>% 
  mutate(market_returns = market_returns_tidy$returns) %>% 
  ggplot(aes(x = market_returns, y = returns)) + 
  geom_point(color = &quot;cornflowerblue&quot;) +
  geom_abline(aes(
    intercept = beta_dplyr_byhand$estimate[1], 
    slope = beta_dplyr_byhand$estimate[2]), 
    color = &quot;purple&quot;,
    size = .5) +
  ylab(&quot;portfolio returns&quot;) +
  xlab(&quot;market returns&quot;) +
  ggtitle(&quot;Scatterplot with hand calculated slope&quot;)</code></pre>
<p><img src="https://i2.wp.com/rviews.rstudio.com/post/2018-02-28-capm-and-visualization_files/figure-html/unnamed-chunk-5-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>We can plot both lines simultaneously to confirm to ourselves that they are the same – they should be right on top of each other but the purple line, our manual <code>abline</code>, extends into infinity so, we should see it start where the green line ends.</p>
<pre><code>portfolio_returns_tq_rebalanced_monthly %>% 
  mutate(market_returns = market_returns_tidy$returns) %>% 
  ggplot(aes(x = market_returns, y = returns)) + 
  geom_point(color = &quot;cornflowerblue&quot;) +
  geom_abline(aes(
    intercept = beta_dplyr_byhand$estimate[1], 
    slope = beta_dplyr_byhand$estimate[2]), 
    color = &quot;purple&quot;, 
    size = .5) +
  geom_smooth(method = &quot;lm&quot;, se = FALSE, color = &quot;green&quot;, size = .5) +
  ylab(&quot;portfolio returns&quot;) +
  xlab(&quot;market returns&quot;) +
  ggtitle(&quot;Compare CAPM beta line to regression line&quot;)</code></pre>
<p><img src="https://i1.wp.com/rviews.rstudio.com/post/2018-02-28-capm-and-visualization_files/figure-html/unnamed-chunk-6-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>All right, that seems to visually confirm (or strongly support) that the fitted line calculated by <code>ggplot</code> and <code>geom_smooth()</code> has a slope equal to the beta we calculated ourselves. Why did we go through this exercise? Well, CAPM beta is a bit “jargony”. Since we need to map that jargon over to the world of linear modeling, it’s a useful practice to consider how jargon reduces to data science concepts. This isn’t a particularly complicated bit of jargon, but it’s good practice to get in the habit of reducing jargon.</p>
</div>
<div>
<h3>A Bit More on Linear Regression: Augmenting Our Data</h3>
<p>Before concluding our analysis of CAPM beta, let’s explore the <code>augment()</code> function from <code>broom</code> and how it helps to create a few more interesting visualizations.</p>
<p>The code chunk below starts with model results from <code>lm(returns ~ market_returns_tidy$returns...)</code>, which is regressing our portfolio returns on the market returns. We store the results in a list-column called called <code>model</code>. Next, we call <code>augment(model)</code> which will add predicted values to the original data set and return a tibble.</p>
<p>Those predicted values will be in the <code>.fitted</code> column. For some reason, the <code>date</code> column gets dropped. It’s nice to have this for visualizations so we will add it back in with <code>mutate(date = portfolio_returns_tq_rebalanced_monthly$date)</code>.</p>
<pre><code>library(broom)

portfolio_model_augmented &lt;- 
portfolio_returns_tq_rebalanced_monthly %>% 
  do(model = lm(returns ~ market_returns_tidy$returns, data = .))%>% 
  augment(model) %>% 
  mutate(date = portfolio_returns_tq_rebalanced_monthly$date)

head(portfolio_model_augmented)</code></pre>
<pre><code>##         returns market_returns_tidy.returns      .fitted     .se.fit
## 1 -0.0008696132                  0.01267837  0.008294282 0.001431288
## 2  0.0186624378                  0.03726809  0.030451319 0.001984645
## 3  0.0206248830                  0.01903021  0.014017731 0.001485410
## 4 -0.0053529692                  0.02333503  0.017896670 0.001563417
## 5 -0.0229487590                 -0.01343411 -0.015234859 0.001953853
## 6  0.0411705787                  0.05038580  0.042271276 0.002521506
##         .resid       .hat     .sigma     .cooksd .std.resid       date
## 1 -0.009163896 0.01698211 0.01101184 0.006116973 -0.8415272 2013-02-28
## 2 -0.011788881 0.03265148 0.01096452 0.020099701 -1.0913142 2013-03-28
## 3  0.006607152 0.01829069 0.01104500 0.003434000  0.6071438 2013-04-30
## 4 -0.023249640 0.02026222 0.01062704 0.047294116 -2.1386022 2013-05-31
## 5 -0.007713900 0.03164618 0.01103127 0.008323550 -0.7137165 2013-06-28
## 6 -0.001100697 0.05270569 0.01107986 0.000294938 -0.1029661 2013-07-31</code></pre>
<p>Let’s use <code>ggplot()</code> to see how well the fitted return values match the actual return values.</p>
<pre><code>portfolio_model_augmented %>% 
  ggplot(aes(x = date)) + 
  geom_line(aes(y = returns, color = &quot;actual returns&quot;)) + 
  geom_line(aes(y = .fitted, color = &quot;fitted returns&quot;)) +
  scale_colour_manual(&quot;&quot;, 
                      values = c(&quot;fitted returns&quot; = &quot;green&quot;, 
                                 &quot;actual returns&quot; = &quot;cornflowerblue&quot;)) +
  xlab(&quot;date&quot;) + 
  ggtitle(&quot;Fitted versus actual returns&quot;)</code></pre>
<p><img src="https://i2.wp.com/rviews.rstudio.com/post/2018-02-28-capm-and-visualization_files/figure-html/unnamed-chunk-8-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Those monthly returns and fitted values seem to track well. Let’s convert both actual returns and fitted returns to the growth of a dollar and run the same comparison. This isn’t a traditional way to visualize actual versus fitted, but it’s still useful.</p>
<pre><code>portfolio_model_augmented %>%
  mutate(actual_growth = cumprod(1 + returns), 
         fitted_growth = cumprod(1 + .fitted)) %>% 
  ggplot(aes(x = date)) + 
  geom_line(aes(y = actual_growth, color = &quot;actual growth&quot;)) + 
  geom_line(aes(y = fitted_growth, color = &quot;fitted growth&quot;)) +
  xlab(&quot;date&quot;) +
  ylab(&quot;actual and fitted growth&quot;) + 
  ggtitle(&quot;Growth of a dollar: actual v. fitted&quot;) +
  scale_x_date(breaks = pretty_breaks(n = 8)) +
  scale_y_continuous(labels = dollar) +
  scale_colour_manual(&quot;&quot;, 
                      values = c(&quot;fitted growth&quot; = &quot;green&quot;, 
                                 &quot;actual growth&quot; = &quot;cornflowerblue&quot;)) </code></pre>
<p><img src="https://i1.wp.com/rviews.rstudio.com/post/2018-02-28-capm-and-visualization_files/figure-html/unnamed-chunk-9-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Our fitted growth tracks our actual growth well, though the actual growth is lower than predicted for most of the five year history.</p>
</div>
<div>
<h3>To Highcharter!</h3>
<p>A nice side benefit of <code>augment()</code> is that it allows us to create an interesting <code>highcharter</code> object that replicates our scatter + regression <code>ggplot</code> from earlier.</p>
<p>First, let’s build the base scatter plot of portfolio returns, which are housed in <code>portfolio_model_augmented$returns</code>, against market returns, which are housed in <code>portfolio_model_augmented$market_returns_tidy.returns</code>.</p>
<pre><code>library(highcharter)

highchart() %>% 
  hc_title(text = &quot;Portfolio v. Market Returns&quot;) %>%
  hc_add_series_scatter(round(portfolio_model_augmented$returns, 4), 
                        round(portfolio_model_augmented$market_returns_tidy.returns, 4)) %>%
  hc_xAxis(title = list(text = &quot;Market Returns&quot;)) %>% 
  hc_yAxis(title = list(text = &quot;Portfolio Returns&quot;))</code></pre>
<div></div>
<p></p>
<p>That looks good; but hover over one of the points. If you’re like me, you will desperately wish that the date of the observation were being displayed. Let’s add that date display functionality.</p>
<p>First, we need to supply the date observations, so we will add a <code>date</code> variable with <code>hc_add_series_scatter(..., date = portfolio_returns_tq_rebalanced_monthly$date)</code>. Then, we want the tool tip to pick up and display that variable. That is done with <code>hc_tooltip(formatter = JS(&quot;function(){return ('port return: ' + this.y + ' <br> mkt return: ' + this.x +  ' <br> date: ' + this.point.date)}&quot;))</code>. We are creating a custom tool tip function to pick up the date. Run the code chunk below and hover over a point.</p>
<pre><code>highchart() %>% 
  hc_title(text = &quot;Portfolio v. Market Returns&quot;) %>%
  hc_add_series_scatter(round(portfolio_model_augmented$returns, 4), 
                        round(portfolio_model_augmented$market_returns_tidy.returns, 4), 
                        date = portfolio_model_augmented$date) %>%
  hc_xAxis(title = list(text = &quot;Market Returns&quot;)) %>% 
  hc_yAxis(title = list(text = &quot;Portfolio Returns&quot;)) %>% 
  hc_tooltip(formatter = JS(&quot;function(){
                            return ('port return: ' + this.y + ' <br> mkt return: ' + this.x +  
                            ' <br> date: ' + this.point.date)}&quot;))</code></pre>
<div></div>
<p></p>
<p>I was curious about the most negative reading in the bottom left, and this new tool tip makes it easy to see that it occurred in August of 2015.</p>
<p>Finally, let’s add the regression line.</p>
<p>To do that, we need to supply x and y coordinates to <code>highcharter</code> and specify that we want to add a line instead of more scatter points. We have the x and y coordinates for our fitted regression line because we added them with the <code>augment()</code> function. The x’s are the market returns and the y’s are the fitted values. We add this element to our code flow with <code>hc_add_series(portfolio_model_augmented, type = &quot;line&quot;, hcaes(x = market_returns_tidy.returns, y = .fitted), name = &quot;CAPM Beta = Regression Slope&quot;)</code></p>
<pre><code>highchart() %>% 
  hc_title(text = &quot;Scatter with Regression Line&quot;) %>% 
  hc_add_series(portfolio_model_augmented, 
                type = &quot;scatter&quot;, 
                hcaes(x = round(market_returns_tidy.returns, 4), 
                      y = round(returns, 4),
                      date = date), 
                name = &quot;Returns&quot;) %>%
  hc_add_series(portfolio_model_augmented, 
                type = &quot;line&quot;, 
                hcaes(x = market_returns_tidy.returns, y = .fitted), 
                name = &quot;CAPM Beta = Regression Slope&quot;) %>% 
  hc_xAxis(title = list(text = &quot;Market Returns&quot;)) %>% 
  hc_yAxis(title = list(text = &quot;Portfolio Returns&quot;)) %>% 
  hc_tooltip(formatter = JS(&quot;function(){
                            return ('port return: ' + this.y + ' <br> mkt return: ' + this.x +  
                            ' <br> date: ' + this.point.date)}&quot;))</code></pre>
<div></div>
<p></p>
<p>That’s all for today and thanks for reading.</p>
</div>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://rviews.rstudio.com/2018/03/02/capm-and-visualization/"> R Views</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/zLblKnVjZx4" height="1"></a></div>