#A function to extract date from FRED. Assumes the date is either annual or monthly. 
FRED_GET <- function(FRED_SERIES_ID,NAME=NA,ST_DATE='1890-01-91',END_DATE=Sys.Date(),ANNUAL_DATA=TRUE){
	NAME <- ifelse(is.na(NAME),FRED_SERIES_ID,NAME)
	DATA_TIME_FRAME <- ifelse(ANNUAL_DATA,"Annual","Monthly")
	URL <- paste0('https://fred.stlouisfed.org/graph/fredgraph.csv?bgcolor=%23ebf3fb&chart_type=line&drp=0&fo=open%20sans&graph_bgcolor=%23ffffff&height=450&mode=fred&recession_bars=off&txtcolor=%23444444&ts=12&tts=12&width=827&nt=0&thu=0&trc=0&show_legend=no&show_axis_titles=no&show_tooltip=no&id=',FRED_SERIES_ID,'&scale=left&cosd=',ST_DATE,'&coed=',END_DATE,'&line_color=%230073e6&link_values=false&line_style=solid&mark_type=none&mw=3&lw=3&ost=-99999&oet=99999&mma=0&fml=a&fq=',DATA_TIME_FRAME,'&fam=avg&fgst=lin&fgsnd=2020-02-01&line_index=1&transformation=lin&vintage_date=',END_DATE,'&revision_date=',END_DATE,'&nd=',END_DATE)
	DATA <- read_csv(URL)
	DATA <- DATA[which(!is.na(DATA[,2] )),]
	colnames(DATA)[2] <- NAME
	if(ANNUAL_DATA){
		colnames(DATA)[1] <- "YEAR"
		DATA$YEAR <- year(DATA$YEAR)
	}else{
		colnames(DATA)[1] <- "DATE"
	}
	return(DATA)
}

CPI_ADJUST <- function(DATA){
	CPI <- FRED_GET("CPIAUCSL") %>% filter(!is.na(CPIAUCSL))
	CPI$CPI_ADJ <- as.numeric(CPI[which.max(CPI$YEAR),2])/CPI$CPIAUCSL
	CPI <- 	CPI %>% select(-"CPIAUCSL")
	DATA <- DATA %>% left_join(CPI)
	DATA[,2] <- DATA[,2]*DATA[,"CPI_ADJ"]
	DATA <-  DATA%>% select(-"CPI_ADJ")
	return(DATA)
}
