<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-etf-country-exposure/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.rstudio.com/rviews/2017/02/08/reproducible-finance-with-r-etf-country-exposure/"> 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>Today, we are going to tackle a project that has long been on my wish list: a Shiny app to take a fund or portfolio, analyze its exposure to different countries, and display those exposures on a world map. Now you know how exciting my wishlists are.</p>
<p>Before describing our data importing/wrangling work here in the Notebook, it might be helpful to look at where we’re headed. The final Shiny app is <a target="_blank" rel="nofollow" href="http://colorado.rstudio.com:3939/content/277/">here</a>. This is similar to a <a target="_blank" rel="nofollow" href="http://colorado.rstudio.com:3939/content/206/">previous project</a> because we are building a leaflet map, shading it according to data added to the spatial dataframe, and including another HTML widget that is reponsive to the map. However, our current project differs in important ways and has a completely different use. </p>
<p>The previous project allowed a user to click a country on the map and view the time series of returns. Our current project will allow the user to choose an ETF and see how that ETF is invested in different countries by how a world map is shaded. </p>
<p>From a substantive perspective, this app helps visualize country risks instead of returns – indeed, it’s the first in our series that does not import stock returns in any way. From an R perspective, in our current project the map is the responsive object according to user inputs, whereas before, the dygraph was the responsive object according to user clicks on a map. They are related and require spatial dataframes, but very different.</p>
<p>If you looked closely at the Shiny app, you noticed that we do have a data object that is responsive to a map click: we display a datatable of companies held by the ETF in whatever country is clicked. That is, if a user chooses an ETF and sees by the shading that the ETF is allocated X% to China, the user can click on the map to see which company the ETF owns in China. That functionality is similar to the dygraphs functionality, except of course, we have to wire up a datatable and do some filtering by country instead of passing an xts object to dygraphs. The fulcrum will still be the clicked map shape. </p>
<p>Alright, that app is what we’re ultimately building but, by way of what we’ll do in this Notebook, here’s the roadmap. </p>
<p>First, we are going to grab the data for one fund, the MSCI Emerging Markets ETF. Note that we are not going to get return data over time. Instead, we just want a snapshot of the ETF holdings: its constituents, their weights, and their home countries. Our eventual app will include several ETFs, but we are going to work with one ETF in this Notebook, with the foreknowledge that we want to reuse our steps when it’s time to build the Shiny app. In short, let’s get it right for this Emerging Markets ETF, and then we can iterate over other ETFs when we move to building our Shiny app.</p>
<p>After we download the snapshot of the emerging markets fund, we will do some data wrangling and some country weight aggregation, and then merge that data to our spatial dataframe. Adding that data will depend on the ETF using the same country naming convention as our spatial dataframe, so we’ll pay attention to that in the wrangling process. </p>
<p>Once we add the data to our spatial dataframe, we will recycle some old code, build a leaflet map, and shade it according to the ETF’s country exposure. This is just a test to see how things will look in the Shiny app, and we can even play around with different color palettes to get things just right. </p>
<p>Once we have the map aesthetics sorted, we’ll turn to Part Two: displaying the details of each country holding. Really, this is just filtering our dataframe by country name – whatever country the user clicks – but we’ll go ahead and make sure things look how we want in this Notebook, and then pass that object to our app eventually.</p>
<p>Let’s get to it!</p>
<p>First, let’s grab the fund data from <a target="_blank" rel="nofollow" href="https://www.ishares.com/us/products/244048/ishares-core-msci-total-international-stock-etf">MSCI’s homepage</a>. We will use the read<em>csv() function from the readr package. We will title it emerging</em>markets_fund, since we’ll be pulling in other funds later. </p>
<p>Note that we have to skip the first 11 rows, which is why the ‘skip = 11’ argument is included. That’s because this csv file is loaded with oddly formatted data in the first 11 rows. If we don’t skip those 11 rows, this import will be totally unhelpful. The ‘import dataset’ button in the IDE saved me minutes/hours of frustration here! </p>
<p><iframe height="450px" width="1000px" src="https://beta.rstudioconnect.com/content/2498/finance_etf_block1.html"></iframe></p>
<p>Now, we have our fund data and the wrangling begins. We are actually going to use this initial object to create two other objects: one will be merged with the spatial dataframe, and one will be a standalone object to be loaded in our Shiny app. </p>
<p><iframe height="630px" width="1000px" src="https://beta.rstudioconnect.com/content/2499/finance_etf_block2.html"></iframe></p>
<p>Those country weights are striking! China + Korea + Taiwan comprise 51% of this fund. The fund is concentrated in economies that are probably closely linked. Perhaps that’s by design? Perhaps the inter-economy correlation isn’t as high as I believe? A cross-border investment or trade Shiny app would be helpful here. </p>
<p>It’s worth a second to consider the definition of ’emerging market’, a term that has become ubiquitous and has a know-it-when-we-see-it feel (if you’re not into political economy, feel free to skip this paragraph). The phrase was coined in 1981 by the World Bank’s Antoine Van Agtmael to help encourage investment in developing nations, as he felt that the phrase ‘Third World’ country was both distasteful and stifling to investors. Learn more <a target="_blank" rel="nofollow" href="http://www.economist.com/node/15906206">here</a>. Today, the phrase connotes an economy that is growing and transitioning from developing to developed, though some commentators include a political transition as well. Since we are working with an MSCI fund, we should consider their definition. It wasn’t easy to track down, but according to the <a target="_blank" rel="nofollow" href="http://lexicon.ft.com/Term?term=emerging-markets">Financial Times</a>, MSCI takes into account the number of listed companies of a certain size (an economic measure) and openness to foreign capital (a political measure).</p>
<p>Back to our task at hand: we have downloaded the fund data and gotten it into shape to be added to our shapefile. That process is the exact same as in our previous post, so before we do that, let’s use the original fund data to create one other object to store country-level detail on companies, weights and sectors. If that seems a bit confusing, head back to the Shiny app and click on a country. The datatable displays company names and details, and we need to create a dataframe to extract and hold that data. </p>
<p><iframe height="660px" width="1000px" src="https://beta.rstudioconnect.com/content/2500/finance_etf_block3.html"></iframe></p>
<p>This is what a user of our Shiny app will see upon clicking on Brazil; it is the country-level detail of how the fund is invested in Brazil. We will save that ‘EEM’ object in the .RDat file so it can be loaded into our Shiny app. </p>
<p>Okay, let’s go ahead and build that map of the world and add our fund country weights to it. This process is identical to how we did it <a target="_blank" rel="nofollow" href="https://www.rstudio.com/rviews/2016/12/14/reproducible-finance-with-r-pulling-and-displaying-etf-data/">here</a>, but we’ll go through the steps again.</p>
<p>First, let’s download the spatial dataframe. We will also use the <code>ms_simplify()</code> function from rmapshaper to reduce the size of the dataframe. This function will reduce the number of longitude and latitude coordinates used to build each country. It will make loading faster in our Shiny app, but won’t affect any of our logic.</p>
<p><iframe height="320px" width="1000px" src="https://beta.rstudioconnect.com/content/2501/finance_etf_block4.html"></iframe></p>
<p>Now, we will use the <code>merge()</code> function from the sp package to add our country weight data. Remember above where we made sure to use a consistent country naming convention when wrangling the ETF data? This is where it will come in handy – we use the ‘name’ column to perform the merge. After the merging, ETF exposures will be added for each country that has a match in the ‘name’ column. For those with no match, the EEM column will be filled with NA. </p>
<p><iframe height="3350px" width="1000px" src="https://beta.rstudioconnect.com/content/2502/finance_etf_block5.html"></iframe></p>
<p>We have our data added to the shapefile. Let’s go ahead and construct a map. First we’ll build a popup to show some detail, then we will create a green palette and a purple palette for no other reason than to see which is more visually appealing. </p>
<p><iframe height="230px" width="1000px" src="https://beta.rstudioconnect.com/content/2503/finance_etf_block6.html"></iframe></p>
<p>Let’s invoke leaflet! As before, we will use <code>layerId = ~name</code>. This is, again, massively important because when we create a Shiny app, we want to pass country names to our datatable and filter accordingly. The <code>layerId</code> is how we’ll do that: when a user clicks on a country, we capture the <code>layerId</code>, which is a country name that can be used for filtering. </p>
<p><iframe height="880px" width="1000px" src="https://beta.rstudioconnect.com/content/2504/finance_etf_block7.html"></iframe></p>
<p><iframe height="560px" width="1000px" src="https://beta.rstudioconnect.com/content/2505/finance_etf_block8.html"></iframe></p>
<p>Both those maps look good to me, but purple might be the way to go ultimately. That’s a decision for next time – see you then!</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/02/08/reproducible-finance-with-r-etf-country-exposure/"> 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/yeHt0259ir0"></a></div>