首页 > 解决方案 > 如何正确使用 lapply 和 Bloomberg Rblpapi 包来提取多组代码

问题描述

我不确定这是一个 lapply 问题还是关于 Rblpapi 语法的问题。Rblpapi 是一个很棒的包,用于通过 R 从Bloomberg 中提取数据。

因为不是每个人都可以访问彭博社,而且涉及到很多代码,这使得提供一个可重复的例子更具挑战性,所以希望有人可以提供一个没有 reprex 的解决方案。

当我使用以下代码时,我可以成功拉取我想要的数据:

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)

当我尝试使用所有代码提取数据以便不必pull_fx(tickers_here, my_field)为每组代码重复代码时,我尝试了以下操作:

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

其中tickers_all是具有所有股票代码分组的字符向量(例如,“rates_tickers_level”)。我为每个股票代码集合返回一个数据框列表,但列表中的每个数据框都是空的。因此,我无法判断我是否只是错误地使用了 lapply,或者我是否提供了错误的语法来使用 bdh 命令(Rblpapi 包)。

我期望的输出是一个数据帧列表,其中包含为每组代码提取的数据(即,“rates_level_df”、“equity_level_us_df”等包含在tickers_all字符向量中的数据帧。

感谢帮助!

标签: rbloombergrblpapi

解决方案


尝试mget使用tickers_all

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

要理解为什么我们需要mget在这里考虑这个简单的例子

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

tmp有变量ab它们以字符串形式存储在其中。要获得存储在其中的值 1 和 2,a我们b需要mget.

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

#$b
#[1] 2

推荐阅读