r - 使用 auto.arima() 和 xreg 进行样本外预测

标签 r forecasting arima

我正在研究一个预测模型,其中我有从 2014 年到当前月份(2018 年 3 月)的月度数据。

我的部分数据是帐单列和报价金额列,例如 (为格式道歉)

年 - 季度 - 月 - 账单 - 报价
2014- 2014Q1-- 201401- 100-------------500
2014- 2014Q1-- 201402- 150-------------600
2014- 2014Q1-- 201403- 200-------------700

我用它来预测月销售额,并尝试将 xreg 与每月的报价数量结合使用。

我查看了下面的文章,但缺少一些东西来完成我想做的事情: ARIMA forecasting with auto.Arima() and xreg

问题:有人可以展示一个使用 xreg 预测 OUT OF SAMPLE 的例子吗?我知道,为了实现这一目标,您需要预测样本外的 xreg 变量,但我无法弄清楚如何将这些 future 值传入。

我在预测值后尝试使用 futurevalues$mean 之类的东西,但这没有用。

这是我的代码:

sales = read.csv('sales.csv')

# Below, I'm creating a training set for the models through 
#  December 2017 (48 months).
train = sales[sales$TRX_MON<=201712,]

# I will also create a test set for our data from January 2018 (3 months)
test = sales[sales$TRX_MON>201712,]

dtstr2 <- ts(train2, start=2014, frequency=12)
dtste2 <- ts(test2, start=2018, frequency=12)

fit2 <- auto.arima(dtstr2[,"BILLINGS"], xreg=dtstr2[,"QUOTES"])
fcast2 <- forecast(fit2, xreg=dtste2[,"QUOTES"], h=24)
fcast2

上面的代码有效,但只给出 3 个月的预测,例如

                  Point Forecast    Lo 80    Hi 80    Lo 95    Hi 95
Jan 2018          70                60       100      50       130
Feb 2018          80                70       110      60       140
Mar 2018          90                80       120      70       150

我搜索了尽可能多的博客和主题,以寻找使用 auto.arima 对 xreg 变量进行样本外预测的示例,但找不到任何这样做的。

有人可以帮忙吗?

非常感谢。

最佳答案

这是一个 MWE,用于对具有未知协变量的时间序列进行样本外预测。 这依赖于提供的数据for this question 以及@Raad 的出色回答。

library("forecast")

dta = read.csv("~/stackexchange/data/xdata.csv")[1:96,]
dta <- ts(dta, start = 1)

# to illustrate out of sample forecasting with covariates lets split the data
train <- window(dta, end = 90)
test <- window(dta, start = 91)

# fit model
covariates <- c("Customers", "Open", "Promo")
fit <- auto.arima(train[,"Sales"], xreg = train[, covariates])

根据测试数据预测

fcast <- forecast(fit, xreg = test[, covariates])

但是,如果我们还不知道客户的值(value)怎么办? 期望的目标是预测客户,然后使用这些预测 销售预测中的值。打开和促销都在控制之下 经理,因此将在预测中“固定”。

customerfit <- auto.arima(train[,"Customers"], xreg = train[, c("Open","Promo")])

我会尝试预测 2 周后,并假设没有促销事件。

newdata <- data.frame(Open = rep(c(1,1,1,1,1,1,0), times = 2),
                          Promo = 0)

customer_fcast <- forecast(customerfit, xreg = newdata)

# the values of customer are in `customer_fcast$mean`

newdata$Customers <- as.vector(customer_fcast$mean)

以与原始数据相同的顺序获取新数据列至关重要! forecast()位置

匹配回归量
sales_fcast <- forecast(fit, xreg = as.matrix(newdata)[,c(3,1,2)])
plot(sales_fcast)

reprex package 创建于 2018-03-29 (v0.2.0).

关于r - 使用 auto.arima() 和 xreg 进行样本外预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49562005/

相关文章:

r - Shiny 的 : variable height of renderplot

r - 如何在多层层次结构中使用 ‘hts’?

r - 如何指定预测中的最小或最大可能值?

r - 代表错误(1,n.ahead): invalid 'times' argument in R

r - 在 R 中按组执行 Arima 时,因子季节有新级别 4

在 R 中 reshape 表格 - 更好的方法?

algorithm - 天气预报算法多种多样

Python Auto ARIMA 模型无法正常工作

python - 从 ARIMA 中提取汇总值

r - 如何使用 gml 格式文件将 igraph 边缘属性设置为字符串?