1

我想使用 API 获取财务数据。我这样做。

#load jsons
library("rjson")
json_file <- "https://api.coindesk.com/v1/bpi/currentprice/USD.json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

#get json content as data.frame
x = data.frame(json_data$time$updated,json_data$time$updatedISO,json_data$time$updateduk,json_data$bpi$USD)
x

但主要问题是信息每分钟都在变化,所以我无法收集历史。有没有办法让 R 每分钟(即以实时模式)独立连接到该站点并每分钟收集数据。所以收集的数据必须保存在C:/Myfolder. 有可能做到吗?

4

1 回答 1

2

像这样的东西可以做到

library("rjson")
json_file <- "https://api.coindesk.com/v1/bpi/currentprice/USD.json"

numOfTimes <- 2L # how many times to run in total
sleepTime <- 60L  # time to wait between iterations (in seconds)
iteration <- 0L
while (iteration < numOfTimes) {
  # gather data
  json_data <- fromJSON(paste(readLines(json_file), collapse=""))
  # get json content as data.frame
  x = data.frame(json_data$time$updated,json_data$time$updatedISO,json_data$time$updateduk,json_data$bpi$USD)
  # create file to save in 'C:/Myfolder' 
  # alternatively, create just one .csv file and update it in each iteration
  nameToSave <- nameToSave <- paste('C:/Myfolder/', 
                                     gsub('\\D','',format(Sys.time(),'%F%T')), 
                                    'json_data.csv', sep = '_')
  # save the file
  write.csv(x, nameToSave)
  # update counter and wait 
  iteration <- iteration + 1L
  Sys.sleep(sleepTime)
}    

请注意,这需要R打开一个会话(您可以创建一个.exe.bat文件并让它在后台运行)。

于 2019-01-16T12:39:10.630 回答