<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-visualizing-asset-returns/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rviews.rstudio.com/2017/11/09/introduction-to-visualizing-asset-returns/"> 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/2017/10/11/from-asset-to-portfolio-returns/" target="_blank">previous post</a>, we reviewed how to import daily prices, build a portfolio, and calculate portfolio returns. Today, we will visualize the returns of our individual assets that ultimately get mashed into a portfolio. The motivation here is to make sure we have scrutinized our assets before they get into our portfolio, because once the portfolio has been constructed, it is tempting to keep the analysis at the portfolio level.</p>
<p>By way of a quick reminder, our ultimate portfolio consists of the following.</p>
<pre><code>+ SPY (S&amp;P 500 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>Let’s load up our packages.</p>
<pre><code>library(tidyverse)
library(tidyquant)
library(timetk)
library(tibbletime)
library(highcharter)</code></pre>
<p>To get our objects into the global environment, we use the next code chunk, which should look familiar from the previous post: we will create one <code>xts</code> object and one <code>tibble</code>, in long/tidy format, of monthly log returns.</p>
<pre><code># The symbols vector holds our tickers. 
symbols &lt;- c(&quot;SPY&quot;,&quot;EFA&quot;, &quot;IJS&quot;, &quot;EEM&quot;,&quot;AGG&quot;)

prices &lt;- 
  getSymbols(symbols, src = 'yahoo', from = &quot;2005-01-01&quot;, 
             auto.assign = TRUE, warnings = FALSE) %>% 
  map(~Ad(get(.))) %>% 
  reduce(merge) %>%
  `colnames&lt;-`(symbols)

# XTS method
prices_monthly &lt;- to.monthly(prices, indexAt = &quot;last&quot;, OHLC = FALSE)
asset_returns_xts &lt;- na.omit(Return.calculate(prices_monthly, method = &quot;log&quot;))

# Tidyverse method, to long, tidy format
asset_returns_long &lt;- 
  prices %>% 
  to.monthly(indexAt = &quot;last&quot;, OHLC = FALSE) %>% 
  tk_tbl(preserve_index = TRUE, rename_index = &quot;date&quot;) %>%
  gather(asset, returns, -date) %>% 
  group_by(asset) %>%  
  mutate(returns = (log(returns) - log(lag(returns))))</code></pre>
<p>We now have two objects holding monthly log returns, <code>asset_returns_xts</code> and <code>asset_returns_long</code>. First, let’s use <code>highcharter</code> to visualize the <code>xts</code> formatted returns.</p>
<p>Highcharter is fantastic for visualizing a time series or many time series. First, we set <code>highchart(type = &quot;stock&quot;)</code> to get a nice time series line. Then we add each of our series to the highcharter code flow. In this case, we’ll add our columns from the xts object.</p>
<pre><code>highchart(type = &quot;stock&quot;) %>% 
  hc_title(text = &quot;Monthly Log Returns&quot;) %>%
  hc_add_series(asset_returns_xts$SPY, 
                  name = names(asset_returns_xts$SPY)) %>%
  hc_add_series(asset_returns_xts$EFA, 
                  name = names(asset_returns_xts$EFA)) %>%
  hc_add_series(asset_returns_xts$IJS, 
                  name = names(asset_returns_xts$IJS)) %>%
  hc_add_theme(hc_theme_flat()) %>%
  hc_navigator(enabled = FALSE) %>% 
  hc_scrollbar(enabled = FALSE)</code></pre>
<p>&lt; HEAD
<div></div>
<p></p>
<p>Take a look at the chart. It has a line for the monthly log returns of 3 of our ETFs (and in my opinion it’s already starting to get crowded). We might be able to pull some useful intuition from this chart. Perhaps one of our ETFs remained stable during the 2008 financial crisis, or had an era of consistently negative/positive returns. Highcharter is great for plotting time series line charts.</p>
<p>Highcharter does have the capacity for histogram making. One method is to first call the base function <code>hist</code> on the data along with the arguments for breaks and <code>plot = FALSE</code>. Then we can call <code>hchart</code> on that object.</p>
<p>=======</p>
<div></div>
<p></p>
<p>Take a look at the chart. It has a line for the monthly log returns of three of our ETFs (and in my opinion, it’s already starting to get crowded). We might be able to pull some useful intuition from this chart. Perhaps one of our ETFs remained stable during the 2008 financial crisis, or had an era of consistently negative/positive returns. Highcharter is great for plotting time series line charts.</p>
<p>Highcharter does have the capacity for histogram making. One method is to first call the base function <code>hist</code> on the data with the arguments for breaks and <code>plot = FALSE</code>. Then we can call <code>hchart</code> on that object.</p>
<p>>>>>>>> ea33b5686b615c7a2697ce0b8da92b85932d655f</p>
<pre><code>hc_spy &lt;- hist(asset_returns_xts$SPY, breaks = 50, plot = FALSE)

hchart(hc_spy) %>% 
  hc_title(text = &quot;SPY Log Returns Distribution&quot;)</code></pre>
<div></div>
<p></p>
<p>Nothing wrong with that chart, and it shows us the distribution of SPY returns. However, <code>highcharter</code> is missing an easy way to chart multiple histograms, and to add density lines to those multiple histograms. The functionality is fine for one set of returns, but here we want to see the distribution of all of our returns series together.</p>
<p>For that, we will head to the tidyverse and use <code>ggplot2</code> on our tidy <code>tibble</code> called <code>assets_returns_long</code>. Because it is in long, tidy format, and it is grouped by the ‘asset’ column, we can chart the asset histograms collectively on one chart.</p>
<pre><code># Make so all titles centered in the upcoming ggplots
theme_update(plot.title = element_text(hjust = 0.5))

asset_returns_long %>% 
  ggplot(aes(x = returns, fill = asset)) + 
  geom_histogram(alpha = 0.25, binwidth = .01)</code></pre>
<p><img src="https://i0.wp.com/rviews.rstudio.com/post/2017-11-07-introduction-to-visualizing-asset-returns_files/figure-html/unnamed-chunk-5-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Let’s use <code>facet_wrap(~asset)</code> to break these out by asset. We can add a title with <code>ggtitle</code>.</p>
<pre><code>asset_returns_long %>% 
  ggplot(aes(x = returns, fill = asset)) + 
  geom_histogram(alpha = 0.25, binwidth = .01) + 
  facet_wrap(~asset) + 
  ggtitle(&quot;Monthly Returns Since 2005&quot;)</code></pre>
<p><img src="https://i2.wp.com/rviews.rstudio.com/post/2017-11-07-introduction-to-visualizing-asset-returns_files/figure-html/unnamed-chunk-6-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Maybe we don’t want to use a histogram, but instead want to use a density line to visualize the various distributions. We can use the <code>stat_density(geom = &quot;line&quot;, alpha = 1)</code> function to do this. The <code>alpha</code> argument is selecting a line thickness. Let’s also add a label to the x and y axes with the <code>xlab</code> and <code>ylab</code> functions.</p>
<pre><code>asset_returns_long %>% 
  ggplot(aes(x = returns, colour = asset, fill = asset)) +
  stat_density(geom = &quot;line&quot;, alpha = 1) +
  ggtitle(&quot;Monthly Returns Since 2005&quot;) +
  xlab(&quot;monthly returns&quot;) +
  ylab(&quot;distribution&quot;) </code></pre>
<p><img src="https://i0.wp.com/rviews.rstudio.com/post/2017-11-07-introduction-to-visualizing-asset-returns_files/figure-html/unnamed-chunk-7-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>That chart is quite digestible, but we can also <code>facet_wrap(~asset)</code> to break the densities out into individual charts.</p>
<pre><code>asset_returns_long %>% 
  ggplot(aes(x = returns, colour = asset, fill = asset)) +
  stat_density(geom = &quot;line&quot;, alpha = 1) +
  facet_wrap(~asset) +
  ggtitle(&quot;Monthly Returns Since 2005&quot;) +
  xlab(&quot;monthly returns&quot;) +
  ylab(&quot;distribution&quot;) </code></pre>
<p><img src="https://i1.wp.com/rviews.rstudio.com/post/2017-11-07-introduction-to-visualizing-asset-returns_files/figure-html/unnamed-chunk-8-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Now we can combine all of our ggplots into one nice, faceted plot.</p>
<p>At the same time, to add to the aesthetic toolkit a bit, we will do some editing to the label colors. First off, let’s choose a different color besides black to be the theme. I will go with cornflower blue, because it’s a nice shade and I don’t see it used very frequently elsewhere. Once we have a color, we can choose the different elements of the chart to change in the the <code>theme</code> function. I make a lot of changes here by way of example but feel free to comment out a few of those lines and see the different options.</p>
<pre><code>asset_returns_long %>% 
  ggplot(aes(x = returns, colour = asset, fill = asset)) +
  stat_density(geom = &quot;line&quot;, alpha = 1) +
  geom_histogram(alpha = 0.25, binwidth = .01) +
  facet_wrap(~asset) +
  ggtitle(&quot;Monthly Returns Since 2005&quot;) +
  xlab(&quot;monthly returns&quot;) +
  ylab(&quot;distribution&quot;) +
  # Lots of elements can be customized in the theme() function
  theme(plot.title = element_text(colour = &quot;cornflowerblue&quot;),  
        strip.text.x = element_text(size = 8, colour = &quot;white&quot;), 
        strip.background = element_rect(colour = &quot;white&quot;, fill = &quot;cornflowerblue&quot;), 
        axis.text.x = element_text(colour = &quot;cornflowerblue&quot;), 
        axis.text = element_text(colour = &quot;cornflowerblue&quot;), 
        axis.ticks.x = element_line(colour = &quot;cornflowerblue&quot;), 
        axis.text.y = element_text(colour = &quot;cornflowerblue&quot;), 
        axis.ticks.y = element_line(colour = &quot;cornflowerblue&quot;),
        axis.title = element_text(colour = &quot;cornflowerblue&quot;),
        legend.title = element_text(colour = &quot;cornflowerblue&quot;),
        legend.text = element_text(colour = &quot;cornflowerblue&quot;)
        )</code></pre>
<p><img src="https://i0.wp.com/rviews.rstudio.com/post/2017-11-07-introduction-to-visualizing-asset-returns_files/figure-html/unnamed-chunk-9-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>We now have one chart, with histograms and line densities broken out for each of our assets. This would scale nicely if we had more assets and wanted to peek at more distributions of returns.</p>
<p>We have not done any substantive work today, but the chart of monthly returns is a tool to quickly glance at the data and see if anything unusual jumps out, or some sort of hypothesis comes to mind. We are going to be combining these assets into a portfolio and, once that occurs, we will rarely view the assets in isolation again. Before that leap to portfolio building, it’s a good idea to glance at the portfolio component distributions.</p>
<p>That’s all for today. Thanks for reading!</p>
<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/2017/11/09/introduction-to-visualizing-asset-returns/"> 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/5xqOldY-FFg" height="1"></a></div>