<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/tidyquant-0-4-0-performanceanalytics-improved-documentation-ggplot2-themes-and-more/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html"> business-science.io - Articles</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I’m excited to announce the release of <code>tidyquant</code> version 0.4.0!!! The release is yet again sizable. It includes <strong>integration with the <code>PerformanceAnalytics</code> package</strong>, which now enables full financial analyses to be performed without ever leaving the “tidyverse” (i.e. <strong>with DATA FRAMES</strong>). The integration includes the ability to perform performance analysis and portfolio attribution at scale (i.e. with many stocks or many portfolios at once)! But wait there’s more… In addition to an introduction vignette, we created <strong>five (yes, five!) topic-specific vignettes</strong> designed to reduce the learning curve for <em>financial data scientists</em>. We also have <strong>new <code>ggplot2</code> themes</strong> to assist with creating beautiful and meaningful financial charts. We included <code>tq_get</code> support for <strong>“compound getters”</strong> so multiple data sources can be brought into a nested data frame all at once. Last, we have added new <code>tq_index()</code> and <code>tq_exchange()</code> functions to make collecting stock data with <code>tq_get</code> even easier. I’ll briefly touch on several of the updates. The package is open source, and you can view the code on the <a target="_blank" rel="nofollow" href="https://github.com/mdancho84/tidyquant">tidyquant github page</a>.</p>
<h1>Table of Contents</h1>
<ul>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#prerequisites">Prerequisites</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#overview">Overview</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#updates">v0.4.0 Updates</a>
<ul>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example1">1: PerformanceAnalytics Integration</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example2">2: New User-Friendly Vignettes</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example3">3: New ggplot2 Themes</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example4">4: “Compound Getters” in tq_get</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example5">5: tq_index and tq_exchange</a></li>
</ul>
</li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#conclusion">Conclusion</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#recap">Recap</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#further-reading">Further Reading</a></li>
</ul>
<h1>Prerequisites <a></a></h1>
<p>First, update to <code>tidyquant</code> v0.4.0.</p>
<figure>
<pre><code data-lang="r"><span>install.packages</span><span>(</span><span>&quot;tidyquant&quot;</span><span>)</span></code></pre>
</figure>
<p>Next, load <code>tidyquant</code>.</p>
<figure>
<pre><code data-lang="r"><span># Loads tidyquant, tidyverse, lubridate, quantmod, TTR, xts, zoo, PerformanceAnalytics
</span><span>library</span><span>(</span><span>tidyquant</span><span>)</span></code></pre>
</figure>
<p>Load the <code>FANG</code> data set, which will be used in the examples. The <code>FANG</code> data set contains the historical stock prices for FB, AMZN, NFLX, and GOOG from the beginning of 2013 through the end of 2016.</p>
<figure>
<pre><code data-lang="r"><span>data</span><span>(</span><span>FANG</span><span>)</span><span>
</span><span>FANG</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 4,032 × 8
##    symbol       date  open  high   low close    volume adjusted
##     &lt;chr>     &lt;date> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl>     &lt;dbl>    &lt;dbl>
## 1      FB 2013-01-02 27.44 28.18 27.42 28.00  69846400    28.00
## 2      FB 2013-01-03 27.88 28.47 27.59 27.77  63140600    27.77
## 3      FB 2013-01-04 28.01 28.93 27.83 28.76  72715400    28.76
## 4      FB 2013-01-07 28.69 29.79 28.65 29.42  83781800    29.42
## 5      FB 2013-01-08 29.51 29.60 28.86 29.06  45871300    29.06
## 6      FB 2013-01-09 29.67 30.60 29.49 30.59 104787700    30.59
## 7      FB 2013-01-10 30.60 31.45 30.28 31.30  95316400    31.30
## 8      FB 2013-01-11 31.28 31.96 31.10 31.72  89598000    31.72
## 9      FB 2013-01-14 32.08 32.21 30.62 30.95  98892800    30.95
## 10     FB 2013-01-15 30.64 31.71 29.88 30.10 173242600    30.10
## # ... with 4,022 more rows</code></pre>
</figure>
<p>I also recommend the open-source <a target="_blank" rel="nofollow" href="https://www.rstudio.com/">RStudio</a> IDE, which makes <em>R Programming</em> easy and efficient especially for financial analysis.</p>
<h1>Overview <a></a></h1>
<blockquote>
<p>tidyquant: Bringing financial analysis to the tidyverse</p>
</blockquote>
<p>Before I dive into the updates, if you are new to <code>tidyquant</code> there’s a few core functions that you need to be aware of:</p>
<ul>
<li>
<p><strong>Getting Financial Data from the web: <code>tq_get()</code></strong>. This is a one-stop shop for getting web-based financial data in a “tidy” data frame format. Get data for daily stock prices (historical), key statistics (real-time), key ratios (historical), financial statements, dividends, splits, economic data from the FRED, FOREX rates from Oanda.</p>
</li>
<li>
<p><strong>Manipulating Financial Data: <code>tq_transmute()</code> and <code>tq_mutate()</code></strong>. Integration for many financial functions from <code>xts</code>, <code>zoo</code>, <code>quantmod</code> and <code>TTR</code> packages. <code>tq_mutate()</code> is used to add a column to the data frame, and <code>tq_transmute()</code> is used to return a new data frame which is necessary for periodicity changes. <strong>Important:</strong> In v0.4.0, <code>tq_transmute()</code> replaces <code>tq_transform()</code> for consistency with <code>dplyr::transmute()</code>.</p>
</li>
<li>
<p><strong>Coercing Data To and From xts and tibble: <code>as_tibble()</code>and <code>as_xts()</code></strong>. There are a ton of <a target="_blank" rel="nofollow" href="http://stackoverflow.com/search?q=xts+data+frame">Stack Overflow articles</a> on converting data frames to and from xts. These two functions can be used to answer 99% of these questions.</p>
</li>
<li>
<p><strong>Performance Analysis and Portfolio Analysis: <code>tq_performance()</code> and <code>tq_portfolio()</code></strong>. The newest additions to the <code>tidyquant</code> family integrate <code>PerformanceAnalytics</code> functions. <code>tq_performance()</code> converts investment returns into performance metrics. <code>tq_portfolio()</code> aggregates a group (or multiple groups) of asset returns into one or more portfolios.</p>
</li>
</ul>
<p>To learn more, <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=tidyquant">browse the new and improved vignettes</a>.</p>
<h1>v0.4.0 Updates <a></a></h1>
<p>We’ve got some neat examples to show off the new capabilities:</p>
<ol>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example1">PerformanceAnalytics Integration</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example2">New User-Friendly Vignettes</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example3">New ggplot2 Themes</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example4">“Compound Getters” in tq_get</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html#example5">tq_index and tq_exchange</a></li>
</ol>
<h2>1: PerformanceAnalytics Integration <a></a></h2>
<p>The <code>PerformanceAnalytics</code> package does two things very well. First, it enables performance analysis of investment returns using a wide variety of metrics that are detailed in the text, <a target="_blank" rel="nofollow" href="https://www.amazon.com/Practical-Portfolio-Performance-Measurement-Attribution/dp/0470059281"><em>“Practical Portfolio Performance Measurement and Attribution”</em> by Carl Bacon</a>. Second, it enables portfolio aggregation, the process of aggregating a weighted group of stocks or investments into a single set of returns. When combined, this functionality enables <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Performance_attribution">portfolio attribution</a>, a set of techniques used to explain a portfolio’s performance versus a benchmark.</p>
<p>The next few examples show off some of the basic capability. These examples scratch the surface of the full capability. Below is a figure demonstrating multiple portfolio analysis, which is an advanced topic discussed in the vignette.</p>
<p><img alt="Portfolio Analysis" src="https://i0.wp.com/www.business-science.io/assets/tidyquant-040.png?w=456" data-recalc-dims="1"></p>
<h3>A: Stock Performance Analysis</h3>
<p>The <strong>Sharpe ratio</strong> is commonly used in finance as a measure of return per unit risk. The larger the value, the better the reward-to-risk trade off. The <code>PerformanceAnalytics</code> package contains a function <code>SharpeRatio</code> (and <code>SharpeRatio.modified</code>) that can be used to quickly calculate from a set of returns. We’ll use <code>tq_performance</code> to calculate the Sharpe ratio in a “tidy” way, using the <code>PerformanceAnalytics</code> integration. Call <code>tq_performance_fun_options()</code> to see a full list of integrated functions. <em>Spoiler alert: there’s 128 functions divided into 14 categories.</em></p>
<p><code>tq_performance()</code> allows us to apply <code>SharpeRatio</code> to “tidy” data frames. The <code>tq_performance()</code> function uses <code>Ra</code> and <code>Rb</code> to specify the asset returns and baseline returns, respectively. These values get passed to the <code>performance_fun</code>, which in our case will be <code>SharpeRatio</code>. The <code>...</code> allows the user to pass additional arguments to the underlying <code>PerformanceAnalytics</code> function. The arguments are shown below.</p>
<figure>
<pre><code data-lang="r"><span>args</span><span>(</span><span>tq_performance</span><span>)</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## function (data, Ra, Rb = NULL, performance_fun, ...) 
## NULL</code></pre>
</figure>
<p>To understand the end goal, we need to analyze the <code>SharpeRatio</code> function. The arguments are displayed below. It contains <code>R</code> a set of returns, <code>Rf</code> the risk-free rate, <code>p</code> the confidence level, and <code>FUN</code> the value of the denominator (default returns Sharpe ratio using all three), and a few other functions that are not used in this example. It’s important to recognize that <code>R</code> in the <code>SharpeRatio()</code> function is specified using asset returns (<code>Ra</code>) in the <code>tq_performance()</code> function. The baseline returns argument (<code>Rb</code>) in the <code>tq_performance()</code> function is not required since the baseline is not required to calculate <code>SharpeRatio</code>. Just keep in mind that you will either see <code>R</code> or the combination of <code>Ra, Rb</code> in the <code>PerformanceAnalytics</code> function arguments, which indicates whether or not <code>Rb</code> is required in <code>tq_performance()</code>.</p>
<figure>
<pre><code data-lang="r"><span>args</span><span>(</span><span>SharpeRatio</span><span>)</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## function (R, Rf = 0, p = 0.95, FUN = c(&quot;StdDev&quot;, &quot;VaR&quot;, &quot;ES&quot;), 
##     weights = NULL, annualize = FALSE, ...) 
## NULL</code></pre>
</figure>
<p>Now that we understand the function, we can easily begin the task of getting the Sharpe ratios for the “FANG” stocks. It involves three steps:</p>
<ol>
<li>Get data with <code>tq_get</code> (already done since we have <code>FANG</code> loaded). Make sure to group by symbol if the tibble includes prices for multiple stocks.</li>
<li>Transmute to period returns with <code>tq_transmute(mutate_fun = periodReturn)</code></li>
<li>Calculate Sharpe ratio with <code>tq_performance(performance_fun = SharpeRatio)</code></li>
</ol>
<figure>
<pre><code data-lang="r"><span>FANG</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>symbol</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>tq_transmute</span><span>(</span><span>ohlc_fun</span><span> </span><span>=</span><span> </span><span>Ad</span><span>,</span><span>
</span><span>mutate_fun</span><span> </span><span>=</span><span> </span><span>periodReturn</span><span>,</span><span>
</span><span>period</span><span> </span><span>=</span><span> </span><span>&quot;daily&quot;</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>tq_performance</span><span>(</span><span>Ra</span><span> </span><span>=</span><span> </span><span>daily.returns</span><span>,</span><span>
</span><span>Rb</span><span> </span><span>=</span><span> </span><span>NULL</span><span>,</span><span>
</span><span>performance_fun</span><span> </span><span>=</span><span> </span><span>SharpeRatio</span><span>,</span><span>
</span><span>Rf</span><span> </span><span>=</span><span> </span><span>0</span><span>,</span><span>
</span><span>p</span><span> </span><span>=</span><span> </span><span>0.95</span><span>,</span><span>
</span><span>FUN</span><span> </span><span>=</span><span> </span><span>&quot;StdDev&quot;</span><span>)</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## Source: local data frame [4 x 2]
## Groups: symbol [4]
## 
##   symbol `StdDevSharpe(Rf=0%,p=95%)`
##    &lt;chr>                       &lt;dbl>
## 1     FB                  0.07439327
## 2   AMZN                  0.06442433
## 3   NFLX                  0.08402702
## 4   GOOG                  0.05825002</code></pre>
</figure>
<p>It’s very easy to get performance metrics for multiple stocks. Next, we’ll take a look at portfolio performance.</p>
<h3>B: Basic Portfolio Performance</h3>
<p>Combining a group of assets into a portfolio is one of the most useful techniques for controlling risk versus reward. The blending of assets naturally diversifies and can reduce downside risk. Further, portfolio attribution is a set of techniques used to analyze a portfolio or set of portfolios against a benchmark. The newest vignette, <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=tidyquant">Performance Analysis with tidyquant</a>, breaks the process into several steps shown in the workflow diagram below.</p>
<p><img alt="Portfolio Workflow" src="https://i0.wp.com/www.business-science.io/assets/performance_analysis_workflow.png?w=456" data-recalc-dims="1"></p>
<p>The process for a single portfolio aggregation without a benchmark is shown below. Portfolio aggregation requires a set of weights that can be applied to the various assets (stocks) in the portfolio. Our portfolio consists of FB, AMZN, NFLX, and GOOG. Passing the weights of 50%, 25%, 25%, and 0% blends and aggregates into one set of portfolio returns.</p>
<figure>
<pre><code data-lang="r"><span>weights</span><span> </span><span>&lt;-</span><span> </span><span>c</span><span>(</span><span>0.50</span><span>,</span><span> </span><span>0.25</span><span>,</span><span> </span><span>0.25</span><span>,</span><span> </span><span>0.00</span><span>)</span><span>
</span><span>FANG_portfolio</span><span> </span><span>&lt;-</span><span> </span><span>FANG</span><span> </span><span>%>%</span><span> </span><span>group_by</span><span>(</span><span>symbol</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>tq_transmute</span><span>(</span><span>ohlc_fun</span><span> </span><span>=</span><span> </span><span>Ad</span><span>,</span><span>
</span><span>mutate_fun</span><span> </span><span>=</span><span> </span><span>periodReturn</span><span>,</span><span>
</span><span>period</span><span> </span><span>=</span><span> </span><span>&quot;monthly&quot;</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>tq_portfolio</span><span>(</span><span>assets_col</span><span> </span><span>=</span><span> </span><span>symbol</span><span>,</span><span>
</span><span>returns_col</span><span> </span><span>=</span><span> </span><span>monthly.returns</span><span>,</span><span>
</span><span>weights</span><span> </span><span>=</span><span> </span><span>weights</span><span>)</span><span>
</span><span>FANG_portfolio</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 48 × 2
##          date portfolio.returns
##        &lt;date>             &lt;dbl>
## 1  2013-01-31       0.260144557
## 2  2013-02-28      -0.004558003
## 3  2013-03-28      -0.019454685
## 4  2013-04-30       0.080958243
## 5  2013-05-31      -0.013883075
## 6  2013-06-28      -0.017906983
## 7  2013-07-31       0.253520291
## 8  2013-08-30       0.103866369
## 9  2013-09-30       0.145446247
## 10 2013-10-31       0.041956895
## # ... with 38 more rows</code></pre>
</figure>
<p>At this point, it’s nice to visualize using a wealth index, which shows the growth of the portfolio. The wealth index is actually an option in <code>tq_portfolio</code>, but it can also be created by converting the portfolio returns using the <code>cumprod()</code> function shown below.</p>
<figure>
<pre><code data-lang="r"><span>init.investment</span><span> </span><span>&lt;-</span><span> </span><span>10000</span><span>
</span><span>FANG_portfolio</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>wealth.index</span><span> </span><span>=</span><span> </span><span>init.investment</span><span> </span><span>*</span><span> </span><span>cumprod</span><span>(</span><span>1</span><span> </span><span>+</span><span> </span><span>portfolio.returns</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>date</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>wealth.index</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_line</span><span>(</span><span>size</span><span> </span><span>=</span><span> </span><span>2</span><span>,</span><span> </span><span>color</span><span> </span><span>=</span><span> </span><span>palette_light</span><span>()[[</span><span>3</span><span>]])</span><span> </span><span>+</span><span>
</span><span>geom_smooth</span><span>(</span><span>method</span><span> </span><span>=</span><span> </span><span>&quot;loess&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>labs</span><span>(</span><span>title</span><span> </span><span>=</span><span> </span><span>&quot;Individual Portfolio: Comparing the Growth of $10K&quot;</span><span>,</span><span>
</span><span>subtitle</span><span> </span><span>=</span><span> </span><span>&quot;Quickly visualize performance&quot;</span><span>,</span><span>
</span><span>x</span><span> </span><span>=</span><span> </span><span>&quot;&quot;</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>&quot;Investment Value&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>theme_tq</span><span>()</span><span> </span><span>+</span><span>
</span><span>scale_y_continuous</span><span>(</span><span>labels</span><span> </span><span>=</span><span> </span><span>scales</span><span>::</span><span>dollar</span><span>)</span></code></pre>
</figure>
<p><img alt="plot of chunk unnamed-chunk-8" src="https://i1.wp.com/www.business-science.io/figure/source/2017-3-4-tidyquant-update-0-4-0/unnamed-chunk-8-1.png?w=456" data-recalc-dims="1"></p>
<p>We can even get some performance metrics using <code>PerformanceAnalytics</code> functions. The table functions are the most useful since they calculate groups of portfolio attribution metrics. <strong>Eighteen different table functions are available</strong>. We’ll use the <code>table.Stats</code> function, which returns a “tidy” set of 15 summary statistics on the stock returns including arithmetic mean, standard deviation, skewness, kurtosis, and more.</p>
<figure>
<pre><code data-lang="r"><span>FANG_portfolio</span><span> </span><span>%>%</span><span>
</span><span>tq_performance</span><span>(</span><span>Ra</span><span> </span><span>=</span><span> </span><span>portfolio.returns</span><span>,</span><span>
</span><span>Rb</span><span> </span><span>=</span><span> </span><span>NULL</span><span>,</span><span>
</span><span>performance_fun</span><span> </span><span>=</span><span> </span><span>table.Stats</span><span>)</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 1 × 16
##   ArithmeticMean GeometricMean Kurtosis `LCLMean(0.95)` Maximum
## *          &lt;dbl>         &lt;dbl>    &lt;dbl>           &lt;dbl>   &lt;dbl>
## 1         0.0379        0.0347   0.5327          0.0138  0.2601
## # ... with 11 more variables: Median &lt;dbl>, Minimum &lt;dbl>, NAs &lt;dbl>,
## #   Observations &lt;dbl>, Quartile1 &lt;dbl>, Quartile3 &lt;dbl>,
## #   SEMean &lt;dbl>, Skewness &lt;dbl>, Stdev &lt;dbl>, `UCLMean(0.95)` &lt;dbl>,
## #   Variance &lt;dbl></code></pre>
</figure>
<p>There’s also capability for <strong>performance attribution</strong> (comparing portfolio performance against a benchmark) and <strong>scaling analyses to multiple portfolios</strong>. For those interested in furthering the analysis, please visit the new vignette, <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=tidyquant">Performance Analysis with tidyquant</a>.</p>
<h2>2: New User-Friendly Vignettes <a></a></h2>
<p>Financial analysis can be overwhelming due to the depth and breadth of various topics. Add to it a new package with new functions and workflows, and the task can seem impossible. The good news is <strong>we understand</strong>.</p>
<p>We are actively taking steps to reduce the learning curve so you can get up to speed quickly. While the work is not done yet, we believe that the vignettes are a good place to start. The goal is to break down complex tasks without overloading the user with everything at once. There is now one main “introduction” that links to five topic-specific vignettes. Each topical vignette covers the basics behind the package including real-world examples so you can see how the package can be implemented. You can access the <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=tidyquant">new vignettes here</a>.</p>
<p><img alt="tidyquant vignettes" src="https://i0.wp.com/www.business-science.io/assets/tidyquant-vignettes.png?w=456" data-recalc-dims="1"></p>
<h2>3: New ggplot2 Themes <a></a></h2>
<p><code>tidyquant</code> ships with some new themes to assist with creating beautiful and meaningful financial charts: <code>theme_tq()</code> and some extra fun ones including <code>theme_tq_dark()</code> and <code>theme_tq_green()</code>. To coordinate aesthetic colors and fills with the appropriate theme, we’ve added <code>scale_color_tq(theme = &quot;light&quot;)</code>. You can modify the <code>theme</code> arg to get the colors to correspond with the different themes. In addition, we have <code>palette_light()</code>, <code>palette_dark()</code> and <code>palette_green()</code> for those interested in using the color palette. Here’s a quick example.</p>
<figure>
<pre><code data-lang="r"><span>FANG</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>symbol</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>tq_transmute</span><span>(</span><span>ohlc_fun</span><span> </span><span>=</span><span> </span><span>Ad</span><span>,</span><span>
</span><span>mutate_fun</span><span> </span><span>=</span><span> </span><span>periodReturn</span><span>,</span><span>
</span><span>period</span><span> </span><span>=</span><span> </span><span>&quot;monthly&quot;</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>wealth.index</span><span> </span><span>=</span><span> </span><span>10000</span><span> </span><span>*</span><span> </span><span>cumprod</span><span>(</span><span>1</span><span> </span><span>+</span><span> </span><span>monthly.returns</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>date</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>wealth.index</span><span>,</span><span> </span><span>color</span><span> </span><span>=</span><span> </span><span>symbol</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_line</span><span>(</span><span>size</span><span> </span><span>=</span><span> </span><span>1.5</span><span>)</span><span> </span><span>+</span><span>
</span><span>labs</span><span>(</span><span>title</span><span> </span><span>=</span><span> </span><span>&quot;Stocks: Comparing the Growth of $10K&quot;</span><span>,</span><span>
</span><span>subtitle</span><span> </span><span>=</span><span> </span><span>&quot;New theme for financial visualizations&quot;</span><span>,</span><span>
</span><span>x</span><span> </span><span>=</span><span> </span><span>&quot;&quot;</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>&quot;Investment Value&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>scale_y_continuous</span><span>(</span><span>labels</span><span> </span><span>=</span><span> </span><span>scales</span><span>::</span><span>dollar</span><span>)</span><span> </span><span>+</span><span>
</span><span>theme_tq</span><span>()</span><span> </span><span>+</span><span>
</span><span>scale_color_tq</span><span>(</span><span>theme</span><span> </span><span>=</span><span> </span><span>&quot;light&quot;</span><span>)</span></code></pre>
</figure>
<p><img alt="plot of chunk unnamed-chunk-10" src="https://i2.wp.com/www.business-science.io/figure/source/2017-3-4-tidyquant-update-0-4-0/unnamed-chunk-10-1.png?w=456" data-recalc-dims="1"></p>
<p>For those interested in learning more about the <code>tidyquant</code> charting capabilities, please visit the updated vignette, <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=tidyquant">Charting with tidyquant</a>.</p>
<h2>4: “Compound Getters” in tq_get <a></a></h2>
<p>Compound getters are a nice tool for those looking to get multiple data sets for one stock symbol. For example, one may want the “key.ratios” and the “key.stats”, which provides key fundamental and financial ratio data on both a historical and real-time basis, respectively. You can now pull this information in one call to <code>tq_get</code> using a “compound getter”.</p>
<figure>
<pre><code data-lang="r"><span>AAPL_data</span><span> </span><span>&lt;-</span><span> </span><span>tq_get</span><span>(</span><span>&quot;AAPL&quot;</span><span>,</span><span> </span><span>get</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>&quot;key.ratios&quot;</span><span>,</span><span> </span><span>&quot;key.stats&quot;</span><span>))</span><span>
</span><span>AAPL_data</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 1 × 3
##   symbol       key.ratios         key.stats
##    &lt;chr>           &lt;list>            &lt;list>
## 1   AAPL &lt;tibble [7 × 2]> &lt;tibble [1 × 55]></code></pre>
</figure>
<p>Let’s examine what’s in the “key.ratios” column using <code>unnest()</code>.</p>
<figure>
<pre><code data-lang="r"><span>AAPL_data</span><span> </span><span>%>%</span><span> </span><span>unnest</span><span>(</span><span>key.ratios</span><span>)</span><span> </span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 7 × 3
##   symbol           section               data
##    &lt;chr>             &lt;chr>             &lt;list>
## 1   AAPL        Financials &lt;tibble [150 × 5]>
## 2   AAPL     Profitability &lt;tibble [170 × 5]>
## 3   AAPL            Growth &lt;tibble [160 × 5]>
## 4   AAPL         Cash Flow  &lt;tibble [50 × 5]>
## 5   AAPL  Financial Health &lt;tibble [240 × 5]>
## 6   AAPL Efficiency Ratios  &lt;tibble [80 × 5]>
## 7   AAPL  Valuation Ratios  &lt;tibble [40 × 5]></code></pre>
</figure>
<p>Like peeling away layers we can see whats inside. Let’s do one more <code>unnest</code>.</p>
<figure>
<pre><code data-lang="r"><span>AAPL_data</span><span> </span><span>%>%</span><span> </span><span>unnest</span><span>(</span><span>key.ratios</span><span>)</span><span> </span><span>%>%</span><span> </span><span>unnest</span><span>(</span><span>data</span><span>)</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 890 × 7
##    symbol    section sub.section group        category       date
##     &lt;chr>      &lt;chr>       &lt;chr> &lt;dbl>           &lt;chr>     &lt;date>
## 1    AAPL Financials  Financials     1 Revenue USD Mil 2007-09-01
## 2    AAPL Financials  Financials     1 Revenue USD Mil 2008-09-01
## 3    AAPL Financials  Financials     1 Revenue USD Mil 2009-09-01
## 4    AAPL Financials  Financials     1 Revenue USD Mil 2010-09-01
## 5    AAPL Financials  Financials     1 Revenue USD Mil 2011-09-01
## 6    AAPL Financials  Financials     1 Revenue USD Mil 2012-09-01
## 7    AAPL Financials  Financials     1 Revenue USD Mil 2013-09-01
## 8    AAPL Financials  Financials     1 Revenue USD Mil 2014-09-01
## 9    AAPL Financials  Financials     1 Revenue USD Mil 2015-09-01
## 10   AAPL Financials  Financials     1 Revenue USD Mil 2016-09-01
## # ... with 880 more rows, and 1 more variables: value &lt;dbl></code></pre>
</figure>
<p>We can do the same thing with the “key.stats”. Set <code>.drop = TRUE</code> to remove the “key.ratios” column.</p>
<figure>
<pre><code data-lang="r"><span>AAPL_data</span><span> </span><span>%>%</span><span> </span><span>unnest</span><span>(</span><span>key.stats</span><span>,</span><span> </span><span>.drop</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>)</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 1 × 56
##   symbol    Ask Ask.Size Average.Daily.Volume    Bid Bid.Size
##    &lt;chr>  &lt;dbl>    &lt;dbl>                &lt;dbl>  &lt;dbl>    &lt;dbl>
## 1   AAPL 139.68      200             28964000 139.53      500
## # ... with 50 more variables: Book.Value &lt;dbl>, Change &lt;dbl>,
## #   Change.From.200.day.Moving.Average &lt;dbl>,
## #   Change.From.50.day.Moving.Average &lt;dbl>,
## #   Change.From.52.week.High &lt;dbl>, Change.From.52.week.Low &lt;dbl>,
## #   Change.in.Percent &lt;dbl>, Currency &lt;chr>, Days.High &lt;dbl>,
## #   Days.Low &lt;dbl>, Days.Range &lt;chr>, Dividend.Pay.Date &lt;date>,
## #   Dividend.per.Share &lt;dbl>, Dividend.Yield &lt;dbl>, EBITDA &lt;dbl>,
## #   EPS &lt;dbl>, EPS.Estimate.Current.Year &lt;dbl>,
## #   EPS.Estimate.Next.Quarter &lt;dbl>, EPS.Estimate.Next.Year &lt;dbl>,
## #   Ex.Dividend.Date &lt;date>, Float.Shares &lt;dbl>, High.52.week &lt;dbl>,
## #   Last.Trade.Date &lt;date>, Last.Trade.Price.Only &lt;dbl>,
## #   Last.Trade.Size &lt;dbl>, Last.Trade.With.Time &lt;chr>,
## #   Low.52.week &lt;dbl>, Market.Capitalization &lt;dbl>,
## #   Moving.Average.200.day &lt;dbl>, Moving.Average.50.day &lt;dbl>,
## #   Name &lt;chr>, Open &lt;dbl>, PE.Ratio &lt;dbl>, PEG.Ratio &lt;dbl>,
## #   Percent.Change.From.200.day.Moving.Average &lt;dbl>,
## #   Percent.Change.From.50.day.Moving.Average &lt;dbl>,
## #   Percent.Change.From.52.week.High &lt;dbl>,
## #   Percent.Change.From.52.week.Low &lt;dbl>, Previous.Close &lt;dbl>,
## #   Price.to.Book &lt;dbl>, Price.to.EPS.Estimate.Current.Year &lt;dbl>,
## #   Price.to.EPS.Estimate.Next.Year &lt;dbl>, Price.to.Sales &lt;dbl>,
## #   Range.52.week &lt;chr>, Revenue &lt;dbl>, Shares.Outstanding &lt;dbl>,
## #   Short.Ratio &lt;dbl>, Stock.Exchange &lt;chr>,
## #   Target.Price.1.yr. &lt;dbl>, Volume &lt;dbl></code></pre>
</figure>
<p>The benefit to “compound getters” is that <strong>all your data is stored in one data frame</strong>. To access it, you can simply <code>unnest</code> the list columns. Additionally, the “compound getters” can be <strong>scaled</strong> in the same way that a single get can be scaled: with a vector of stock symbols or a data frame of stock symbols with the symbols in the first column. See the next section for scaling using the new <code>tq_index()</code> and <code>tq_exchange()</code> functions.</p>
<h2>5. tq_index and tq_exchange <a></a></h2>
<p>We got some really good feedback from a certain someone at <em>RStudio</em> on combining two calls to <code>tq_get()</code> in a row for retrieving an index of stock symbols (e.g. “SP500”) and then the scaling the retrieval of data for the stock symbols. The advice was really good because (1) it was ugly having two calls to <code>tq_get()</code> in a row and (2) more importantly it got us thinking how we can improve scaling data collection. Here’s the significant change from “old way” to the “new way”.</p>
<figure>
<pre><code data-lang="r"><span># Not evaluated due to excessive run time
# Old method
</span><span>tq_get</span><span>(</span><span>&quot;SP500&quot;</span><span>,</span><span> </span><span>get</span><span> </span><span>=</span><span> </span><span>&quot;stock.index&quot;</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>tq_get</span><span>(</span><span>get</span><span> </span><span>=</span><span> </span><span>&quot;stock.prices&quot;</span><span>)</span><span>
</span><span># New method
</span><span>tq_index</span><span>(</span><span>&quot;SP500&quot;</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>tq_get</span><span>(</span><span>get</span><span> </span><span>=</span><span> </span><span>&quot;stock.prices&quot;</span><span>)</span></code></pre>
</figure>
<p>The separation of a stock list from a call to retrieve the data for each of the stocks is fundamentally a good idea because now we can have more lists. For example, if you want to download stock prices for every stock covered on the NASDAQ exchange, you can use the new <code>tq_exchange(&quot;NASDAQ&quot;)</code> to retrieve the stock list and then pipe (<code>%>%</code>) the list to <code>tq_get</code>.</p>
<figure>
<pre><code data-lang="r"><span>tq_exchange</span><span>(</span><span>&quot;NASDAQ&quot;</span><span>)</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 3,169 × 7
##    symbol                                company last.sale.price
##     &lt;chr>                                  &lt;chr>           &lt;dbl>
## 1     PIH 1347 Property Insurance Holdings, Inc.            7.20
## 2    FLWS                1-800 FLOWERS.COM, Inc.            9.85
## 3    FCCY          1st Constitution Bancorp (NJ)           18.65
## 4    SRCE                 1st Source Corporation           47.08
## 5    VNET                   21Vianet Group, Inc.            7.10
## 6    TWOU                               2U, Inc.           37.65
## 7    JOBS                            51job, Inc.           35.60
## 8    CAFD             8point3 Energy Partners LP           12.91
## 9    EGHT                                8x8 Inc           14.90
## 10   AVHI                        A V Homes, Inc.           16.85
## # ... with 3,159 more rows, and 4 more variables: market.cap &lt;chr>,
## #   ipo.year &lt;dbl>, sector &lt;chr>, industry &lt;chr></code></pre>
</figure>
<p>Piping to <code>tq_get</code>. (Warning: <em>A word of caution that this could take 10-20 minutes to download the stock prices for all 3169 stock symbols.</em>)</p>
<figure>
<pre><code data-lang="r"><span># Not evaluated due to excessive time
</span><span>tq_exchange</span><span>(</span><span>&quot;NASDAQ&quot;</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>tq_get</span><span>(</span><span>get</span><span> </span><span>=</span><span> </span><span>&quot;stock.prices&quot;</span><span>)</span></code></pre>
</figure>
<p>The combination of <code>tq_index</code> and <code>tq_exchange</code> now gives the user access to a wide range of stock lists. To get the full list of options, use <code>tq_index_options()</code> and <code>tq_exchange_options()</code>, respectively.</p>
<h1>Conclusions <a></a></h1>
<p>This is an exciting release for a few reasons. First, the <code>PerformanceAnalytics</code> integration fills a big gap that now allows full financial analysis to be performed within the “tidyverse” (i.e. using data frames only). You can start a workflow with a symbol or set of symbols and through piping (<code>%>%</code>) to <code>tq_get</code>, <code>tq_transmute</code>, and <code>tq_performance</code> can end with performance metrics all in a few lines of code. Previously this was impossible.</p>
<p>Second, portfolio attribution and performance analysis is now possible in the “tidyverse”. This is very interesting because with the data science workflow discussed in <a target="_blank" rel="nofollow" href="http://r4ds.had.co.nz/">R for Data Science</a> the scale at which portfolios can be modeled and analyzed is limitless (refer to many models and the <code>purrr</code> package).</p>
<p>Third, data science is a rapidly evolving field with new people joining the community by the second. With this influx we recognize it’s important to reduce the learning curve for “financial data scientists”, those looking to apply data science to finance. As a result, we are actively taking steps to reduce the learning curve. The first step of providing a set of improved vignettes is complete. We will continue to focus on this area in the future.</p>
<h1>Recap <a></a></h1>
<p>This post was meant to give users and potential users a flavor for the new additions to <code>tidyquant</code> v0.4.0. We took a peek at the new <code>PerformanceAnalytics</code> integration, which enables performance analysis and portfolio aggregation. We introduced the new vignettes, which are topical and are designed to get users up to speed quickly. We discussed several other important new features such as new <code>ggplot2</code> themes, the new support for “compound getters” in <code>tq_get</code>, and the new <code>tq_index</code> and <code>tq_exchange</code> functions for retrieving stock lists. There are a number of other changes not specifically addressed. Those interested can view the <a target="_blank" rel="nofollow" href="https://github.com/mdancho84/tidyquant/blob/master/NEWS.md">NEWS here</a>.</p>
<h1>Further Reading <a></a></h1>
<ol>
<li>
<p><strong><a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=tidyquant">Tidyquant Vignettes</a></strong>: This overview just scratches the surface of <code>tidyquant</code>. The vignettes explain much, much more!</p>
</li>
<li>
<p><strong><a target="_blank" rel="nofollow" href="http://r4ds.had.co.nz/">R for Data Science</a></strong>: A free book that thoroughly covers the “tidyverse”. A prerequisite for maximizing your abilities with <code>tidyquant</code>.</p>
</li>
</ol>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.business-science.io/code-tools/2017/03/04/tidyquant-update-0-4-0.html"> business-science.io - Articles</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 title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/L7Z-Ayj6SXI"></a></div>