Skip to content Skip to sidebar Skip to footer

Parsing 10-year Federal Note Yield From The Website

Typically, this is the commonly advised way in R to download the 10-year federal note yield library(quantmod) getSymbols('DGS10',src='FRED') Fed<-last(DGS10) The problem is tha

Solution 1:

rvest is a good option, as these are rendered tables. Another is:

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 in1: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
# 24512/22/160.420.510.650.871.221.542.042.362.552.863.12
# 24612/23/160.420.520.650.871.221.542.042.352.552.863.12
# 24712/27/160.500.510.660.891.281.582.072.372.572.883.14
# 24812/28/160.480.530.620.901.261.552.022.322.512.833.09
# 24912/29/160.390.470.620.851.221.491.962.302.492.823.08
# 25012/30/160.440.510.620.851.201.471.932.252.452.793.06

Solution 2:

As an alternative, Quandl.com usually offers updates earlier than FRED for Treasury yields. Data is easily imported into R via the Quandl package.

Post a Comment for "Parsing 10-year Federal Note Yield From The Website"