IB Special: Logo Realigning in R

Inspired by a tweet from yyc_sem, I though it was time to delve into a topic near and dear to any of us who have had to realign logos oh so perfectly on a page.

Nestled within the highcharter package in R, there are modules that allow us to manipulate points, with additional functionality to add images as markers, so I am going to combine the two and probably give myself a few flashbacks in the process.


Follow my blog

Setup

As always, here are the packages I am going to need to have installed to make this work.

  1. tidyverse – Mainly stringr and dplyr, but I am tired of writing all the packages separately. Just install the whole thing already.
  2. tidyquant – Core financial functions in R. Allows the user to pull things like share price, intraday if you sign up for Tiingo.
  3. highcharter – My favorite graphing library in R. To get all of the functionality, you need to install the development version (the instructions are in the website).
  4. knitr (optional) – If I were to be using exclusively gif or jpg and wanted better control over resizing the logos, I will use this package. I am using mostly svg files from the web for this tutorial so will not be using it here (but sadly is also why some of the logos appear squished). Basically everywhere you see .x, replace it with knitr::image_uri(.x), though the image has to be stored in either a temporary or permanent file location on your computer. For some reason this doesn’t work with image url links.

I also want to head over to Tiingo and sign up for free. This gives you the ability to download various financial data, including intraday share prices and is the source of all financial data in this blog post.


First One

In this portion, I will just pull some data from Tiingo and show the functionality. The suite of financial data outside of share price is not that robust, so I just grabbed Market Cap and Debt To Equity for the 13 biggest shale names. I also went and did the hard work of finding the logo links for you too, though it isn’t exactly rocket science.


Data Table

I will set up a tibble, which is basically just a table in R.

library(tidyverse)
library(tidyquant)
library(highcharter)

