Reproducible Finance with R: Interactive Maps and ETF Analysis

[This article was first published on RStudio, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

by Jonathan Regenstein

In this post, I’ll describe a Shiny app to support the Emerging Markets ETF Country Exposure analysis developed in a previous post

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 here.

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.

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 runtime option called shinyprerendered 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.

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.

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.

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”.

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.

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.

Let’s go ahead and render the default map to the user.

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.

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 leafletProxy() function to accomplish that.

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.

Have a read through the code chunk and then we’ll dissect it.

  1. Inside the observeEvent function, capture the radio button selection with ‘input$fund’, and save it to an object called ‘indicator’.

  2. 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.

  3. 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.

  4. Display the new map.
    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’.
    b) Remove the layerId so we have a clean slate. Add back the provider tiles; then add back the polygons.
    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 ‘worldfundcountry_weights[[indicator]]’). We can do that because the column in the spatial data frame has the same name as the fund object.

In the original the Notebook where we created the data frame emergingmarketcountryweights, we made a decision that makes interactive shading smoother: we named the column in the data frame that holds the country weights ’emergingmarket’. Then we added that data frame to the spatial data frame and the spatial data frame got a new column called ’emerging_market’.

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!

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!

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.

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.

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!

To leave a comment for the author, please follow the link and comment on their blog: RStudio.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)