Search code examples
rbloombergrblpapi

How to use lapply correctly with Bloomberg Rblpapi package to pull multiple groups of tickers


I am not sure if this is an lapply question or a question about the Rblpapi syntax. Rblpapi is a fantastic package to use for extracting data from bloomberg via R.

Because not everyone has bloomberg access and because there are many tickers involved, this makes providing a reproducible example more challenging so hopefully someone can offer a solution without a reprex.

When I used the following code, I can successfully pull the data I want to:

library(Rblpapi)
library(tidyverse)

# Connect to Bloomberg  --------------------------------------------------------------------
  blpConnect()


# Specify beginning and end dates
beg_date <- as.Date("1927-12-30", format = "%Y-%m-%d")
end_date <- Sys.Date()


# Specify Bloomberg field to pull
my_field <- "PX_LAST"


# Call ticker script to load tickers
source(file.path(my_path, "tickers.R"), echo = FALSE)

 
# Create function to pull Bloomberg data
pull_fx <- function(input_tickers, input_field) {
  df <- as.data.frame(
    bdh(
      input_tickers,
      input_field,
      start.date               = beg_date,
      end.date                 = end_date,
      include.non.trading.days = TRUE
    )
  )
}

# Pull data  
rates_level_df         <- pull_fx(rates_tickers_level, my_field)
equity_level_us_df     <- pull_fx(equity_tickers_us_level, my_field)

When I attempt to pull the data with all of the tickers so I don't have to keep repeating the pull_fx(tickers_here, my_field) code for each set of tickers, I tried this:

list_df <- lapply(tickers_all, pull_fx, input_field = my_field)

where tickers_all is a character vector with all of the ticker groupings (e.g., "rates_tickers_level"). I get a list of data frames back for each ticker collection, but each data frame in the list is empty. As a result, I can't tell if I am just using lapply incorrectly or if I providing the wrong syntax for using lapply with the bdh command (Rblpapi package).

The output I was expecting was a list of data frames with the data pulled for each set of tickers (i.e., the "rates_level_df", "equity_level_us_df", etc. data frames that are included in the tickers_all character vector.

Appreciate the help!


Solution

  • Try using mget with tickers_all

    list_df <- lapply(mget(tickers_all), pull_fx, input_field = my_field)
    

    To understand why we need mget here consider this simple example

    a <- 1
    b <- 2
    tmp <- c('a', 'b')
    tmp
    #[1] "a" "b"
    

    tmp has variables a and b which are stored as strings in them. To get value 1 and 2 which are stored in a and b we need mget.

    mget(tmp)
    #$a
    #[1] 1
    
    #$b
    #[1] 2