--- title: "A bit of advanced material on R" author: "K Foster" date: "July 13, 2016" output: html_document --- This gives a bit of a taste for some of the additional features of R. # Time Series in R In this course we will do very little time series analysis but for now I will demonstrate some of the stuff that R can easily do. First install some packages (your method might vary): ```{r eval=FALSE} install.packages("zoo") install.packages("lattice") install.packages("latticeExtra") install.packages("gdata") install.packages("quantmod") ``` ```{r message=FALSE} library(zoo) library(lattice) library(latticeExtra) library(gdata) library(quantmod) rm(list = ls(all = TRUE)) ``` Then get data from online - also a cool easy thing to do with R. Start with just getting data from FRED, which is easy with the quantmod package. ```{r message=FALSE} getSymbols(c('GDP','PCEC','GPDI','GCE','NETEXP'),src='FRED') ``` Alt can load it from other government data, ```{r} oilspot_url <- "http://www.eia.gov/dnav/pet/xls/PET_PRI_SPT_S1_D.xls" oilspot_dat <- read.xls(oilspot_url, sheet = 2, pattern = "Cushing") oilfut_url <- "http://www.eia.gov/dnav/pet/xls/PET_PRI_FUT_S1_D.xls" oilfut_dat <- read.xls(oilfut_url, sheet = 2, pattern = "Cushing, OK Crude Oil Future Contract 1") ``` Use R's built-in system for converting jumbles of letters and numbers into dates, ```{r} date_spot <- as.Date(oilspot_dat$Date, format='%b %d,%Y') date_fut <- as.Date(oilfut_dat$Date, format='%b %d,%Y') ``` Then R's "ts" for time-series and the "zoo" package. ```{r} wti_spot <- ts(oilspot_dat$Cushing..OK.WTI.Spot.Price.FOB..Dollars.per.Barrel., start = c(1986,2), frequency = 365) wti_fut1 <- ts(oilfut_dat$Cushing..OK.Crude.Oil.Future.Contract.1..Dollars.per.Barrel., start = c(1983,89), frequency = 365) wti_sp_dat <- zoo(wti_spot,date_spot) wti_ft_dat <- zoo(wti_fut1,date_fut) wti_spotfut <- merge(wti_sp_dat,wti_ft_dat, all=FALSE) ``` And plot the results, ```{r} plot(wti_spotfut, plot.type = "single", col = c("black", "blue")) ``` It's tough to see any difference, so try this ```{r} wti_2013 <- window(wti_spotfut, start = as.Date("2013-01-01"), end = as.Date("2013-12-31")) plot(wti_2013, plot.type = "single", col = c("black", "blue")) ``` If you like this publication, you can get fancier, ```{r} asTheEconomist(xyplot(wti_2013, xlab="Cushing WTI Spot Future Price")) ```