<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/reproducible-finance-with-r-interactive-maps-and-etf-analysis/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.rstudio.com/rviews/2017/03/08/reproducible-finance-with-r-interactive-maps-and-etf-analysis/"> RStudio</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>

<p>by Jonathan Regenstein</p>
<p>In this post, I’ll describe a <a target="_blank" rel="nofollow" href="http://colorado.rstudio.com:3939/content/277/">Shiny app</a> to support the Emerging Markets ETF Country Exposure analysis developed in a <a target="_blank" rel="nofollow" href="https://www.rstudio.com/rviews/2017/02/08/reproducible-finance-with-r-etf-country-exposure/">previous post</a></p>
<p>I have done some additional work and updated the analysis to include five ETFs in the app, whereas we originally imported data on 1 ETF. The new notebook is available <a target="_blank" rel="nofollow" href="http://colorado.rstudio.com:3939/content/322/Fund-Country-Weights-Multiple-ETFS-DataGrab.nb.html">here</a>. </p>
<p>As we start to build our Shiny app, we will assume that our underlying Notebook has been used to build the desired ETF data objects and spatial data frame, and that those have been saved in an appropriately named .RDat file. That’s an important assumption because the first thing we’ll do in the chunk below is load up that file.</p>
<p>A brief aside before we dive into the first code chunk: if you look at the source code for this app, you might notice that the code chunks have different ‘contexts’ – something we haven’t had in our previous flexdashboards. For example, the first chunk has ‘context = “data”‘, the next has ‘context = “render”, and so on. That is because I am taking advantage of a new run<em>time option called <a target="_blank" rel="nofollow" href="http://rmarkdown.rstudio.com/authoring_shiny_prerendered.html#overview">shinyprerendered</a></em> that is still under development. This run time allows your flexdashboard to “pre-render” certain objects, meaning they are knit prior to deployment. Here, we pre-render our data and our map object. </p>
<p>First, we’ll load up our data and build a map of the world, shaded by our original emerging markets fund. That is what a user will see when first arriving to the app. We can think of it as the default map and shading before the user has done anything. We didn’t have to use emerging markets as the default, but it was the first fund we imported in the Notebook. </p>
<p><iframe height="340px" width="1000px" src="https://beta.rstudioconnect.com/content/2586/etf_shiny_block1.html"></iframe></p>
<p>This code should look familiar. When we load the .RDat file, all of the saved objects go the global environment, and after the chunk has been run (or pre-rendered), the data and map object are available. </p>
<p>Now we want to set up some radio buttons so that the user can eventually change the shading of the map. This is pure UI work and is a simple selection of radio buttons. Note, in particular, how we give the user a choice of radio buttons with a nice intuitive label but then assign each button with a string value that matches the name of our fund objects. For example, we label the second button as “Global Infrastructure ETF”, which is what the user sees. But, upon choosing that button, we assign an input value equal to “infrastructure”. </p>
<p><iframe height="180px" width="1000px" src="https://beta.rstudioconnect.com/content/2587/etf_shiny_block2.html"></iframe></p>
<p>Go back and look at the Notebook and, no surprise, “infrastructure” is what we titled our infrastructure fund object, as well as the column in the spatial data frame that contains country weights for the infrastructure fund.</p>
<p>I will harp on this point again below but it was quite purposeful to choose one label – “infrastructure” – for both the fund object and the column in the spatial data frame. It allows us to use one radio button to reference both of those. The same convention holds true for the other funds: one label for the fund object and the spatial data frame column that holds country weights.</p>
<p>Let’s go ahead and render the default map to the user. </p>
<p><iframe height="90px" width="1000px" src="https://beta.rstudioconnect.com/content/2588/etf_shiny_block3.html"></iframe></p>
<p>Next, we build that default map in the “server” context. It will be shaded by whatever defaults we chose in the first chunk. In this case, we shade by the emerging market ETF country weights. </p>
<p><iframe height="110px" width="1000px" src="https://beta.rstudioconnect.com/content/2589/etf_shiny_block4.html"></iframe></p>
<p>After we have that map, finally, the fun part: we’re going to allow the user to change the shading of the map according to the radio buttons. But – but! – we don’t want to rebuild a map of the world upon each radio button selection. Instead, we want to change just the shading and the pop up, and we’ll use the <a target="_blank" rel="nofollow" href="https://rstudio.github.io/leaflet/shiny.html">leafletProxy() function</a> to accomplish that. </p>
<p>This will be a four step process: (1) use observeEvent() to capture the input from the radio button, (2) build a new palette based on that input, (3)build a new pop up based on that input, (4) display the new map which consists of the original map plus the new palette and pop up. </p>
<p>Have a read through the code chunk and then we’ll dissect it.</p>
<p><iframe height="720px" width="1000px" src="https://beta.rstudioconnect.com/content/2590/etf_shiny_block5.html"></iframe></p>
<ol>
<li>
<p>Inside the observeEvent function, capture the radio button selection with ‘input$fund’, and save it to an object called ‘indicator’. </p>
</li>
<li>
<p>Create a new palette based on the indicator called ‘newPal’, in the same way as we created the palette in the the first code chunk, except instead of explicitly passing in a fund like ’emerging_market’, pass in ‘indicator’, which has taken on a fund value from the radio button. </p>
</li>
<li>
<p>Create a new pop up based on the indicator using the same process. Call it newPopup and pass it ‘indicator’ instead of an explicit fund name. </p>
</li>
<li>
<p>Display the new map.<br>
a) Use leafletProxy() to build out that new map. We don’t want rebuild the whole map, so we tell leafletProxy() to start with the already built ‘fundMap’.<br>
b) Remove the layerId so we have a clean slate. Add back the provider tiles; then add back the polygons.<br>
c) To add a palette, we do two things: use ‘newPal’, which is based on the radio button, and use the column from the spatial data frame that has the same name as ‘indicator’ (that is, shade the palette by ‘world<em>fund</em>country_weights[[indicator]]’). We can do that because the column in the spatial data frame has the same name as the fund object. </p>
</li>
</ol>
<p>In the original <a target="_blank" rel="nofollow" href="http://colorado.rstudio.com:3939/content/322/Fund-Country-Weights-Multiple-ETFS-DataGrab.nb.html">the Notebook</a> where we created the data frame emerging<em>market</em>country<em>weights, we made a decision that makes interactive shading smoother: we named the column in the data frame that holds the country weights ’emerging</em>market’. Then we added that data frame to the spatial data frame and the spatial data frame got a new column called ’emerging_market’. </p>
<p>Notice that because he column in the spatial data frame emerging_market, has the same name as our fund object We can reference both from one selection of the radio button. Convenient! </p>
<p>Just to finish off the new map, we use ‘popup = newPopup’ to add the popup object we created from the radio input. Our app now has an interactively shaded map!</p>
<p>Before we head to happy hour, though, let’s finish up with a relatively simple addition to the app. When a user clicks a country, not only does the user see a popup but also country level detail in a data table. The data table shows the individual companies that the ETF holds in the clicked country, and the weight to each of those companies. </p>
<p>Again, the hard work was done in the Notebook. When we loaded the .RDat file, it contained an object for each fund, with that convenient label I have belabored, with a column for countries and a column for companies. All we need do is filter that object by the clicked country. Our friend eventReactive() again allows us to capture the clicked country’s id, and we subset by that id. For example, if a user clicks on China, we subset and display only the companies with ‘China’ in the country column. </p>
<p><iframe height="800px" width="1000px" src="https://beta.rstudioconnect.com/content/2591/etf_shiny_block6.html"></iframe></p>
<p>And, we’re done! Please note, however, that the techniques employed in this map can be used to map country exposures of mutual funds, bespoke stock/bond portfolios, currency and commodities holdings, etc. Enjoy!</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://www.rstudio.com/rviews/2017/03/08/reproducible-finance-with-r-interactive-maps-and-etf-analysis/"> RStudio</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/emk8i7alKvk"></a></div>