安装
更新R至3.3.0及以上版本,然后install.packages('seasonal')
即可,无须安装其他依赖包。
library(dplyr)
library(seasonal)
示例数据
以中国对美国1995-01至2016-04的月度出口数据为例,单位美元
export <- read.csv('C:/users/xuliheng/desktop/trade_adjust/exp_country.csv',stringsAsFactors=FALSE)
export_us <- select(export,time,exp = X1)
export_us <- filter(export_us,time>='1995-01',time<='2016-04')
head(export_us)
## time exp
## 1 1995-01 165235.7
## 2 1995-02 139748.4
## 3 1995-03 187067.3
## 4 1995-04 178912.8
## 5 1995-05 213668.4
## 6 1995-06 237262.9
读入月度平均汇率数据
exchange_rate <- read.csv('C:/users/xuliheng/desktop/trade_adjust/exchange_rate.csv',stringsAsFactors=FALSE)
exchange_rate <- filter(exchange_rate,time>='1995-01',time<='2016-04')
head(exchange_rate)
## time exchange
## 1 1995-01 8.4408
## 2 1995-02 8.4354
## 3 1995-03 8.4274
## 4 1995-04 8.4224
## 5 1995-05 8.3104
## 6 1995-06 8.3004
将出口数据单位调整至人民币
export_us$exp <- export_us$exp*exchange_rate$exchange
head(export_us)
## time exp
## 1 1995-01 1394721
## 2 1995-02 1178834
## 3 1995-03 1576491
## 4 1995-04 1506875
## 5 1995-05 1775670
## 6 1995-06 1969377
将出口数据转换成时间序列类型
exp <- ts(export_us$exp,start=c(1995,1),end=c(2016,4), frequency=12)
初始数据图
ts.plot(exp)
季节调整:考虑中国农历年
季节调整,考虑中国年因素
cny.ts <- genhol(cny, start = 0, end = 6, center = "calendar")
m1 <- seas(x = exp, xreg = cny.ts, regression.usertype = "holiday", x11 = "")
调整前后对比
ts.plot(exp,final(m1),col=c('black','red'),ylab='exp')
legend('topleft',c('Raw','Adjust'),lty=1,col=c('black','red'))
另外一种季节调整方法
*# modeling complex holiday effects in Chinese exports to the US*
*# - positive pre-CNY effect*
*# - negative post-CNY effect*
pre_cny <- genhol(cny, start = -6, end = -1, frequency = 12, center = "calendar")
post_cny <- genhol(cny, start = 0, end = 6, frequency = 12, center = "calendar")
m2 <- seas(x = exp, x11 = "",xreg = cbind(pre_cny, post_cny), regression.usertype = "holiday",x11 = list())
ts.plot(final(m1),final(m2),col=c('black','red'),ylab='exp')
legend('topleft',c('Adjust1','Adjust2'),lty=1,col=c('black','red'))