R - Time Series

From Training Material
Jump to navigation Jump to search

Time Series Libraries

  • ts() from stats package
  • zoo
  • xts

Graphing Time Series

 s <- read.table("http://training-course-material.com/images/1/19/Sales-time-series.txt",h=T)
 s$Date <- as.Date(s$Date)
 head(s)
 plot(s)
 
 # Using build in ts object
 sts <- ts(s$Price,start=2002,deltat=1/12)
 plot(sts)

 # using xts
 install.packages("xts")
 library("xts")
 Price <- xts(s$Price,s$Date)
 head(Price)
 tail(Price)
 plot(Price)

Filtering xts series

 #12 to 16th observation 
 Price[12:16]

 #2nd to 4th in reverse order
 Price[4:2]

 #1st, 13th and 25th oveservation
 Price[c(1,13,25)]


 # Prices only in 2005
 Price["2005"]
 # Prices in Jan 2005
 Price["2005-01"]
 # Prices from 2005 Jan to 2007 March
 Price["2005-01/2007-03"]
 # Prices from the beginning of the data untill 2008
 Price["2005-01/2008"]

 
 # Price in first year
 first(Price,"year")
 
 first(Price,"2 months")
 last(Price,"3 quarters")

Getting rid of trend

# Shows the dates
index(Price)

# Returns the Prices value
coredata(Price)

#Plot the function
plot(coredata(Price) ~ index(Price),type="l",ylim=c(-3,13))

# Fit the trend line
m <- lm(coredata(Price) ~ index(Price))

# Validate the model
summary(m)

# Plot the trend
abline(m)

# The same as above
lines(m$fitted.values ~ index(Price))

# m$residuals = $fitted - index(Price)

# Plot the detrended values
lines(m$residuals ~ index(Price),type="l",col="blue")

# Plot relative detrended Prices
detrendPrice <- m$residuals
plot(xts(detrendPrice/mean(Price),index(Price)),type="l")

Exercise

Detrend the Sales volume and plot a chart