Seasonal Adjustment of Time Series using R
Installing Packages
In the first step the packages are installed using the following codes that are used in the coding.
#### INSTALLING PACKAGES ######
if (!require(pacman)) install.packages("pacman")## Loading required package: pacman
pacman::p_load(openxlsx,readxl,seasonal,dplR,BCDating,mFilter, ggplot2, utils,astsa,RColorBrewer)
###############################Setting the Working Directory
Set the working directory where the seasonally adjusted file needs to be downloaded.
#### setting working directory ######
setwd("~/")
###############################Seasonal Adjustment Code
Here I write the seasonal adjusment code for and data. The inputs of the code are- x: the time series vector in numeric class that will be seasonally adjusted. For example, GDP at constant price, price index, index of industrial production, etc.
- year: starting year of the data, i.e., x.
-
number: if it is quarterly, the quarter number or if monthly, it is month number. For example, For 2007 third quarter
year=2007, number=3and for 2010 October monthyear=2010, number=10. -
freq : it is a character
quarterlyormonthly. - filename : name of the file.csv in which the original and seasonally adjusted series needs to be stored.
seasadj=function(x,year,number, freq, filename="SeasAdj Data.csv"){
if(freq=="quarterly"){
xts=ts(x, start=c(year, number), frequency=4)
sdat=seas(xts)
sdy=sdat$data[,1]
SAData=data.frame(list(as.numeric(x),as.numeric(sdy)))
colnames(SAData)=c("Original Variable","Seasonally Adjusted Variable")
write.table(SAData, filename,na = "",row.names =FALSE,col.names = TRUE,append = FALSE,sep = ",")
tsplot(cbind(xts,sdy),gg=F,spaghetti=T,col=brewer.pal(n = 8, name = "Dark2"))
legend('topleft', col=brewer.pal(n = 8, name = "Dark2"), lwd=2, legend=c("Original", "Seasonally Adjusted"))
}
if(freq=="monthly"){
xts=ts(x, start=c(year, number), frequency=12)
sdat=seas(xts)
sdy=sdat$data[,1]
SAData=data.frame(list(as.numeric(x),as.numeric(sdy)))
colnames(SAData)=c("Original Variable","Seasonally Adjusted Variable")
write.table(SAData, filename ,na = "",row.names =FALSE,col.names = TRUE,append = FALSE,sep = ",")
tsplot(cbind(xts,sdy),gg=F,spaghetti=T,col=brewer.pal(n = 8, name = "Dark2"))
legend('topleft', col=brewer.pal(n = 8, name = "Dark2"), lwd=2, legend=c("Original", "Seasonally Adjusted"))
}
}Example
We have taken quarterly GDP data of India for seasonal adjustment.
#Quarterly Data
data_q=read.xlsx("https://mudulisilu.files.wordpress.com/2021/11/quarterly_data.xlsx")
seasadj(data_q$GDP,2006,3,"quarterly","IndiaGDP.csv")