通常,这是R中下载10年联邦票据收益率的常用方法
library(quantmod)
getSymbols("DGS10",src='FRED')
Fed<-last(DGS10)
问题是检索到的价值比财政部网站上的价格提前一天 https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield
有没有办法解析上述网页以检索最近10年的国库券收益率?
答案 0 :(得分:1)
rvest
是一个很好的选择,因为它们是渲染表。另一个是:
library(httr)
library(XML)
year = 2016
URL = paste0("https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yieldYear&year=",year)
urldata <- httr::GET(URL)
data <- XML::readHTMLTable(rawToChar(urldata$content),
stringsAsFactors = FALSE)
# Finds html based list element w/daily data for the year
namesCheck <- c("Date","1 mo","3 mo","6 mo","1 yr","2 yr","3 yr","5 yr","7 yr","10 yr","20 yr","30 yr")
dataCheck <- NULL
for(i in 1:length(data)){
dataCheck[[i]] <- names(data[[i]])
}
## Returns appropriate frame
dataCheck <- which(unlist(lapply(1:length(dataCheck), function(i)
(dataCheck[[i]] == namesCheck)[1])) == TRUE)
data <- as.data.frame((data[dataCheck]))
names(data) <- gsub("NULL.","", names(data)) # Take out "NULL."
tail(data)
# Date 1.mo 3.mo 6.mo 1.yr 2.yr 3.yr 5.yr 7.yr 10.yr 20.yr 30.yr
# 245 12/22/16 0.42 0.51 0.65 0.87 1.22 1.54 2.04 2.36 2.55 2.86 3.12
# 246 12/23/16 0.42 0.52 0.65 0.87 1.22 1.54 2.04 2.35 2.55 2.86 3.12
# 247 12/27/16 0.50 0.51 0.66 0.89 1.28 1.58 2.07 2.37 2.57 2.88 3.14
# 248 12/28/16 0.48 0.53 0.62 0.90 1.26 1.55 2.02 2.32 2.51 2.83 3.09
# 249 12/29/16 0.39 0.47 0.62 0.85 1.22 1.49 1.96 2.30 2.49 2.82 3.08
# 250 12/30/16 0.44 0.51 0.62 0.85 1.20 1.47 1.93 2.25 2.45 2.79 3.06
答案 1 :(得分:1)
作为替代方案,Quandl.com通常会提供比FRED早的国债收益率更新。通过Quandl包可以轻松地将数据导入R.