#Load the Data
df2 <- tibble(
  ticker = c("COP", "EOG", "PXD", "OXY", "HES", 
             "FANG", "COG", "CLR", "DVN", "MRO", 
             "XEC", "EQT", "OVV"),
  mc = c(42.94, 
         29.73, 19.88, 18.68, 
         16.58, 8.96, 7.31, 7.19, 6.3, 5.72, 4.3, 
         4.17, 4.1),
  d2e = c(0.5, 0.3, 0.3, 2,
          1.51, 0.63, 0.55, 0.92, 
          1.5, 0.54, 1.5, 0.64, 1.87),
  url1 = c("https://upload.wikimedia.org/wikipedia/commons/0/0c/ConocoPhillips_Logo.svg", 
          "https://upload.wikimedia.org/wikipedia/commons/c/c7/EOG_Resources_logo.svg", 
          "https://upload.wikimedia.org/wikipedia/commons/6/62/Pioneer_Natural_Resources_logo.svg", 
          "https://upload.wikimedia.org/wikipedia/commons/3/37/Occidental-Petroleum-Logo.svg", 
          "https://upload.wikimedia.org/wikipedia/commons/5/58/Hess_Corporation_Logo.svg", 
          "https://businessintexas.com/wp-content/uploads/2020/06/diamondback-Energy-logo.jpg", 
          "https://upload.wikimedia.org/wikipedia/commons/d/d3/Cabot_Corporation_Logo.svg", 
          "https://upload.wikimedia.org/wikipedia/commons/3/34/ContRes.svg", 
          "https://upload.wikimedia.org/wikipedia/commons/6/67/Devon-Energy-Logo.svg", 
          "https://upload.wikimedia.org/wikipedia/commons/b/bd/Marathon_Oil_logo.svg", 
          "https://mma.prnewswire.com/media/220288/cimarex_energy_co_logo.jpg", 
          "https://upload.wikimedia.org/wikipedia/en/5/51/EQT_logo.png", 
          "https://pbs.twimg.com/profile_images/1221057214368165889/xzvuWDwn_400x400.png"
)

#Convert Debt to Equity to Percentage
df2$d2e <- df2$d2e*100  


This was all pretty straightforward as all I am doing is uploading the stock tickers, the Market Cap in billions (mc), the Debt to Equity Ratio (d2e) and the url of each logo. Most are svg formats, but you can see there are three that are in png format as I couldn’t find a quick svg for them. Works the same, but svg images scale better than png when you change the page size. I also convert debt to equity to percentage.


Image Conversion

In order to keep myself from copy-pasting each individual line into the graph and defining the marker, I can actually set up the image marker within the tibble. This will allow me to write one line of code for the image when I plot it in highcharter.

df2 <- df2 %>% 
    mutate(
      marker = 
                       map(url1, ~ list(symbol = str_glue("url({data_uri})", data_uri = .x )))
                       
    )

Essentially, I define a marker, and then create a list item for each row that contains the symbol definition. The url({data_uri}) portion just takes your .x (which is the url1 you define right after map( and puts it into the format needed for highcharts to convert it to an image on the screen. And in case you forgot, url1 is the link to the image we defined in the tibble.

There are actually other ways to do this step, but this works so let’s not reinvent the wheel.


Graph

Now I am ready for the first graph. I will post the code and then explain.

#Define basic color scheme.
cols <- c('#0D1540', '#06357a', '#00a4e3', '#adafb2',
 '#a31c37', '#d26400', '#eaa814', '#5c1848', '#786592',
 '#ff4e50', '#027971', '#008542', '#5c6d00')

  
highchart() %>%
    hc_add_series(
      df2,
      "scatter",
      hcaes(mc, d2e, size = 10),
      name = "Operator",
      maxSize = 75,
      cursor = "move",
      dragDrop = list(
        draggableX = TRUE,
        draggableY = TRUE
      ), showInLegend = F
    )  %>% 
    hc_add_dependency("modules/draggable-points.js") %>%
    hc_xAxis(min = 0, max = 50,
             title = list(text = 'Market Cap, In Billions',
                          style = list(fontSize = '15pt', fontFamily = 'Arial', color = cols[1])),
             labels = list(format = '${value}bn', 
                           style = list(fontSize = '12pt', fontFamily = 'Arial', color = cols[1])))%>%
    hc_yAxis(min = 0, max = 250, gridLineColor = 'transparent', 
             title = list(text = 'Debt to Equity %',
                          style = list(fontSize = '15pt', fontFamily = 'Arial', color = cols[1])),
             labels = list(format = '{value}%',
                           style = list(fontSize = '12pt', fontFamily = 'Arial', color = cols[1]))) %>%
    hc_title(text = 'Market Cap vs Debt to Equity',
             style = list(fontSize = '20pt', fontFamily = 'Arial', color = cols[1]), align = 'left')%>%
    hc_subtitle(text = 'Source: Tiingo 01/29/2021',
             style = list(fontSize = '14pt', fontFamily = 'Arial', color = cols[3]), align = 'left')

Steps are separated by the %>% sign in R.

  1. The first line defines the color scheme to use, which may or may not have been lifted from an employer at some point in my life. I do like the scheme so I’ve kept it.
  2. Call a blank highchart().
  3. Add our data series. First we load df2 (our tibble), we define a graph type of ‘scatter’, define the x-y within hcaes(), as well as the size of our bubble. I used a static number so as to keep all the bubbles the same size, though you could use one of the values in the tibble to make them bigger or smaller based on relative size. maxSize defines how big the largest bubbles will appear in the chart. The rest of this section are needed to define the movement of our image; ie is it draggable in both directions and can it move. I also disable the legend for this series.
  4. To add the dragging module in highcharts we need to add a dependency.
  5. The rest of the lines are for styling the axes and adding a title/subtitle. Play around with it a bit and you’ll figure it out.

And voila, we have it.

Figure 1: Market Cap vs Debt to Equity for Largest Shale Players

As you can see when messing with the graph, you can move the images around however you like so as to avoid crowding. And if you are in RStudio (I mean you probably should be), you can download this image in whatever size you want as an image.

For you excel jockeys who spend time arrange logos on the page, perhaps this can be helpful to you once you start journeying in to code. I’ve certainly used it extensively in the past.


Now for a bit of fun….

As anyone not living on a rock is aware, investors have decided a struggling retailer who sells used video games is now one of the hottest stocks to own in the market (ie GameStop). Let’s play around with tidyquant and combine that functionality with the above workflow to take a jab at our beloved Energy Universe.


Intraday Stock Data

If you signed up for Tiingo, you can go to your settings and grab the API key. This allows me to programatically grab intrady share prices in R. Let’s look at GME since January 20th.

tiingo_api_key('xxxxxxxxxxxxxxxxx')

gme <- tq_get(c('GME'),
                get = "tiingo.iex",
                from   = "2021-01-20",
                to     = "2021-01-30",
                resample_frequency = "5min")

  gme$marketCap <- round(gme$close*69750000/1000000000, 2)

Once I download the share price data, I will convert that to Market Cap by multiplying by Shares Outstanding. I will then adjust it to billions to match my previous dataset.

Next, I am going to add the median date of that dataset to my original tibble. I also need to convert it to timestamp for plotting with highcharts. The exact date doesn’t really matter, as I am just going to move logos around after.

  df2$dateT <- datetime_to_timestamp(median(gme$date))

Graph

Now I am going to plot it up.

  highchart() %>% hc_colors(cols[2]) %>%
    hc_add_dependency("modules/draggable-points.js")%>%
    hc_add_series(
      df2,
      "scatter",
      hcaes(dateT, mc, size = 10),
      name = "Operator",
      maxSize = 50,
      cursor = "move",
      dragDrop = list(
        draggableX = TRUE,
        draggableY = FALSE
      ), showInLegend = F,
      tooltip = list(pointFormat = 
                       "<b>Company:</b> {point.ticker}<br>
                               <b>Market Cap:</b> ${point.y} bn<br>
                               <b>Debt to Equity:</b> {point.d2e}%")
    )%>%
    hc_add_series(gme, type = 'line',
                  hcaes(x = datetime_to_timestamp(date), y = marketCap), 
                  showInLegend = F,
                  color = cols[3],
                  tooltip = list(pointFormat = 
                                   "<b>Company:</b> GME<br>
                               <b>Date:</b> {point.date}<br>
                               <b>Market Cap:</b> ${point.y} bn")) %>%
    hc_xAxis(type = 'datetime', dateTimeLabelFormats = list(day = '%m-%d')) %>%
    hc_yAxis(reversed = F, gridLineColor = 'transparent', min = 0, max = 50,
             title = list(text = 'Market Cap (US$bn)', 
                          style = list(fontSize = '14pt',
                                       fontFamily = 'Arial', 
                                       color =  cols[1], fontWeight = 'bold')),
             labels = list( style = list(fontSize = '12pt', 
                                         fontFamily = 'Arial',
                                         color =  cols[1], fontWeight = 'bold'))) %>%
    hc_chart(zoomType = 'x') %>%
    hc_title(text = 'GME Market Cap vs ShaleCo Market Cap (In Billions)', align = 'left') %>%
    hc_subtitle(text = 'Source: Tiingo (Shale Market Cap as of 01/29)', align = 'left') 

Once again, the steps are separated by %>%.

  1. Call the highchart() and define the color scheme with hc_colors(cols[2]). The 2 selects the second color of my color series and uses it for the share price.
  2. Add our logos. Similar to the previous graph, but this time I set the draggableY to False, as I want it to always be reflective of the actual Market Cap. I also add in a custom tooltip that pulls from the data in my tibble (point.d2e and point.ticker), or from my defined x and y (point.y). I also change my x/y call to hcaes(dateT, mc, size = 10). dateT is my x and mc is my y.
  3. Add the Market Cap over time from GME, with this series being a line instead of scatter. In this one I also show how to conver to timestamp within the graph definition. I also add another custom tooltip.
  4. The remaining lines are all styling, so feel free to play around with it. I do add hc_chart(zoomType = ‘x’) to allow the user to drag on the plot to see a custom time period.

And finally, we have an image we can play around with by dragging the shale company market caps over to reflect when GME value exceeded theirs over the last couple of weeks. Feel free to play around with the logos and move them where you like!

Figure 2: Market Cap for Largest Shale Players vs GME over the last two weeks


Summary

Hope you enjoyed this one and know that this is legitmately a method I’ve used in the past for arranging logos. Especially now that I make HTML-based Powerpoints with Rmarkdown. These are entirely interactive powerpoints and eventually I will show how to populate these. The functionality is truly awesome.

And if you enjoyed this, take a look at some of my other R tutorials.

Thanks!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: