<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/visualize-your-portfolios-performance-and-generate-a-nice-report-with-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/visualize-your-portfolios-performance-and-generate-a-nice-report-with-r/"> R Programming – DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<ul></ul>
<p><strong>
<p>Categories</p>
<p></p></strong>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/category/visualizing-data/" title="Permanent Link toVisualizing Data" target="_blank">Visualizing Data</a></li>
</ol>
<p><strong>
<p>Tags</p>
<p></p></strong>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/tag/data-visualisation/" title="Permanent Link toData Visualisation" target="_blank">Data Visualisation</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/tag/dplyr/" title="Permanent Link todplyr" target="_blank">dplyr</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/tag/ggplot2/" title="Permanent Link toggplot2" target="_blank">ggplot2</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/tag/lares/" title="Permanent Link tolares" target="_blank">lares</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/tag/rstats/" title="Permanent Link toR Programming" target="_blank">R Programming</a></li>
</ol>
<p>There are few things more exciting than seeing your stocks values going up! I started investing last year in stocks and, like visualization and R lover, I couldn’t help but create some nice plots and functions to automate the process of watching it happen. </p>
<p>Some of you might already know the <code>lares</code> package; I’ve included these following ‘stocks family’ functions for some time now but today is the day in which I’ll share with you its nice useful outputs.<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2018/09/Visualize-your-Portfolios-Performance-and-Generate-a-Nice-Report-with-R-1.png?ssl=1" target="_blank"><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2018/09/Visualize-your-Portfolios-Performance-and-Generate-a-Nice-Report-with-R-1-1024x764.png?w=450&ssl=1" alt="" class="wp-image-17196" data-recalc-dims="1"></a></p>
<h2>Introduction</h2>
<p>The overall idea of these functions is to visualize your stocks and portfolio’s performance with a just a few lines of simple code. I’ve created individual functions for each of the calculations and plots, and some other functions that gather all of them into a single list of objects for further use. </p>
<p>On the other hand, the <code>lares</code> package is “my personal library used to automate and speed my everyday work on Analysis and Machine Learning tasks”. I am more than happy to share it with you for your personal use. Feel free to install, use, and comment on any of its code and functionalities and I’ll happy to help you with it. I have previously shared other uses of the library in other posts which might also interest you: <a rel="nofollow" href="https://datascienceplus.com/machine-learning-results-one-plot-to-rule-them-all/" target="_blank">Visualizing ML Results (binary)</a>, <a rel="nofollow" href="https://datascienceplus.com/machine-learning-results-in-r-one-plot-to-rule-them-all-part-2-regression-models/" target="_blank">Visualizing ML Results (continuous)</a> and <a rel="nofollow" href="https://datascienceplus.com/understanding-titanic-dataset-with-h2os-automl-dalex-and-lares-library/" target="_blank">AutoML to understand datasets</a>.</p>
<ul>
<li>NOTE 1: The following post was written by a <i>non-economist or professional investor</i>. I am open to your comments and technical corrections if needed. Glad to learn as always!</li>
<li>NOTE 2: I will be using the less customizable functions in this post so we can focus more on the outputs than in the coding part; but once again, feel free to use the functions and dive into the library to understand or change them!</li>
<li>NOTE 3: All currency units are USD ($).</li>
</ul>
<h2>Get Historical Values</h2>
<p>Let’s start by downloading a <a rel="nofollow" href="http://bit.ly/laresDummyP" target="_blank">dummy Excel file</a> which contains the recommended input format. In there, you will find three tabs which must be filled with your personal data: </p>
<ol>
<li>Portfolio: a summary of your investments. Each row represents a Stock and gathers some data from the other 2 tabs. The only inputs you have to fill are Stocks symbols or <a rel="nofollow" href="https://www.investopedia.com/terms/s/stocksymbol.asp" target="_blank">Tickers</a>, and a given category you wish to group them by (US Stocks, International, Recommended by Bernardo…)</li>
<li>Funds: here you will log any inputs or outputs of cash to your investment account. The required values are date and amount. There is an additional column for personal use to write notes and concepts if you want to.</li>
<li>Transactions: this last tab will be your purchase log. You should write which, when, how many, and by how much did you buy each of your stocks.</li>
</ol>
<p>Now we get to the fun part: R! Even though you might have already installed the <code>lares</code> library before, I strongly recommend to update it with the following command because I’ve created some of the gathering functions recently (yesterday):</p>
<pre>
devtools::install_github(&quot;laresbernardo/lares&quot;)
</pre>
<p><b>NOTE:</b> It may take a while to install the first time because I have some dependencies on other big libraries (like <code>h2o</code> ~123MB). But don’t worry, all of them are quite useful!</p>
<p>After you have filled your data (or you might just want to try the dummy’s), we import it. To quicken the process, we can use the <code>get_stocks</code> function which automatically imports all tabs from your file and returns a list with these three tables.</p>
<pre>
library(lares)
df &lt;- get_stocks(filename = &quot;dummyPortfolio.xlsx&quot;)
</pre>
<h2>Calculations and Plots</h2>
<p>To understand where we are now we need to understand where we were before. Let’s download our historical data from the first day we purchased each stock until today included. After that, we automatically process (<code>dplyr</code> mostly) all the data in such a way that we can get the variance for each day, percentages, growth, etc. Finally, some nice plots (<code>ggplot2</code> mostly) are created; even though they will have some redundant information, they will give us a wider perspective on our whole portfolio.</p>
<p>For further customization, there are three parameters I’ve added to the function: </p>
<ol>
<li>tax: What percentage of your dividends does Uncle Sam (or equivalent) bite?</li>
<li>expenses: How much does your bank or broker charges per transaction?</li>
<li>cash_fix: Literally, how much do you want to sum to your current cash balance to fix it.</li>
</ol>
<p>Sometimes, the results need a little adjustment because of dividends not yet published or a little difference in quoting timings. Usually, I wouldn’t use this parameter.</p>
<p>If your values are <code>tax = 30, expenses = 7, cash_fix = 0</code>, you can simply run the following code to process your portfolio’s data (if not, put them inside the function):</p>
<pre>
dfp &lt;- stocks_objects(df)
</pre>
<p><b>That’s it!</b> Now we have everything we need to visualize our stocks’ growth and portfolio’s performance. Let’s take a look at some of the plots created:</p>
<p>First, I’d like to see an overall daily plot for my portfolio’s ups and downs. It is relevant to see percentages for daily changes and for absolute changes so we don’t panic when a crazy-steep-roller-coaster-day happens. </p>
<pre>
print(dfp$p_portf_daily_change)
</pre>
<p>Will show the following plot:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2018/09/Visualize-your-Portfolios-Performance-and-Generate-a-Nice-Report-with-R-2.png?ssl=1" target="_blank"><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2018/09/Visualize-your-Portfolios-Performance-and-Generate-a-Nice-Report-with-R-2-1024x768.png?w=450&ssl=1" alt="" class="wp-image-17197" data-recalc-dims="1"></a></p>
<p>Then, I’d like to see a plot with all my stocks and its numbers, order by relevance (value). We can see all of our stock’s current data (grey boxes at the left), how many we have and their current value. Next to it, at each bar’s foot, the amount invested and their weighted average purchase price. And the head of the bars, we have the earnings metrics: how much have they grown/shrank in absolute currency numbers or percentages. We can also see a symbol, located at today’s total value, that represents if the value has increased or decreased compared to your total stock investment. </p>
<pre>
print(dfp$p_portf_stocks_change)
</pre>
<p>Will plot the following:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2018/09/Visualize-your-Portfolios-Performance-and-Generate-a-Nice-Report-with-R-1.png?ssl=1" target="_blank"><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2018/09/Visualize-your-Portfolios-Performance-and-Generate-a-Nice-Report-with-R-1-1024x764.png?w=450&ssl=1" alt="" class="wp-image-17196" data-recalc-dims="1"></a></p>
<p>The next cool plot we get shows the daily percentage change since the first stock you purchased for each Ticker. The grids will group and plot each stock into the category you defined at your Excel’s Portfolio tab. There are also some points added at those days you did transactions; with those you can evaluate in the future if it was or not a good moment to buy/sell (don’t worry: no one can predict the future!)</p>
<pre>
print(dfp$p_portf_stocks_histchange)
</pre>
<p>Will generate this plot:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2018/09/Visualize-your-Portfolios-Performance-and-Generate-a-Nice-Report-with-R-3.png?ssl=1" target="_blank"><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2018/09/Visualize-your-Portfolios-Performance-and-Generate-a-Nice-Report-with-R-3-1024x793.png?w=450&ssl=1" alt="" class="wp-image-17198" data-recalc-dims="1"></a></p>
<h2>Generate Report</h2>
<p>We can generate a nice HTML report with our portfolio’s performance using another quick command. It uses RMarkdown for rendering the plots and table into a single document. In addition to our prior plots, there is one more which shows the distribution of stocks into categories and a nice table with all the useful data summarizing everything up. </p>
<pre>
stocks_html(dfp)
</pre>
<p>Now you have a new nice HTML report created in your working directory. You can download this post’s report <a rel="nofollow" href="http://bit.ly/laresStocks" target="_blank">here</a>.</p>
<h2>Extra tip</h2>
<p><strong>RServer + cronR + mailR</strong>: RStudio in the cloud has indubitably been a great friend of mine for some time now. It automates daily tasks such as reporting, updating Google Sheets, sending mails, creating databases… and you only have to write the code once! It is a great way to get more independence from your company’s Tech Team. You could set a <code>cronR</code> job to send a daily or weekly report to your email automatically with this great tool.</p>
<p>Hope you guys enjoyed this post. If you have any doubts, comments, <a rel="nofollow" href="https://github.com/laresbernardo/lares/pulls" target="_blank">pull requests</a>, <a rel="nofollow" href="https://github.com/laresbernardo/lares/issues" target="_blank">issues</a>, just let me know! Please, do <a rel="nofollow" href="https://www.linkedin.com/in/laresbernardo/" target="_blank">LinkedIn</a> me if you want to connect. </p>
<p>Thanks for your time <img alt="😉" src="https://s.w.org/images/core/emoji/2.4/72x72/1f609.png" class="wp-smiley"></p>
<p><strong>
<p>Related Post</p>
<p></p></strong>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/exploring-san-francisco-bay-areas-bike-share-system/" title="Permanent Link toExploring San Francisco Bay Area’s Bike Share System" target="_blank">Exploring San Francisco Bay Area’s Bike Share System</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/blue-bikes-sharing-in-boston/" title="Permanent Link toAnalysis and Visualization of Blue Bikes Sharing in Boston" target="_blank">Analysis and Visualization of Blue Bikes Sharing in Boston</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/analysis-of-los-angeles-crime-with-r/" title="Permanent Link toAnalysis of Los Angeles Crime with R" target="_blank">Analysis of Los Angeles Crime with R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/mapping-the-prevalence-of-alzheimer-disease-mortality-in-the-usa/" title="Permanent Link toMapping the Prevalence of Alzheimer Disease Mortality in the USA" target="_blank">Mapping the Prevalence of Alzheimer Disease Mortality in the USA</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/animating-the-goals-of-the-world-cup-comparing-the-old-vs-new-gganimate-and-tweenr-api/" title="Permanent Link toAnimating the Goals of the World Cup: Comparing the old vs. new gganimate and tweenr API" target="_blank">Animating the Goals of the World Cup: Comparing the old vs. new gganimate and tweenr API</a></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="https://datascienceplus.com/visualize-your-portfolios-performance-and-generate-a-nice-report-with-r/"> R Programming – DataScience+</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/1DtK7KcUhxU" height="1"></a></div>