| Title: | Forecasting Functions for Time Series and Linear Models |
|---|---|
| Description: | Methods and tools for displaying and analysing univariate time series forecasts including exponential smoothing via state space models and automatic ARIMA modelling. |
| Authors: | Rob Hyndman [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-2140-5352>), George Athanasopoulos [aut] (ORCID: <https://orcid.org/0000-0002-5389-2802>), Christoph Bergmeir [aut] (ORCID: <https://orcid.org/0000-0002-3665-9021>), Gabriel Caceres [aut] (ORCID: <https://orcid.org/0000-0002-2947-2023>), Leanne Chhay [aut], Kirill Kuroptev [aut], Maximilian Mücke [aut] (ORCID: <https://orcid.org/0009-0000-9432-9795>), Mitchell O'Hara-Wild [aut] (ORCID: <https://orcid.org/0000-0001-6729-7695>), Fotios Petropoulos [aut] (ORCID: <https://orcid.org/0000-0003-3039-4955>), Slava Razbash [aut], Earo Wang [aut] (ORCID: <https://orcid.org/0000-0001-6448-5260>), Farah Yasmeen [aut] (ORCID: <https://orcid.org/0000-0002-1479-5401>), Federico Garza [ctb], Daniele Girolimetto [ctb], Ross Ihaka [ctb, cph], R Core Team [ctb, cph], Daniel Reid [ctb], David Shaub [ctb], Yuan Tang [ctb] (ORCID: <https://orcid.org/0000-0001-5243-233X>), Xiaoqian Wang [ctb], Zhenyu Zhou [ctb] |
| Maintainer: | Rob Hyndman <[email protected]> |
| License: | GPL-3 |
| Version: | 9.0.2.9000 |
| Built: | 2026-06-01 23:07:21 UTC |
| Source: | https://github.com/robjhyndman/forecast |
Returns range of summary measures of the forecast accuracy. If x is
provided, the function measures test set forecast accuracy
based on x - f. If x is not provided, the function only produces
training set accuracy measures of the forecasts based on
f["x"] - fitted(f). All measures are defined and discussed in Hyndman
and Koehler (2006).
## S3 method for class 'forecast' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'mforecast' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'fc_model' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'Arima' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'lm' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'ts' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'numeric' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...)## S3 method for class 'forecast' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'mforecast' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'fc_model' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'Arima' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'lm' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'ts' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...) ## S3 method for class 'numeric' accuracy(object, x, test = NULL, d = NULL, D = NULL, ...)
object |
An object of class |
x |
An optional numerical vector containing actual values of the same
length as object, or a time series overlapping with the times of |
test |
Indicator of which elements of |
d |
An integer indicating the number of lag-1 differences to be used for the denominator in MASE calculation. Default value is 1 for non-seasonal series and 0 for seasonal series. |
D |
An integer indicating the number of seasonal differences to be used for the denominator in MASE calculation. Default value is 0 for non-seasonal series and 1 for seasonal series. |
... |
Additional arguments depending on the specific method. |
The measures calculated are:
ME: Mean Error
RMSE: Root Mean Squared Error
MAE: Mean Absolute Error
MPE: Mean Percentage Error
MAPE: Mean Absolute Percentage Error
MASE: Mean Absolute Scaled Error
ACF1: Autocorrelation of errors at lag 1.
By default, the MASE calculation is scaled using MAE of training set naive
forecasts for non-seasonal time series, training set seasonal naive forecasts
for seasonal time series and training set mean forecasts for non-time series data.
If f is a numerical vector rather than a forecast object, the MASE
will not be returned as the training data will not be available.
See Hyndman and Koehler (2006) and Hyndman and Athanasopoulos (2014, Section 2.5) for further details.
Matrix giving forecast accuracy measures.
Rob J Hyndman
Hyndman, R.J. and Koehler, A.B. (2006) "Another look at measures of forecast accuracy". International Journal of Forecasting, 22(4), 679-688.
Hyndman, R.J. and Athanasopoulos, G. (2018) "Forecasting: principles and practice", 2nd ed., OTexts, Melbourne, Australia. Section 3.4 "Evaluating forecast accuracy". https://otexts.com/fpp2/accuracy.html.
fit1 <- rwf(EuStockMarkets[1:200, 1], h = 100) fit2 <- meanf(EuStockMarkets[1:200, 1], h = 100) accuracy(fit1) accuracy(fit2) accuracy(fit1, EuStockMarkets[201:300, 1]) accuracy(fit2, EuStockMarkets[201:300, 1]) plot(fit1) lines(EuStockMarkets[1:300, 1])fit1 <- rwf(EuStockMarkets[1:200, 1], h = 100) fit2 <- meanf(EuStockMarkets[1:200, 1], h = 100) accuracy(fit1) accuracy(fit2) accuracy(fit1, EuStockMarkets[201:300, 1]) accuracy(fit2, EuStockMarkets[201:300, 1]) plot(fit1) lines(EuStockMarkets[1:300, 1])
The function Acf computes (and by default plots) an estimate of the
autocorrelation function of a (possibly multivariate) time series. Function
Pacf computes (and by default plots) an estimate of the partial
autocorrelation function of a (possibly multivariate) time series. Function
Ccf computes the cross-correlation or cross-covariance of two
univariate series.
Acf( x, lag.max = NULL, type = c("correlation", "covariance", "partial"), plot = TRUE, na.action = na.contiguous, demean = TRUE, ... ) Pacf( x, lag.max = NULL, plot = TRUE, na.action = na.contiguous, demean = TRUE, ... ) Ccf( x, y, lag.max = NULL, type = c("correlation", "covariance"), plot = TRUE, na.action = na.contiguous, ... ) taperedacf( x, lag.max = NULL, type = c("correlation", "partial"), plot = TRUE, calc.ci = TRUE, level = 95, nsim = 100, ... ) taperedpacf(x, ...)Acf( x, lag.max = NULL, type = c("correlation", "covariance", "partial"), plot = TRUE, na.action = na.contiguous, demean = TRUE, ... ) Pacf( x, lag.max = NULL, plot = TRUE, na.action = na.contiguous, demean = TRUE, ... ) Ccf( x, y, lag.max = NULL, type = c("correlation", "covariance"), plot = TRUE, na.action = na.contiguous, ... ) taperedacf( x, lag.max = NULL, type = c("correlation", "partial"), plot = TRUE, calc.ci = TRUE, level = 95, nsim = 100, ... ) taperedpacf(x, ...)
x |
A univariate or multivariate (not Ccf) numeric time series object or a numeric vector or matrix. |
lag.max |
Maximum lag at which to calculate the acf. Default is $10*log10(N/m)$ where $N$ is the number of observations and $m$ the number of series. Will be automatically limited to one less than the number of observations in the series. |
type |
Character string giving the type of acf to be computed. Allowed
values are |
plot |
logical. If |
na.action |
Function to handle missing values. Default is
|
demean |
Should covariances be about the sample means? |
... |
Additional arguments passed to the plotting function. |
y |
A univariate numeric time series object or a numeric vector. |
calc.ci |
If |
level |
Percentage level used for the confidence intervals. |
nsim |
The number of bootstrap samples used in estimating the confidence intervals. |
The functions improve the stats::acf(), stats::pacf() and stats::ccf()
functions. The main differences are that Acf does not plot a spike at lag
0 when type = "correlation" (which is redundant) and the horizontal axes
show lags in time units rather than seasonal units.
The tapered versions implement the ACF and PACF estimates and plots described in Hyndman (2015), based on the banded and tapered estimates of autocovariance proposed by McMurry and Politis (2010).
The Acf, Pacf and Ccf functions return objects
of class "acf" as described in stats::acf() from the stats
package. The taperedacf and taperedpacf functions return
objects of class "mpacf".
Rob J Hyndman
Hyndman, R.J. (2015). Discussion of “High-dimensional autocovariance matrices and optimal linear prediction”. Electronic Journal of Statistics, 9, 792-796.
McMurry, T. L., & Politis, D. N. (2010). Banded and tapered estimates for autocovariance matrices and the linear process bootstrap. Journal of Time Series Analysis, 31(6), 471-482.
stats::acf(), stats::pacf(), stats::ccf(), tsdisplay()
Acf(wineind) Pacf(wineind) ## Not run: taperedacf(wineind, nsim = 50) taperedpacf(wineind, nsim = 50) ## End(Not run)Acf(wineind) Pacf(wineind) ## Not run: taperedacf(wineind, nsim = 50) taperedpacf(wineind, nsim = 50) ## End(Not run)
An ARFIMA(p,d,q) model is selected and estimated automatically using the Hyndman-Khandakar (2008) algorithm to select p and q and the Haslett and Raftery (1989) algorithm to estimate the parameters including d.
arfima( y, drange = c(0, 0.5), estim = c("mle", "ls"), model = NULL, lambda = NULL, biasadj = FALSE, xreg = NULL, x = y, ... )arfima( y, drange = c(0, 0.5), estim = c("mle", "ls"), model = NULL, lambda = NULL, biasadj = FALSE, xreg = NULL, x = y, ... )
y |
a numeric vector or univariate time series of class |
drange |
Allowable values of d to be considered. Default of
|
estim |
If |
model |
Output from a previous call to |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
xreg |
Optionally, a numerical vector or matrix of external regressors,
which must have the same number of rows as |
x |
Deprecated. Included for backwards compatibility. |
... |
Other arguments passed to |
This function combines fracdiff::fracdiff() and
auto.arima() to automatically select and estimate an ARFIMA
model. The fractional differencing parameter is chosen first assuming an
ARFIMA(2,d,0) model. Then the data are fractionally differenced using the
estimated d and an ARMA model is selected for the resulting time series
using auto.arima(). Finally, the full ARFIMA(p,d,q) model is
re-estimated using fracdiff::fracdiff(). If estim = "mle",
the ARMA coefficients are refined using stats::arima().
A list object of S3 class fracdiff, which is described in
the fracdiff::fracdiff() documentation. A few additional objects
are added to the list including x (the original time series), and the
residuals and fitted values.
Rob J Hyndman and Farah Yasmeen
J. Haslett and A. E. Raftery (1989) Space-time Modelling with Long-memory Dependence: Assessing Ireland's Wind Power Resource (with discussion); Applied Statistics 38, 1-50.
Hyndman, R.J. and Khandakar, Y. (2008) "Automatic time series forecasting: The forecast package for R", Journal of Statistical Software, 26(3).
fracdiff::fracdiff(), auto.arima(), forecast.fracdiff().
library(fracdiff) x <- fracdiff.sim(100, ma = -0.4, d = 0.3)$series fit <- arfima(x) tsdisplay(residuals(fit))library(fracdiff) x <- fracdiff.sim(100, ma = -0.4, d = 0.3)$series fit <- arfima(x) tsdisplay(residuals(fit))
Largely a wrapper for the stats::arima() function in the stats
package. The main difference is that this function allows a drift term. It
is also possible to take an ARIMA model from a previous call to Arima
and re-apply it to the data y.
Arima( y, order = c(0, 0, 0), seasonal = c(0, 0, 0), xreg = NULL, include.mean = TRUE, include.drift = FALSE, include.constant = NULL, lambda = model$lambda, biasadj = attr(lambda, "biasadj"), method = c("CSS-ML", "ML", "CSS"), model = NULL, x = y, ... )Arima( y, order = c(0, 0, 0), seasonal = c(0, 0, 0), xreg = NULL, include.mean = TRUE, include.drift = FALSE, include.constant = NULL, lambda = model$lambda, biasadj = attr(lambda, "biasadj"), method = c("CSS-ML", "ML", "CSS"), model = NULL, x = y, ... )
y |
a numeric vector or univariate time series of class |
order |
a specification of the non-seasonal part of the ARIMA
model: the three integer components |
seasonal |
a specification of the seasonal part of the ARIMA
model, plus the period (which defaults to |
xreg |
Optionally, a numerical vector or matrix of external regressors,
which must have the same number of rows as |
include.mean |
Should the ARIMA model include a mean term? The default
is |
include.drift |
Should the ARIMA model include a linear drift term?
(i.e., a linear regression with ARIMA errors is fitted.) The default is
|
include.constant |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
method |
fitting method: maximum likelihood or minimize conditional sum-of-squares. The default (unless there are missing values) is to use conditional-sum-of-squares to find starting values, then maximum likelihood. Can be abbreviated. |
model |
Output from a previous call to |
x |
Deprecated. Included for backwards compatibility. |
... |
Additional arguments to be passed to |
The fitted model is a regression with ARIMA(p,d,q) errors
where is a vector of regressors at time and is an
ARMA(p,d,q) error process. If there are no regressors, and , then c
is an estimate of the mean of . For more information, see Hyndman &
Athanasopoulos (2018). For details of the estimation algorithm, see the
stats::arima() function in the stats package.
See the stats::arima() function in the stats package.
The additional objects returned are:
x |
The time series data |
xreg |
The regressors used in fitting (when relevant). |
sigma2 |
The bias adjusted MLE of the innovations variance. |
Rob J Hyndman
Hyndman, R.J. and Athanasopoulos, G. (2018) "Forecasting: principles and practice", 2nd ed., OTexts, Melbourne, Australia. https://OTexts.com/fpp2/.
auto.arima(), forecast.Arima().
library(ggplot2) WWWusage |> Arima(order = c(3, 1, 0)) |> forecast(h = 20) |> autoplot() # Fit model to first few years of AirPassengers data air.model <- Arima( window(AirPassengers, end = 1956 + 11 / 12), order = c(0, 1, 1), seasonal = list(order = c(0, 1, 1), period = 12), lambda = 0 ) plot(forecast(air.model, h = 48)) lines(AirPassengers) # Apply fitted model to later data air.model2 <- Arima(window(AirPassengers, start = 1957), model = air.model) # Forecast accuracy measures on the log scale. # in-sample one-step forecasts. accuracy(air.model) # out-of-sample one-step forecasts. accuracy(air.model2) # out-of-sample multi-step forecasts accuracy( forecast(air.model, h = 48, lambda = NULL), log(window(AirPassengers, start = 1957)) )library(ggplot2) WWWusage |> Arima(order = c(3, 1, 0)) |> forecast(h = 20) |> autoplot() # Fit model to first few years of AirPassengers data air.model <- Arima( window(AirPassengers, end = 1956 + 11 / 12), order = c(0, 1, 1), seasonal = list(order = c(0, 1, 1), period = 12), lambda = 0 ) plot(forecast(air.model, h = 48)) lines(AirPassengers) # Apply fitted model to later data air.model2 <- Arima(window(AirPassengers, start = 1957), model = air.model) # Forecast accuracy measures on the log scale. # in-sample one-step forecasts. accuracy(air.model) # out-of-sample one-step forecasts. accuracy(air.model2) # out-of-sample multi-step forecasts accuracy( forecast(air.model, h = 48, lambda = NULL), log(window(AirPassengers, start = 1957)) )
Returns time series of the regression residuals from a fitted ARIMA model.
arima.errors(object)arima.errors(object)
object |
An object containing a time series model of class |
This is a deprecated function
which is identical to residuals.Arima(object, type="regression")
Regression residuals are equal to the original data
minus the effect of any regression variables. If there are no regression
variables, the errors will be identical to the original series (possibly
adjusted to have zero mean).
A ts object
Rob J Hyndman
Returns the order of a univariate ARIMA or ARFIMA model.
arimaorder(object)arimaorder(object)
object |
An object of class |
A numerical vector giving the values , and of
the ARIMA or ARFIMA model. For a seasonal ARIMA model, the returned vector
contains the values , , , , , and
, where is the period of seasonality.
Rob J Hyndman
stats::ar(), auto.arima, Arima(), stats::arima(), arfima().
WWWusage |> auto.arima() |> arimaorder()WWWusage |> auto.arima() |> arimaorder()
Returns best ARIMA model according to either AIC, AICc or BIC value. The function conducts a search over possible models within the order constraints provided.
auto.arima( y, d = NA, D = NA, max.p = 5, max.q = 5, max.P = 2, max.Q = 2, max.order = 5, max.d = 2, max.D = 1, start.p = 2, start.q = 2, start.P = 1, start.Q = 1, stationary = FALSE, seasonal = TRUE, ic = c("aicc", "aic", "bic"), stepwise = TRUE, nmodels = 94, trace = FALSE, approximation = (length(x) > 150 || frequency(x) > 12), method = NULL, truncate = NULL, xreg = NULL, test = c("kpss", "adf", "pp"), test.args = list(), seasonal.test = c("seas", "ocsb", "hegy", "ch"), seasonal.test.args = list(), allowdrift = TRUE, allowmean = TRUE, lambda = NULL, biasadj = FALSE, parallel = FALSE, num.cores = 2, x = y, ... )auto.arima( y, d = NA, D = NA, max.p = 5, max.q = 5, max.P = 2, max.Q = 2, max.order = 5, max.d = 2, max.D = 1, start.p = 2, start.q = 2, start.P = 1, start.Q = 1, stationary = FALSE, seasonal = TRUE, ic = c("aicc", "aic", "bic"), stepwise = TRUE, nmodels = 94, trace = FALSE, approximation = (length(x) > 150 || frequency(x) > 12), method = NULL, truncate = NULL, xreg = NULL, test = c("kpss", "adf", "pp"), test.args = list(), seasonal.test = c("seas", "ocsb", "hegy", "ch"), seasonal.test.args = list(), allowdrift = TRUE, allowmean = TRUE, lambda = NULL, biasadj = FALSE, parallel = FALSE, num.cores = 2, x = y, ... )
y |
a numeric vector or univariate time series of class |
d |
Order of first-differencing. If missing, will choose a value based
on |
D |
Order of seasonal-differencing. If missing, will choose a value
based on |
max.p |
Maximum value of p. |
max.q |
Maximum value of q. |
max.P |
Maximum value of P. |
max.Q |
Maximum value of Q. |
max.order |
Maximum value of p+q+P+Q if model selection is not stepwise. |
max.d |
Maximum number of non-seasonal differences. |
max.D |
Maximum number of seasonal differences. |
start.p |
Starting value of p in stepwise procedure. |
start.q |
Starting value of q in stepwise procedure. |
start.P |
Starting value of P in stepwise procedure. |
start.Q |
Starting value of Q in stepwise procedure. |
stationary |
If |
seasonal |
If |
ic |
Information criterion to be used in model selection. |
stepwise |
If |
nmodels |
Maximum number of models considered in the stepwise search. |
trace |
If |
approximation |
If |
method |
fitting method: maximum likelihood or minimize conditional sum-of-squares. The default (unless there are missing values) is to use conditional-sum-of-squares to find starting values, then maximum likelihood. Can be abbreviated. |
truncate |
An integer value indicating how many observations to use in
model selection. The last |
xreg |
Optionally, a numerical vector or matrix of external regressors,
which must have the same number of rows as |
test |
Type of unit root test to use. See |
test.args |
Additional arguments to be passed to the unit root test. |
seasonal.test |
This determines which method is used to select the number of seasonal differences. The default method is to use a measure of seasonal strength computed from an STL decomposition. Other possibilities involve seasonal unit root tests. |
seasonal.test.args |
Additional arguments to be passed to the seasonal
unit root test.
See |
allowdrift |
If |
allowmean |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
parallel |
If |
num.cores |
Allows the user to specify the amount of parallel processes
to be used if |
x |
Deprecated. Included for backwards compatibility. |
... |
Additional arguments to be passed to |
The default arguments are designed for rapid estimation of models for many time series.
If you are analysing just one time series, and can afford to take some more time, it
is recommended that you set stepwise = FALSE and approximation = FALSE.
Non-stepwise selection can be slow, especially for seasonal data. The stepwise algorithm outlined in Hyndman & Khandakar (2008) is used except that the default method for selecting seasonal differences is now based on an estimate of seasonal strength (Wang, Smith & Hyndman, 2006) rather than the Canova-Hansen test. There are also some other minor variations to the algorithm described in Hyndman and Khandakar (2008).
Same as for Arima()
Rob J Hyndman
Hyndman, RJ and Khandakar, Y (2008) "Automatic time series forecasting: The forecast package for R", Journal of Statistical Software, 26(3).
Wang, X, Smith, KA, Hyndman, RJ (2006) "Characteristic-based clustering for time series data", Data Mining and Knowledge Discovery, 13(3), 335-364.
fit <- auto.arima(WWWusage) plot(forecast(fit, h = 20))fit <- auto.arima(WWWusage) plot(forecast(fit, h = 20))
autoplot takes an object of type ts or mts and creates
a ggplot object suitable for usage with stat_forecast.
## S3 method for class 'mts' autolayer(object, colour = TRUE, series = NULL, ...) ## S3 method for class 'msts' autolayer(object, series = NULL, ...) ## S3 method for class 'ts' autolayer(object, colour = TRUE, series = NULL, ...) ## S3 method for class 'ts' autoplot( object, series = NULL, xlab = "Time", ylab = deparse1(substitute(object)), main = NULL, ... ) ## S3 method for class 'mts' autoplot( object, colour = TRUE, facets = FALSE, xlab = "Time", ylab = deparse1(substitute(object)), main = NULL, ... ) ## S3 method for class 'msts' autoplot(object, ...) ## S3 method for class 'ts' fortify(model, data, ...)## S3 method for class 'mts' autolayer(object, colour = TRUE, series = NULL, ...) ## S3 method for class 'msts' autolayer(object, series = NULL, ...) ## S3 method for class 'ts' autolayer(object, colour = TRUE, series = NULL, ...) ## S3 method for class 'ts' autoplot( object, series = NULL, xlab = "Time", ylab = deparse1(substitute(object)), main = NULL, ... ) ## S3 method for class 'mts' autoplot( object, colour = TRUE, facets = FALSE, xlab = "Time", ylab = deparse1(substitute(object)), main = NULL, ... ) ## S3 method for class 'msts' autoplot(object, ...) ## S3 method for class 'ts' fortify(model, data, ...)
object |
Object of class |
colour |
If |
series |
Identifies the time series with a colour, which integrates well
with the functionality of |
... |
Other plotting parameters to affect the plot. |
xlab |
X-axis label. |
ylab |
Y-axis label. |
main |
Main title. |
facets |
If |
model |
Object of class |
data |
Not used (required for |
fortify.ts takes a ts object and converts it into a data frame
(for usage with ggplot2).
None. Function produces a ggplot graph.
Mitchell O'Hara-Wild
stats::plot.ts(), ggplot2::fortify()
library(ggplot2) autoplot(USAccDeaths) lungDeaths <- cbind(mdeaths, fdeaths) autoplot(lungDeaths) autoplot(lungDeaths, facets = TRUE)library(ggplot2) autoplot(USAccDeaths) lungDeaths <- cbind(mdeaths, fdeaths) autoplot(lungDeaths) autoplot(lungDeaths, facets = TRUE)
Produces a ggplot object of their equivalent Acf, Pacf, Ccf, taperedacf and taperedpacf functions.
## S3 method for class 'acf' autoplot(object, ci = 0.95, ...) ggAcf( x, lag.max = NULL, type = c("correlation", "covariance", "partial"), plot = TRUE, na.action = na.contiguous, demean = TRUE, ... ) ggPacf( x, lag.max = NULL, plot = TRUE, na.action = na.contiguous, demean = TRUE, ... ) ggCcf( x, y, lag.max = NULL, type = c("correlation", "covariance"), plot = TRUE, na.action = na.contiguous, ... ) ## S3 method for class 'mpacf' autoplot(object, ...) ggtaperedacf( x, lag.max = NULL, type = c("correlation", "partial"), plot = TRUE, calc.ci = TRUE, level = 95, nsim = 100, ... ) ggtaperedpacf(x, ...)## S3 method for class 'acf' autoplot(object, ci = 0.95, ...) ggAcf( x, lag.max = NULL, type = c("correlation", "covariance", "partial"), plot = TRUE, na.action = na.contiguous, demean = TRUE, ... ) ggPacf( x, lag.max = NULL, plot = TRUE, na.action = na.contiguous, demean = TRUE, ... ) ggCcf( x, y, lag.max = NULL, type = c("correlation", "covariance"), plot = TRUE, na.action = na.contiguous, ... ) ## S3 method for class 'mpacf' autoplot(object, ...) ggtaperedacf( x, lag.max = NULL, type = c("correlation", "partial"), plot = TRUE, calc.ci = TRUE, level = 95, nsim = 100, ... ) ggtaperedpacf(x, ...)
object |
Object of class |
ci |
coverage probability for confidence interval. Plotting of the confidence interval is suppressed if ci is zero or negative. |
... |
Other plotting parameters to affect the plot. |
x |
a univariate or multivariate (not Ccf) numeric time series object or a numeric vector or matrix. |
lag.max |
maximum lag at which to calculate the acf. |
type |
character string giving the type of acf to be computed. Allowed
values are |
plot |
logical. If |
na.action |
function to handle missing values. Default is
|
demean |
Should covariances be about the sample means? |
y |
a univariate numeric time series object or a numeric vector. |
calc.ci |
If |
level |
Percentage level used for the confidence intervals. |
nsim |
The number of bootstrap samples used in estimating the confidence intervals. |
If autoplot is given an acf or mpacf object, then an
appropriate ggplot object will be created.
ggtaperedpacf
A ggplot object.
Mitchell O'Hara-Wild
stats::plot.acf() Acf(), [stats::acf(), taperedacf()
library(ggplot2) ggAcf(wineind) wineind |> Acf(plot = FALSE) |> autoplot() ## Not run: wineind |> taperedacf(plot = FALSE) |> autoplot() ggtaperedacf(wineind) ggtaperedpacf(wineind) ## End(Not run) ggCcf(mdeaths, fdeaths)library(ggplot2) ggAcf(wineind) wineind |> Acf(plot = FALSE) |> autoplot() ## Not run: wineind |> taperedacf(plot = FALSE) |> autoplot() ggtaperedacf(wineind) ggtaperedpacf(wineind) ## End(Not run) ggCcf(mdeaths, fdeaths)
Produces a ggplot object of seasonally decomposed time series for objects of
class stl (created with stats::stl(), class seas (created with
seasonal::seas()), or class decomposed.ts (created with
stats::decompose()).
## S3 method for class 'decomposed.ts' autoplot(object, labels = NULL, range.bars = NULL, ...) ## S3 method for class 'stl' autoplot(object, labels = NULL, range.bars = TRUE, ...) ## S3 method for class 'StructTS' autoplot(object, labels = NULL, range.bars = TRUE, ...) ## S3 method for class 'seas' autoplot(object, labels = NULL, range.bars = NULL, ...) ## S3 method for class 'mstl' autoplot(object, ...)## S3 method for class 'decomposed.ts' autoplot(object, labels = NULL, range.bars = NULL, ...) ## S3 method for class 'stl' autoplot(object, labels = NULL, range.bars = TRUE, ...) ## S3 method for class 'StructTS' autoplot(object, labels = NULL, range.bars = TRUE, ...) ## S3 method for class 'seas' autoplot(object, labels = NULL, range.bars = NULL, ...) ## S3 method for class 'mstl' autoplot(object, ...)
object |
Object of class |
labels |
Labels to replace "seasonal", "trend", and "remainder". |
range.bars |
Logical indicating if each plot should have a bar at its
right side representing relative size. If |
... |
Other plotting parameters to affect the plot. |
Returns an object of class ggplot.
Mitchell O'Hara-Wild
seasonal::seas(), stats::stl(), stats::decompose(),
stats::StructTS(), stats::plot.stl().
library(ggplot2) co2 |> decompose() |> autoplot() nottem |> stl(s.window = "periodic") |> autoplot() ## Not run: library(seasonal) seas(USAccDeaths) |> autoplot() ## End(Not run)library(ggplot2) co2 |> decompose() |> autoplot() nottem |> stl(s.window = "periodic") |> autoplot() ## Not run: library(seasonal) seas(USAccDeaths) |> autoplot() ## End(Not run)
Plots historical data with multivariate forecasts and prediction intervals.
## S3 method for class 'mforecast' autoplot(object, PI = TRUE, facets = TRUE, colour = FALSE, ...) ## S3 method for class 'mforecast' autolayer(object, series = NULL, PI = TRUE, ...) ## S3 method for class 'mforecast' plot(x, main = paste("Forecasts from", unique(x$method)), xlab = "time", ...)## S3 method for class 'mforecast' autoplot(object, PI = TRUE, facets = TRUE, colour = FALSE, ...) ## S3 method for class 'mforecast' autolayer(object, series = NULL, PI = TRUE, ...) ## S3 method for class 'mforecast' plot(x, main = paste("Forecasts from", unique(x$method)), xlab = "time", ...)
object |
Multivariate forecast object of class |
PI |
If |
facets |
If |
colour |
If |
... |
additional arguments to each individual |
series |
Matches an unidentified forecast layer with a coloured object on the plot. |
x |
Multivariate forecast object of class |
main |
Main title. Default is the forecast method. For autoplot, specify a vector of titles for each plot. |
xlab |
X-axis label. For autoplot, specify a vector of labels for each plot. |
autoplot will produce an equivalent plot as a ggplot object.
Mitchell O'Hara-Wild
Hyndman and Athanasopoulos (2018) Forecasting: principles and practice, 2nd edition, OTexts: Melbourne, Australia. https://otexts.com/fpp2/
plot.forecast(), stats::plot.ts()
library(ggplot2) lungDeaths <- cbind(mdeaths, fdeaths) fit <- tslm(lungDeaths ~ trend + season) fcast <- forecast(fit, h = 10) plot(fcast) autoplot(fcast) carPower <- as.matrix(mtcars[, c("qsec", "hp")]) carmpg <- mtcars[, "mpg"] fit <- lm(carPower ~ carmpg) fcast <- forecast(fit, newdata = data.frame(carmpg = 30)) plot(fcast, xlab = "Year") autoplot(fcast, xlab = rep("Year", 2))library(ggplot2) lungDeaths <- cbind(mdeaths, fdeaths) fit <- tslm(lungDeaths ~ trend + season) fcast <- forecast(fit, h = 10) plot(fcast) autoplot(fcast) carPower <- as.matrix(mtcars[, c("qsec", "hp")]) carmpg <- mtcars[, "mpg"] fit <- lm(carPower ~ carmpg) fcast <- forecast(fit, newdata = data.frame(carmpg = 30)) plot(fcast, xlab = "Year") autoplot(fcast, xlab = rep("Year", 2))
The bagged model forecasting method.
baggedModel(y, bootstrapped_series = bld.mbb.bootstrap(y, 100), fn = ets, ...) baggedETS(y, bootstrapped_series = bld.mbb.bootstrap(y, 100), ...)baggedModel(y, bootstrapped_series = bld.mbb.bootstrap(y, 100), fn = ets, ...) baggedETS(y, bootstrapped_series = bld.mbb.bootstrap(y, 100), ...)
y |
A numeric vector or univariate time series of class |
bootstrapped_series |
bootstrapped versions of y. |
fn |
the forecast function to use. Default is |
... |
Other arguments passed to the forecast function. |
This function implements the bagged model forecasting method described in
Bergmeir et al. By default, the ets() function is applied to all
bootstrapped series. Base models other than ets() can be given by the
parameter fn. Using the default parameters, the function
bld.mbb.bootstrap() is used to calculate the bootstrapped series
with the Box-Cox and Loess-based decomposition (BLD) bootstrap. The function
forecast.baggedModel() can then be used to calculate forecasts.
baggedETS is a wrapper for baggedModel, setting fn to "ets".
This function is included for backwards compatibility only, and may be
deprecated in the future.
Returns an object of class baggedModel.
The function print is used to obtain and print a summary of the
results.
models |
A list containing the fitted ensemble models. |
method |
The function for producing a forecastable model. |
y |
The original time series. |
bootstrapped_series |
The bootstrapped series. |
modelargs |
The arguments passed through to |
fitted |
Fitted values (one-step forecasts). The mean of the fitted values is calculated over the ensemble. |
residuals |
Original values minus fitted values. |
Christoph Bergmeir, Fotios Petropoulos
Bergmeir, C., R. J. Hyndman, and J. M. Benitez (2016). Bagging Exponential Smoothing Methods using STL Decomposition and Box-Cox Transformation. International Journal of Forecasting 32, 303-312.
fit <- baggedModel(WWWusage) fcast <- forecast(fit) plot(fcast)fit <- baggedModel(WWWusage) fcast <- forecast(fit) plot(fcast)
Fits a BATS model applied to y, as described in De Livera, Hyndman &
Snyder (2011). Parallel processing is used by default to speed up the
computations.
bats( y, use.box.cox = NULL, use.trend = NULL, use.damped.trend = NULL, seasonal.periods = NULL, use.arma.errors = TRUE, use.parallel = length(y) > 1000, num.cores = 2, bc.lower = 0, bc.upper = 1, biasadj = FALSE, model = NULL, ... )bats( y, use.box.cox = NULL, use.trend = NULL, use.damped.trend = NULL, seasonal.periods = NULL, use.arma.errors = TRUE, use.parallel = length(y) > 1000, num.cores = 2, bc.lower = 0, bc.upper = 1, biasadj = FALSE, model = NULL, ... )
y |
The time series to be forecast. Can be |
use.box.cox |
|
use.trend |
|
use.damped.trend |
|
seasonal.periods |
If |
use.arma.errors |
|
use.parallel |
|
num.cores |
The number of parallel processes to be used if using
parallel processing. If |
bc.lower |
The lower limit (inclusive) for the Box-Cox transformation. |
bc.upper |
The upper limit (inclusive) for the Box-Cox transformation. |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
model |
Output from a previous call to |
... |
Additional arguments to be passed to |
An object of class bats. The generic accessor functions
fitted.values and residuals extract useful features of the
value returned by bats and associated functions. The fitted model is
designated BATS(omega, p,q, phi, m1,...mJ) where omega is the Box-Cox
parameter and phi is the damping parameter; the error is modelled as an
ARMA(p,q) process and m1,...,mJ list the seasonal periods used in the model.
Slava Razbash and Rob J Hyndman
De Livera, A.M., Hyndman, R.J., & Snyder, R. D. (2011), Forecasting time series with complex seasonal patterns using exponential smoothing, Journal of the American Statistical Association, 106(496), 1513-1527.
## Not run: fit <- bats(USAccDeaths) plot(forecast(fit)) taylor.fit <- bats(taylor) plot(forecast(taylor.fit)) ## End(Not run)## Not run: fit <- bats(USAccDeaths) plot(forecast(fit)) taylor.fit <- bats(taylor) plot(forecast(taylor.fit)) ## End(Not run)
Returns number of trading days in each month or quarter of the observed time period in a major financial center.
bizdays(x, FinCenter = c("New York", "London", "NERC", "Toronto", "Zurich"))bizdays(x, FinCenter = c("New York", "London", "NERC", "Toronto", "Zurich"))
x |
Monthly or quarterly time series. |
FinCenter |
Major financial center. |
Useful for trading days length adjustments. More on how to define "business
days", please refer to timeDate::isBizday().
Time series
Earo Wang
x <- ts(rnorm(30), start = c(2013, 2), frequency = 12) bizdays(x, FinCenter = "New York")x <- ts(rnorm(30), start = c(2013, 2), frequency = 12) bizdays(x, FinCenter = "New York")
Generates bootstrapped versions of a time series using the Box-Cox and Loess-based decomposition bootstrap.
bld.mbb.bootstrap(x, num, block_size = NULL)bld.mbb.bootstrap(x, num, block_size = NULL)
x |
Original time series. |
num |
Number of bootstrapped versions to generate. |
block_size |
Block size for the moving block bootstrap. |
The procedure is described in Bergmeir et al. Box-Cox decomposition is applied, together with STL or Loess (for non-seasonal time series), and the remainder is bootstrapped using a moving block bootstrap.
A list with bootstrapped versions of the series. The first series in the list is the original series.
Christoph Bergmeir, Fotios Petropoulos
Bergmeir, C., R. J. Hyndman, and J. M. Benitez (2016). Bagging Exponential Smoothing Methods using STL Decomposition and Box-Cox Transformation. International Journal of Forecasting 32, 303-312.
bootstrapped_series <- bld.mbb.bootstrap(WWWusage, 100)bootstrapped_series <- bld.mbb.bootstrap(WWWusage, 100)
BoxCox() returns a transformation of the input variable using a Box-Cox transformation. InvBoxCox() reverses the transformation.
BoxCox(x, lambda) InvBoxCox(x, lambda, biasadj = FALSE, fvar = NULL)BoxCox(x, lambda) InvBoxCox(x, lambda, biasadj = FALSE, fvar = NULL)
x |
a numeric vector or time series of class |
lambda |
transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
fvar |
Optional parameter required if |
The Box-Cox transformation (as given by Bickel & Doksum 1981) is given by
if . For ,
.
a numeric vector of the same length as x.
Rob J Hyndman & Mitchell O'Hara-Wild
Box, G. E. P. and Cox, D. R. (1964) An analysis of transformations. JRSS B 26 211–246. Bickel, P. J. and Doksum K. A. (1981) An Analysis of Transformations Revisited. JASA 76 296-311.
lambda <- BoxCox.lambda(lynx) lynx.fit <- ar(BoxCox(lynx, lambda)) plot(forecast(lynx.fit, h = 20, lambda = lambda))lambda <- BoxCox.lambda(lynx) lynx.fit <- ar(BoxCox(lynx, lambda)) plot(forecast(lynx.fit, h = 20, lambda = lambda))
If method = "guerrero", Guerrero's (1993) method is used, where lambda
minimizes the coefficient of variation for subseries of x.
BoxCox.lambda(x, method = c("guerrero", "loglik"), lower = -1, upper = 2)BoxCox.lambda(x, method = c("guerrero", "loglik"), lower = -1, upper = 2)
x |
A numeric vector or time series of class |
method |
Choose method to be used in calculating lambda. |
lower |
Lower limit for possible lambda values. |
upper |
Upper limit for possible lambda values. |
If method = "loglik", the value of lambda is chosen to maximize the
profile log likelihood of a linear model fitted to x. For
non-seasonal data, a linear time trend is fitted while for seasonal data, a
linear time trend with seasonal dummy variables is used.
a number indicating the Box-Cox transformation parameter.
Leanne Chhay and Rob J Hyndman
Box, G. E. P. and Cox, D. R. (1964) An analysis of transformations. JRSS B 26 211–246.
Guerrero, V.M. (1993) Time-series analysis supported by power transformations. Journal of Forecasting, 12, 37–48.
lambda <- BoxCox.lambda(AirPassengers, lower = 0) air.fit <- Arima( AirPassengers, order = c(0, 1, 1), seasonal = list(order = c(0, 1, 1), period = 12), lambda = lambda ) plot(forecast(air.fit))lambda <- BoxCox.lambda(AirPassengers, lower = 0) air.fit <- Arima( AirPassengers, order = c(0, 1, 1), seasonal = list(order = c(0, 1, 1), period = 12), lambda = lambda ) plot(forecast(air.fit))
If plot = TRUE, produces a time plot of the residuals, the
corresponding ACF, and a histogram. If test is not FALSE,
the output from either a Ljung-Box test or Breusch-Godfrey test is printed.
checkresiduals(object, lag, test, plot = TRUE, ...)checkresiduals(object, lag, test, plot = TRUE, ...)
object |
Either a time series model, a forecast object, or a time series (assumed to be residuals). |
lag |
Number of lags to use in the Ljung-Box or Breusch-Godfrey test.
If missing, it is set to |
test |
Test to use for serial correlation. By default, if |
plot |
Logical. If |
... |
Other arguments are passed to |
None
Rob J Hyndman
ggtsdisplay(), stats::Box.test(), lmtest::bgtest()
fit <- ets(WWWusage) checkresiduals(fit)fit <- ets(WWWusage) checkresiduals(fit)
Based on Croston's (1972) method for intermittent demand forecasting, also described in Shenstone and Hyndman (2005). Croston's method involves using simple exponential smoothing (SES) on the non-zero elements of the time series and a separate application of SES to the times between non-zero elements of the time series. Returns a model object that can be used to generate forecasts using Croston's method for intermittent demand time series. It isn't a true statistical model in that it doesn't describe a data generating process that would lead to the forecasts produced using Croston's method.
croston_model(y, alpha = 0.1, type = c("croston", "sba", "sbj"))croston_model(y, alpha = 0.1, type = c("croston", "sba", "sbj"))
y |
a numeric vector or univariate time series of class |
alpha |
Value of alpha. Default value is 0.1. |
type |
Which variant of Croston's method to use. Defaults to |
Note that prediction intervals are not computed as Croston's method has no underlying stochastic model.
There are two variant methods available which apply multiplicative correction factors
to the forecasts that result from the original Croston's method. For the
Syntetos-Boylan approximation (type = "sba"), this factor is ,
and for the Shale-Boylan-Johnston method (type = "sbj"), this factor is
, where is the smoothing parameter for
the interval SES application.
An object of class croston_model
Rob J Hyndman
Croston, J. (1972) "Forecasting and stock control for intermittent demands", Operational Research Quarterly, 23(3), 289-303.
Shale, E.A., Boylan, J.E., & Johnston, F.R. (2006). Forecasting for intermittent demand: the estimation of an unbiased average. Journal of the Operational Research Society, 57(5), 588-592.
Shenstone, L., and Hyndman, R.J. (2005) "Stochastic models underlying Croston's method for intermittent demand forecasting". Journal of Forecasting, 24, 389-402.
Syntetos A.A., Boylan J.E. (2001). On the bias of intermittent demand estimates. International Journal of Production Economics, 71, 457–466.
y <- rpois(20, lambda = 0.3) fit <- croston_model(y) forecast(fit) |> autoplot()y <- rpois(20, lambda = 0.3) fit <- croston_model(y) forecast(fit) |> autoplot()
Computes the leave-one-out cross-validation statistic (the mean of PRESS – prediction residual sum of squares), AIC, corrected AIC, BIC and adjusted R^2 values for a linear model.
CV(obj)CV(obj)
obj |
Output from |
Numerical vector containing CV, AIC, AICc, BIC and AdjR2 values.
Rob J Hyndman
y <- ts(rnorm(120, 0, 3) + 20 * sin(2 * pi * (1:120) / 12), frequency = 12) fit1 <- tslm(y ~ trend + season) fit2 <- tslm(y ~ season) CV(fit1) CV(fit2)y <- ts(rnorm(120, 0, 3) + 20 * sin(2 * pi * (1:120) / 12), frequency = 12) fit1 <- tslm(y ~ trend + season) fit2 <- tslm(y ~ season) CV(fit1) CV(fit2)
CVar computes the errors obtained by applying an autoregressive
modelling function to subsets of the time series y using k-fold
cross-validation as described in Bergmeir, Hyndman and Koo (2015). It also
applies a Ljung-Box test to the residuals. If this test is significant
(see returned pvalue), there is serial correlation in the residuals and the
model can be considered to be underfitting the data. In this case, the
cross-validated errors can underestimate the generalization error and should
not be used.
CVar( y, k = 10, FUN = nnetar, cvtrace = FALSE, blocked = FALSE, LBlags = 24, ... )CVar( y, k = 10, FUN = nnetar, cvtrace = FALSE, blocked = FALSE, LBlags = 24, ... )
y |
Univariate time series |
k |
Number of folds to use for cross-validation. |
FUN |
Function to fit an autoregressive model. Currently, it only works
with the |
cvtrace |
Provide progress information. |
blocked |
choose folds randomly or as blocks? |
LBlags |
lags for the Ljung-Box test, defaults to 24, for yearly series can be set to 20 |
... |
Other arguments are passed to |
A list containing information about the model and accuracy for each fold, plus other summary information computed across folds.
Gabriel Caceres and Rob J Hyndman
Bergmeir, C., Hyndman, R.J., Koo, B. (2018) A note on the validity of cross-validation for evaluating time series prediction. Computational Statistics & Data Analysis, 120, 70-83. https://robjhyndman.com/publications/cv-time-series/.
modelcv <- CVar(lynx, k = 5, lambda = 0.15) print(modelcv) print(modelcv$fold1) library(ggplot2) autoplot(lynx, series = "Data") + autolayer(modelcv$testfit, series = "Fits") + autolayer(modelcv$residuals, series = "Residuals") ggAcf(modelcv$residuals)modelcv <- CVar(lynx, k = 5, lambda = 0.15) print(modelcv) print(modelcv$fold1) library(ggplot2) autoplot(lynx, series = "Data") + autolayer(modelcv$testfit, series = "Fits") + autolayer(modelcv$residuals, series = "Residuals") ggAcf(modelcv$residuals)
The Diebold-Mariano test compares the forecast accuracy of two forecast methods.
dm.test( e1, e2, alternative = c("two.sided", "less", "greater"), h = 1, power = 2, varestimator = c("acf", "bartlett") )dm.test( e1, e2, alternative = c("two.sided", "less", "greater"), h = 1, power = 2, varestimator = c("acf", "bartlett") )
e1 |
Forecast errors from method 1. |
e2 |
Forecast errors from method 2. |
alternative |
A character string specifying the alternative hypothesis,
must be one of |
h |
The forecast horizon used in calculating |
power |
The power used in the loss function. Usually 1 or 2. |
varestimator |
A character string specifying the long-run variance estimator.
Options are |
This function implements the modified test proposed by Harvey, Leybourne and
Newbold (1997). The null hypothesis is that the two methods have the same
forecast accuracy. For alternative = "less", the alternative hypothesis
is that method 2 is less accurate than method 1. For
alternative = "greater", the alternative hypothesis is that method 2 is
more accurate than method 1. For alternative = "two.sided", the
alternative hypothesis is that method 1 and method 2 have different levels
of accuracy. The long-run variance estimator can either be the
auto-correlation estimator varestimator = "acf", or the estimator based
on Bartlett weights varestimator = "bartlett" which ensures a positive estimate.
Both long-run variance estimators are proposed in Diebold and Mariano (1995).
A list with class htest containing the following
components:
statistic |
the value of the DM-statistic. |
parameter |
the forecast horizon and loss function power used in the test. |
alternative |
a character string describing the alternative hypothesis. |
varestimator |
a character string describing the long-run variance estimator. |
p.value |
the p-value for the test. |
method |
a character string with the value "Diebold-Mariano Test". |
data.name |
a character vector giving the names of the two error series. |
George Athanasopoulos and Kirill Kuroptev
Diebold, F.X. and Mariano, R.S. (1995) Comparing predictive accuracy. Journal of Business and Economic Statistics, 13, 253-263.
Harvey, D., Leybourne, S., & Newbold, P. (1997). Testing the equality of prediction mean squared errors. International Journal of forecasting, 13(2), 281-291.
# Test on in-sample one-step forecasts f1 <- ets(WWWusage) f2 <- auto.arima(WWWusage) accuracy(f1) accuracy(f2) dm.test(residuals(f1), residuals(f2), h = 1) # Test on out-of-sample one-step forecasts f1 <- ets(WWWusage[1:80]) f2 <- auto.arima(WWWusage[1:80]) f1.out <- ets(WWWusage[81:100], model = f1) f2.out <- Arima(WWWusage[81:100], model = f2) accuracy(f1.out) accuracy(f2.out) dm.test(residuals(f1.out), residuals(f2.out), h = 1)# Test on in-sample one-step forecasts f1 <- ets(WWWusage) f2 <- auto.arima(WWWusage) accuracy(f1) accuracy(f2) dm.test(residuals(f1), residuals(f2), h = 1) # Test on out-of-sample one-step forecasts f1 <- ets(WWWusage[1:80]) f2 <- auto.arima(WWWusage[1:80]) f1.out <- ets(WWWusage[81:100], model = f1) f2.out <- Arima(WWWusage[81:100], model = f2) accuracy(f1.out) accuracy(f2.out) dm.test(residuals(f1.out), residuals(f2.out), h = 1)
Returns forecasts using Taylor's (2003) Double-Seasonal Holt-Winters method.
dshw( y, period1 = NULL, period2 = NULL, h = 2 * max(period1, period2), alpha = NULL, beta = NULL, gamma = NULL, omega = NULL, phi = NULL, lambda = NULL, biasadj = FALSE, armethod = TRUE, model = NULL )dshw( y, period1 = NULL, period2 = NULL, h = 2 * max(period1, period2), alpha = NULL, beta = NULL, gamma = NULL, omega = NULL, phi = NULL, lambda = NULL, biasadj = FALSE, armethod = TRUE, model = NULL )
y |
Either an |
period1 |
Period of the shorter seasonal period. Only used if |
period2 |
Period of the longer seasonal period. Only used if |
h |
Number of periods for forecasting. |
alpha |
Smoothing parameter for the level. If |
beta |
Smoothing parameter for the slope. If |
gamma |
Smoothing parameter for the first seasonal period. If
|
omega |
Smoothing parameter for the second seasonal period. If
|
phi |
Autoregressive parameter. If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
armethod |
If |
model |
If it's specified, an existing model is applied to a new data set. |
Taylor's (2003) double-seasonal Holt-Winters method uses additive trend and
multiplicative seasonality, where there are two seasonal components which
are multiplied together. For example, with a series of half-hourly data, one
would set period1 = 48 for the daily period and period2 = 336 for
the weekly period. The smoothing parameter notation used here is different
from that in Taylor (2003); instead it matches that used in Hyndman et al
(2008) and that used for the ets() function.
An object of class forecast.
Rob J Hyndman
Taylor, J.W. (2003) Short-term electricity demand forecasting using double seasonal exponential smoothing. Journal of the Operational Research Society, 54, 799-805.
Hyndman, R.J., Koehler, A.B., Ord, J.K., and Snyder, R.D. (2008) Forecasting with exponential smoothing: the state space approach, Springer-Verlag. https://robjhyndman.com/expsmooth/.
## Not run: fcast <- dshw(taylor) plot(fcast) t <- seq(0, 5, by = 1 / 20) x <- exp(sin(2 * pi * t) + cos(2 * pi * t * 4) + rnorm(length(t), 0, 0.1)) fit <- dshw(x, 20, 5) plot(fit) ## End(Not run)## Not run: fcast <- dshw(taylor) plot(fcast) t <- seq(0, 5, by = 1 / 20) x <- exp(sin(2 * pi * t) + cos(2 * pi * t * 4) + rnorm(length(t), 0, 0.1)) fit <- dshw(x, 20, 5) plot(fit) ## End(Not run)
Returns a vector of 0's and 1's or fractional results if Easter spans March
and April in the observed time period. Easter is defined as the days from
Good Friday to Easter Sunday inclusively, plus optionally Easter Monday if
easter.mon = TRUE.
easter(x, easter.mon = FALSE)easter(x, easter.mon = FALSE)
x |
Monthly or quarterly time series. |
easter.mon |
If |
Useful for adjusting calendar effects.
Time series
Earo Wang
easter(wineind, easter.mon = TRUE)easter(wineind, easter.mon = TRUE)
Returns ets model applied to y.
ets( y, model = "ZZZ", damped = NULL, alpha = NULL, beta = NULL, gamma = NULL, phi = NULL, additive.only = FALSE, lambda = NULL, biasadj = FALSE, lower = c(rep(1e-04, 3), 0.8), upper = c(rep(0.9999, 3), 0.98), opt.crit = c("lik", "amse", "mse", "sigma", "mae"), nmse = 3, bounds = c("both", "usual", "admissible"), ic = c("aicc", "aic", "bic"), restrict = TRUE, allow.multiplicative.trend = FALSE, use.initial.values = FALSE, ... )ets( y, model = "ZZZ", damped = NULL, alpha = NULL, beta = NULL, gamma = NULL, phi = NULL, additive.only = FALSE, lambda = NULL, biasadj = FALSE, lower = c(rep(1e-04, 3), 0.8), upper = c(rep(0.9999, 3), 0.98), opt.crit = c("lik", "amse", "mse", "sigma", "mae"), nmse = 3, bounds = c("both", "usual", "admissible"), ic = c("aicc", "aic", "bic"), restrict = TRUE, allow.multiplicative.trend = FALSE, use.initial.values = FALSE, ... )
y |
a numeric vector or univariate time series of class |
model |
Usually a three-character string identifying method using the framework terminology of Hyndman et al. (2002) and Hyndman et al. (2008). The first letter denotes the error type ("A", "M" or "Z"); the second letter denotes the trend type ("N","A","M" or "Z"); and the third letter denotes the season type ("N","A","M" or "Z"). In all cases, "N"=none, "A"=additive, "M"=multiplicative and "Z"=automatically selected. So, for example, "ANN" is simple exponential smoothing with additive errors, "MAM" is multiplicative Holt-Winters' method with multiplicative errors, and so on. It is also possible for the model to be of class |
damped |
If |
alpha |
Value of alpha. If |
beta |
Value of beta. If |
gamma |
Value of gamma. If |
phi |
Value of phi. If |
additive.only |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
lower |
Lower bounds for the parameters (alpha, beta, gamma, phi). Ignored if |
upper |
Upper bounds for the parameters (alpha, beta, gamma, phi). Ignored if |
opt.crit |
Optimization criterion. One of "mse" (Mean Square Error),
"amse" (Average MSE over first |
nmse |
Number of steps for average multistep MSE (1<= |
bounds |
Type of parameter space to impose: |
ic |
Information criterion to be used in model selection. |
restrict |
If |
allow.multiplicative.trend |
If |
use.initial.values |
If |
... |
Other arguments are ignored. |
Based on the classification of methods as described in Hyndman et al (2008).
The methodology is fully automatic. The only required argument for ets is the time series. The model is chosen automatically if not specified. This methodology performed extremely well on the M3-competition data. (See Hyndman, et al, 2002, below.)
An object of class ets.
The generic accessor functions fitted.values and residuals
extract useful features of the value returned by ets and associated
functions.
Rob J Hyndman
Hyndman, R.J., Koehler, A.B., Snyder, R.D., and Grose, S. (2002) "A state space framework for automatic forecasting using exponential smoothing methods", International J. Forecasting, 18(3), 439–454.
Hyndman, R.J., Akram, Md., and Archibald, B. (2008) "The admissible parameter space for exponential smoothing models". Annals of Statistical Mathematics, 60(2), 407–426.
Hyndman, R.J., Koehler, A.B., Ord, J.K., and Snyder, R.D. (2008) Forecasting with exponential smoothing: the state space approach, Springer-Verlag. https://robjhyndman.com/expsmooth/.
stats::HoltWinters(), rwf(), Arima().
fit <- ets(USAccDeaths) plot(forecast(fit))fit <- ets(USAccDeaths) plot(forecast(fit))
findfrequency returns the period of the dominant frequency of a time
series. For seasonal data, it will return the seasonal period. For cyclic
data, it will return the average cycle length.
findfrequency(x)findfrequency(x)
x |
a numeric vector or time series of class |
The dominant frequency is determined from a spectral analysis of the time
series. First, a linear trend is removed, then the spectral density function
is estimated from the best fitting autoregressive model (based on the AIC).
If there is a large (possibly local) maximum in the spectral density
function at frequency , then the function will return the period
(rounded to the nearest integer). If no such dominant frequency
can be found, the function will return 1.
an integer value
Rob J Hyndman
findfrequency(USAccDeaths) # Monthly data findfrequency(taylor) # Half-hourly data findfrequency(lynx) # Annual datafindfrequency(USAccDeaths) # Monthly data findfrequency(taylor) # Half-hourly data findfrequency(lynx) # Annual data
Returns h-step forecasts for the data used in fitting the model.
## S3 method for class 'ARFIMA' fitted(object, h = 1, ...) ## S3 method for class 'Arima' fitted(object, h = 1, ...) ## S3 method for class 'ar' fitted(object, ...) ## S3 method for class 'bats' fitted(object, h = 1, ...) ## S3 method for class 'ets' fitted(object, h = 1, ...) ## S3 method for class 'modelAR' fitted(object, h = 1, ...) ## S3 method for class 'nnetar' fitted(object, h = 1, ...) ## S3 method for class 'tbats' fitted(object, h = 1, ...)## S3 method for class 'ARFIMA' fitted(object, h = 1, ...) ## S3 method for class 'Arima' fitted(object, h = 1, ...) ## S3 method for class 'ar' fitted(object, ...) ## S3 method for class 'bats' fitted(object, h = 1, ...) ## S3 method for class 'ets' fitted(object, h = 1, ...) ## S3 method for class 'modelAR' fitted(object, h = 1, ...) ## S3 method for class 'nnetar' fitted(object, h = 1, ...) ## S3 method for class 'tbats' fitted(object, h = 1, ...)
object |
An object of class |
h |
The number of steps to forecast ahead. |
... |
Other arguments. |
A time series of the h-step forecasts.
Rob J Hyndman & Mitchell O'Hara-Wild
forecast.Arima(), forecast.bats(), forecast.tbats(),
forecast.ets(), forecast.nnetar(), residuals.Arima(),
residuals.bats() residuals.tbats(), residuals.ets(),
residuals.nnetar().
fit <- ets(WWWusage) plot(WWWusage) lines(fitted(fit), col = "red") lines(fitted(fit, h = 2), col = "green") lines(fitted(fit, h = 3), col = "blue") legend("topleft", legend = paste("h =", 1:3), col = 2:4, lty = 1)fit <- ets(WWWusage) plot(WWWusage) lines(fitted(fit), col = "red") lines(fitted(fit, h = 2), col = "green") lines(fitted(fit, h = 3), col = "blue") legend("topleft", legend = paste("h =", 1:3), col = 2:4, lty = 1)
Returns forecasts and other information for bagged models.
## S3 method for class 'baggedModel' forecast( object, h = if (frequency(object$y) > 1) 2 * frequency(object$y) else 10, ... )## S3 method for class 'baggedModel' forecast( object, h = if (frequency(object$y) > 1) 2 * frequency(object$y) else 10, ... )
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
... |
Other arguments, passed on to the |
Intervals are calculated as min and max values over the point forecasts from the models in the ensemble. I.e., the intervals are not prediction intervals, but give an indication of how different the forecasts within the ensemble are.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Christoph Bergmeir, Fotios Petropoulos
Bergmeir, C., R. J. Hyndman, and J. M. Benitez (2016). Bagging Exponential Smoothing Methods using STL Decomposition and Box-Cox Transformation. International Journal of Forecasting 32, 303-312.
fit <- baggedModel(WWWusage) fcast <- forecast(fit) plot(fcast) ## Not run: fit2 <- baggedModel(WWWusage, fn = "auto.arima") fcast2 <- forecast(fit2) plot(fcast2) accuracy(fcast2) ## End(Not run)fit <- baggedModel(WWWusage) fcast <- forecast(fit) plot(fcast) ## Not run: fit2 <- baggedModel(WWWusage, fn = "auto.arima") fcast2 <- forecast(fit2) plot(fcast2) accuracy(fcast2) ## End(Not run)
Forecasts h steps ahead with a BATS model. Prediction intervals are
also produced.
## S3 method for class 'bats' forecast(object, h, level = c(80, 95), fan = FALSE, biasadj = NULL, ...) ## S3 method for class 'tbats' forecast( object, h, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, biasadj = NULL, ... )## S3 method for class 'bats' forecast(object, h, level = c(80, 95), fan = FALSE, biasadj = NULL, ...) ## S3 method for class 'tbats' forecast( object, h, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, biasadj = NULL, ... )
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
... |
Other arguments are ignored. |
simulate |
If |
bootstrap |
If |
innov |
Optional matrix of future innovations to be used in
simulations. Ignored if |
npaths |
Number of sample paths used in computing simulated prediction intervals. |
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Slava Razbash and Rob J Hyndman
De Livera, A.M., Hyndman, R.J., & Snyder, R. D. (2011), Forecasting time series with complex seasonal patterns using exponential smoothing, Journal of the American Statistical Association, 106(496), 1513-1527.
bats(), tbats(), forecast.ets().
## Not run: fit <- bats(USAccDeaths) plot(forecast(fit)) taylor.fit <- bats(taylor) plot(forecast(taylor.fit)) ## End(Not run)## Not run: fit <- bats(USAccDeaths) plot(forecast(fit)) taylor.fit <- bats(taylor) plot(forecast(taylor.fit)) ## End(Not run)
Returns forecasts and other information for Croston's forecasts applied to y.
## S3 method for class 'croston_model' forecast(object, h = 10, ...) croston(y, h = 10, alpha = 0.1, type = c("croston", "sba", "sbj"), x = y)## S3 method for class 'croston_model' forecast(object, h = 10, ...) croston(y, h = 10, alpha = 0.1, type = c("croston", "sba", "sbj"), x = y)
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
... |
Additional arguments affecting the forecasts produced. If
|
y |
a numeric vector or univariate time series of class |
alpha |
Value of alpha. Default value is 0.1. |
type |
Which variant of Croston's method to use. Defaults to |
x |
Deprecated. Included for backwards compatibility. |
Based on Croston's (1972) method for intermittent demand forecasting, also
described in Shenstone and Hyndman (2005). Croston's method involves using
simple exponential smoothing (SES) on the non-zero elements of the time
series and a separate application of SES to the times between non-zero
elements of the time series. The smoothing parameters of the two
applications of SES are assumed to be equal and are denoted by alpha.
Note that prediction intervals are not computed as Croston's method has no underlying stochastic model.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
Croston, J. (1972) "Forecasting and stock control for intermittent demands", Operational Research Quarterly, 23(3), 289-303.
Shale, E.A., Boylan, J.E., & Johnston, F.R. (2006). Forecasting for intermittent demand: the estimation of an unbiased average. Journal of the Operational Research Society, 57(5), 588-592.
Shenstone, L., and Hyndman, R.J. (2005) "Stochastic models underlying Croston's method for intermittent demand forecasting". Journal of Forecasting, 24, 389-402.
Syntetos A.A., Boylan J.E. (2001). On the bias of intermittent demand estimates. International Journal of Production Economics, 71, 457–466.
y <- rpois(20, lambda = 0.3) fcast <- croston(y) autoplot(fcast)y <- rpois(20, lambda = 0.3) fcast <- croston(y) autoplot(fcast)
Returns forecasts and other information for univariate ETS models.
## S3 method for class 'ets' forecast( object, h = if (object$m > 1) 2 * object$m else 10, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, PI = TRUE, lambda = object$lambda, biasadj = NULL, ... )## S3 method for class 'ets' forecast( object, h = if (object$m > 1) 2 * object$m else 10, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, PI = TRUE, lambda = object$lambda, biasadj = NULL, ... )
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
simulate |
If |
bootstrap |
If |
innov |
Optional matrix of future innovations to be used in
simulations. Ignored if |
npaths |
Number of sample paths used in computing simulated prediction intervals. |
PI |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
... |
Other arguments are ignored. |
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
fit <- ets(USAccDeaths) plot(forecast(fit, h = 48))fit <- ets(USAccDeaths) plot(forecast(fit, h = 48))
Returns forecasts and other information for univariate ARIMA models.
## S3 method for class 'fracdiff' forecast( object, h = 10, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), ... ) ## S3 method for class 'Arima' forecast( object, h = if (object$arma[5] > 1) 2 * object$arma[5] else 10, level = c(80, 95), fan = FALSE, xreg = NULL, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), ... ) ## S3 method for class 'ar' forecast( object, h = 10, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, lambda = NULL, biasadj = FALSE, ... )## S3 method for class 'fracdiff' forecast( object, h = 10, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), ... ) ## S3 method for class 'Arima' forecast( object, h = if (object$arma[5] > 1) 2 * object$arma[5] else 10, level = c(80, 95), fan = FALSE, xreg = NULL, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), ... ) ## S3 method for class 'ar' forecast( object, h = 10, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, lambda = NULL, biasadj = FALSE, ... )
object |
An object of class |
h |
Number of periods for forecasting. If |
level |
Confidence levels for prediction intervals. |
fan |
If |
simulate |
If |
bootstrap |
If |
innov |
Optional matrix of future innovations to be used in
simulations. Ignored if |
npaths |
Number of sample paths used in computing simulated prediction intervals. |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
... |
Other arguments are ignored. |
xreg |
Future values of any regression variables. A numerical vector or matrix of external regressors; it should not be a data frame. |
For Arima or ar objects, the function calls stats::predict.Arima() or
stats::predict.ar and constructs an object of class forecast from the
results. For fracdiff objects, the calculations are all done within
fracdiff::fracdiff() using the equations given by Peiris and Perera (1988).
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
Peiris, M. & Perera, B. (1988), On prediction with fractionally differenced ARIMA models, Journal of Time Series Analysis, 9(3), 215-220.
stats::predict.Arima(), stats::predict.ar(), auto.arima(),
Arima(), stats::arima(), stats::ar(), arfima().
fit <- Arima(WWWusage, c(3, 1, 0)) plot(forecast(fit)) library(fracdiff) x <- fracdiff.sim(100, ma = -0.4, d = 0.3)$series fit <- arfima(x) plot(forecast(fit, h = 30))fit <- Arima(WWWusage, c(3, 1, 0)) plot(forecast(fit)) library(fracdiff) x <- fracdiff.sim(100, ma = -0.4, d = 0.3)$series fit <- arfima(x) plot(forecast(fit, h = 30))
Returns forecasts and other information for univariate Holt-Winters time series models.
## S3 method for class 'HoltWinters' forecast( object, h = if (frequency(object$x) > 1) 2 * frequency(object$x) else 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, ... )## S3 method for class 'HoltWinters' forecast( object, h = if (frequency(object$x) > 1) 2 * frequency(object$x) else 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, ... )
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
... |
Other arguments are ignored. |
This function calls stats::predict.HoltWinters() and constructs
an object of class forecast from the results.
It is included for completeness, but the ets() is recommended
for use instead of stats::HoltWinters.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
stats::predict.HoltWinters, stats::HoltWinters().
fit <- HoltWinters(WWWusage, gamma = FALSE) plot(forecast(fit))fit <- HoltWinters(WWWusage, gamma = FALSE) plot(forecast(fit))
forecast.lm is used to predict linear models, especially those
involving trend and seasonality components.
## S3 method for class 'lm' forecast( object, newdata, h = 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), ts = TRUE, ... )## S3 method for class 'lm' forecast( object, newdata, h = 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), ts = TRUE, ... )
object |
Object of class "lm", usually the result of a call to
|
newdata |
An optional data frame in which to look for variables with
which to predict. If omitted, it is assumed that the only variables are
trend and season, and |
h |
Number of periods for forecasting. Ignored if |
level |
Confidence levels for prediction intervals. |
fan |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
ts |
If |
... |
Other arguments passed to |
forecast.lm is largely a wrapper for
stats::predict.lm() except that it allows variables "trend"
and "season" which are created on the fly from the time series
characteristics of the data. Also, the output is reformatted into a
forecast object.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
y <- ts(rnorm(120, 0, 3) + 1:120 + 20 * sin(2 * pi * (1:120) / 12), frequency = 12) fit <- tslm(y ~ trend + season) plot(forecast(fit, h = 20))y <- ts(rnorm(120, 0, 3) + 1:120 + 20 * sin(2 * pi * (1:120) / 12), frequency = 12) fit <- tslm(y ~ trend + season) plot(forecast(fit, h = 20))
Returns forecasts and prediction intervals for a Gaussian iid model.
meanf() is a convenience function that combines mean_model() and forecast().
## S3 method for class 'mean_model' forecast( object, h = 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(object$lambda, "biasadj"), bootstrap = FALSE, npaths = 5000, ... ) meanf( y, h = 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, bootstrap = FALSE, npaths = 5000, x = y )## S3 method for class 'mean_model' forecast( object, h = 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(object$lambda, "biasadj"), bootstrap = FALSE, npaths = 5000, ... ) meanf( y, h = 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, bootstrap = FALSE, npaths = 5000, x = y )
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
bootstrap |
If |
npaths |
Number of sample paths used in computing simulated prediction intervals. |
... |
Additional arguments not used. |
y |
a numeric vector or univariate time series of class |
x |
Deprecated. Included for backwards compatibility. |
The model assumes that the data are independent and identically distributed
Forecasts are given by
where is estimated by the sample mean.
The function summary() is used to obtain and print a summary of the
results, while the function plot() produces a plot of the forecasts and
prediction intervals.
The generic accessor functions stats::fitted() and stats::residuals()
extract useful features of the object returned by mean_model().
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
fit_nile <- mean_model(Nile) fit_nile |> forecast(h = 10) |> autoplot() nile.fcast <- meanf(Nile, h = 10)fit_nile <- mean_model(Nile) fit_nile |> forecast(h = 10) |> autoplot() nile.fcast <- meanf(Nile, h = 10)
forecast.mlm is used to predict multiple linear models, especially
those involving trend and seasonality components.
## S3 method for class 'mlm' forecast( object, newdata, h = 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(object$lambda, "biasadj"), ts = TRUE, ... )## S3 method for class 'mlm' forecast( object, newdata, h = 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(object$lambda, "biasadj"), ts = TRUE, ... )
object |
Object of class "mlm", usually the result of a call to
|
newdata |
An optional data frame in which to look for variables with
which to predict. If omitted, it is assumed that the only variables are
trend and season, and |
h |
Number of periods for forecasting. Ignored if |
level |
Confidence levels for prediction intervals. |
fan |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
ts |
If |
... |
Other arguments passed to |
forecast.mlm is largely a wrapper for forecast.lm() except that it
allows forecasts to be generated on multiple series. Also, the output is
reformatted into a mforecast object.
An object of class mforecast.
The function summary is used to obtain and print a summary of the
results, while the function plot produces a plot of the forecasts and
prediction intervals.
The generic accessor functions fitted.values and residuals
extract useful features of the value returned by forecast.lm.
An object of class mforecast is a list containing at least the
following elements:
model |
A list containing information about the fitted model |
method |
The name of the forecasting method as a character string |
mean |
Point forecasts as a multivariate time series |
lower |
Lower limits for prediction intervals of each series |
upper |
Upper limits for prediction intervals of each series |
level |
The confidence values associated with the prediction intervals |
x |
The historical data for the response variable. |
residuals |
Residuals from the fitted model. That is x minus fitted values. |
fitted |
Fitted values |
Mitchell O'Hara-Wild
tslm(), forecast.lm(), stats::lm().
lungDeaths <- cbind(mdeaths, fdeaths) fit <- tslm(lungDeaths ~ trend + season) fcast <- forecast(fit, h = 10) carPower <- as.matrix(mtcars[, c("qsec", "hp")]) carmpg <- mtcars[, "mpg"] fit <- lm(carPower ~ carmpg) fcast <- forecast(fit, newdata = data.frame(carmpg = 30))lungDeaths <- cbind(mdeaths, fdeaths) fit <- tslm(lungDeaths ~ trend + season) fcast <- forecast(fit, h = 10) carPower <- as.matrix(mtcars[, c("qsec", "hp")]) carmpg <- mtcars[, "mpg"] fit <- lm(carPower ~ carmpg) fcast <- forecast(fit, newdata = data.frame(carmpg = 30))
Returns forecasts and other information for user-defined models.
## S3 method for class 'modelAR' forecast( object, h = if (object$m > 1) 2 * object$m else 10, PI = FALSE, level = c(80, 95), fan = FALSE, xreg = NULL, lambda = object$lambda, bootstrap = FALSE, innov = NULL, npaths = 1000, ... )## S3 method for class 'modelAR' forecast( object, h = if (object$m > 1) 2 * object$m else 10, PI = FALSE, level = c(80, 95), fan = FALSE, xreg = NULL, lambda = object$lambda, bootstrap = FALSE, innov = NULL, npaths = 1000, ... )
object |
An object of class |
h |
Number of periods for forecasting. If |
PI |
If |
level |
Confidence levels for prediction intervals. |
fan |
If |
xreg |
Future values of any regression variables. A numerical vector or matrix of external regressors; it should not be a data frame. |
lambda |
Box-Cox transformation parameter. If |
bootstrap |
If |
innov |
Values to use as innovations for prediction intervals. Must be
a matrix with |
npaths |
Number of sample paths used in computing simulated prediction intervals. |
... |
Additional arguments passed to |
Prediction intervals are calculated through simulations and can be slow. Note that if the model is too complex and overfits the data, the residuals can be arbitrarily small; if used for prediction interval calculations, they could lead to misleadingly small values.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman and Gabriel Caceres
mforecast is a class of objects for forecasting from multivariate
time series or multivariate time series models. The function invokes
particular methods which depend on the class of the first argument.
## S3 method for class 'mts' forecast( object, h = if (frequency(object) > 1) 2 * frequency(object) else 10, level = c(80, 95), fan = FALSE, robust = FALSE, lambda = NULL, biasadj = FALSE, find.frequency = FALSE, allow.multiplicative.trend = FALSE, ... )## S3 method for class 'mts' forecast( object, h = if (frequency(object) > 1) 2 * frequency(object) else 10, level = c(80, 95), fan = FALSE, robust = FALSE, lambda = NULL, biasadj = FALSE, find.frequency = FALSE, allow.multiplicative.trend = FALSE, ... )
object |
a multivariate time series or multivariate time series model for which forecasts are required |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
robust |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
find.frequency |
If |
allow.multiplicative.trend |
If |
... |
Additional arguments affecting the forecasts produced. |
For example, the function forecast.mlm() makes multivariate
forecasts based on the results produced by tslm().
An object of class mforecast.
The function summary is used to obtain and print a summary of the
results, while the function plot produces a plot of the multivariate
forecasts and prediction intervals.
The generic accessor functions fitted.values and residuals
extract various useful features of the value returned by forecast$model.
An object of class mforecast is a list usually containing at least
the following elements:
model |
A list containing information about the fitted model |
method |
The name of the forecasting method as a character string |
mean |
Point forecasts as a time series |
lower |
Lower limits for prediction intervals |
upper |
Upper limits for prediction intervals |
level |
The confidence values associated with the prediction intervals |
x |
The original time series (either |
residuals |
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values. |
fitted |
Fitted values (one-step forecasts) |
Rob J Hyndman & Mitchell O'Hara-Wild
Other functions which return objects of class mforecast
are forecast.mlm(), forecast.varest().
Returns forecasts and other information for univariate neural network models.
## S3 method for class 'nnetar' forecast( object, h = if (object$m > 1) 2 * object$m else 10, PI = FALSE, level = c(80, 95), fan = FALSE, xreg = NULL, lambda = object$lambda, bootstrap = FALSE, npaths = 1000, innov = NULL, ... )## S3 method for class 'nnetar' forecast( object, h = if (object$m > 1) 2 * object$m else 10, PI = FALSE, level = c(80, 95), fan = FALSE, xreg = NULL, lambda = object$lambda, bootstrap = FALSE, npaths = 1000, innov = NULL, ... )
object |
An object of class |
h |
Number of periods for forecasting. If |
PI |
If |
level |
Confidence levels for prediction intervals. |
fan |
If |
xreg |
Future values of any regression variables. A numerical vector or matrix of external regressors; it should not be a data frame. |
lambda |
Box-Cox transformation parameter. If |
bootstrap |
If |
npaths |
Number of sample paths used in computing simulated prediction intervals. |
innov |
Values to use as innovations for prediction intervals. Must be
a matrix with |
... |
Additional arguments passed to |
Prediction intervals are calculated through simulations and can be slow. Note that if the network is too complex and overfits the data, the residuals can be arbitrarily small; if used for prediction interval calculations, they could lead to misleadingly small values. It is possible to use out-of-sample residuals to ameliorate this, see examples.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman and Gabriel Caceres
## Fit & forecast model fit <- nnetar(USAccDeaths, size = 2) fcast <- forecast(fit, h = 20) plot(fcast) ## Not run: ## Include prediction intervals in forecast fcast2 <- forecast(fit, h = 20, PI = TRUE, npaths = 100) plot(fcast2) ## Set up out-of-sample innovations using cross-validation fit_cv <- CVar(USAccDeaths, size = 2) res_sd <- sd(fit_cv$residuals, na.rm = TRUE) myinnovs <- rnorm(20 * 100, mean = 0, sd = res_sd) ## Forecast using new innovations fcast3 <- forecast(fit, h = 20, PI = TRUE, npaths = 100, innov = myinnovs) plot(fcast3) ## End(Not run)## Fit & forecast model fit <- nnetar(USAccDeaths, size = 2) fcast <- forecast(fit, h = 20) plot(fcast) ## Not run: ## Include prediction intervals in forecast fcast2 <- forecast(fit, h = 20, PI = TRUE, npaths = 100) plot(fcast2) ## Set up out-of-sample innovations using cross-validation fit_cv <- CVar(USAccDeaths, size = 2) res_sd <- sd(fit_cv$residuals, na.rm = TRUE) myinnovs <- rnorm(20 * 100, mean = 0, sd = res_sd) ## Forecast using new innovations fcast3 <- forecast(fit, h = 20, PI = TRUE, npaths = 100, innov = myinnovs) plot(fcast3) ## End(Not run)
Returns forecasts and prediction intervals for a generalized random walk model.
rwf() is a convenience function that combines rw_model() and forecast().
naive() is a wrapper to rwf() with drift = FALSE and lag = 1, while
snaive() is a wrapper to rwf() with drift = FALSE and lag = frequency(y).
## S3 method for class 'rw_model' forecast( object, h = 10, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, npaths = 5000, innov = NULL, lambda = object$lambda, biasadj = FALSE, ... ) rwf( y, h = 10, drift = FALSE, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, lag = 1, ..., x = y ) naive( y, h = 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, ..., x = y ) snaive( y, h = 2 * frequency(x), level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, ..., x = y )## S3 method for class 'rw_model' forecast( object, h = 10, level = c(80, 95), fan = FALSE, simulate = FALSE, bootstrap = FALSE, npaths = 5000, innov = NULL, lambda = object$lambda, biasadj = FALSE, ... ) rwf( y, h = 10, drift = FALSE, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, lag = 1, ..., x = y ) naive( y, h = 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, ..., x = y ) snaive( y, h = 2 * frequency(x), level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, ..., x = y )
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
simulate |
If |
bootstrap |
If |
npaths |
Number of sample paths used in computing simulated prediction intervals. |
innov |
Optional matrix of future innovations to be used in
simulations. Ignored if |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
... |
Additional arguments not used. |
y |
a numeric vector or univariate time series of class |
drift |
Logical flag. If |
lag |
Lag parameter. |
x |
Deprecated. Included for backwards compatibility. |
The model assumes that
where is the lag parameter,
is the drift parameter, and
are iid.
The model without drift has .
In the model with drift, is estimated
by the sample mean of the differences .
If , this is equivalent to an ARIMA(0,1,0) model with
an optional drift coefficient. For , it is equivalent to an
ARIMA(0,0,0)(0,1,0)p model.
The forecasts are given by
where is the integer part of .
For a regular random walk, and , so all forecasts are equal to the last observation.
Forecast standard errors allow for uncertainty in estimating the drift parameter
(unlike the corresponding forecasts obtained by fitting an ARIMA model
directly).
The generic accessor functions stats::fitted() and stats::residuals()
extract useful features of the object returned.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
# Three ways to do the same thing gold_model <- rw_model(gold) gold_fc1 <- forecast(gold_model, h = 50) gold_fc2 <- rwf(gold, h = 50) gold_fc3 <- naive(gold, h = 50) # Plot the forecasts autoplot(gold_fc1) # Drift forecasts rwf(gold, drift = TRUE) |> autoplot() # Seasonal naive forecasts snaive(wineind) |> autoplot()# Three ways to do the same thing gold_model <- rw_model(gold) gold_fc1 <- forecast(gold_model, h = 50) gold_fc2 <- rwf(gold, h = 50) gold_fc3 <- naive(gold, h = 50) # Plot the forecasts autoplot(gold_fc1) # Drift forecasts rwf(gold, drift = TRUE) |> autoplot() # Seasonal naive forecasts snaive(wineind) |> autoplot()
spline_model().The cubic smoothing spline model is equivalent to an ARIMA(0,2,2) model but with a restricted parameter space. The advantage of the spline model over the full ARIMA model is that it provides a smooth historical trend as well as a linear forecast function. Hyndman, King, Pitrun, and Billah (2002) show that the forecast performance of the method is hardly affected by the restricted parameter space.
## S3 method for class 'spline_model' forecast( object, h = 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, ... ) splinef( y, h = 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, method = c("gcv", "mle"), x = y )## S3 method for class 'spline_model' forecast( object, h = 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), simulate = FALSE, bootstrap = FALSE, innov = NULL, npaths = 5000, ... ) splinef( y, h = 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, method = c("gcv", "mle"), x = y )
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
simulate |
If |
bootstrap |
If |
innov |
Optional matrix of future innovations to be used in
simulations. Ignored if |
npaths |
Number of sample paths used in computing simulated prediction intervals. |
... |
Other arguments are ignored. |
y |
a numeric vector or univariate time series of class |
method |
fitting method: maximum likelihood or minimize conditional sum-of-squares. The default (unless there are missing values) is to use conditional-sum-of-squares to find starting values, then maximum likelihood. Can be abbreviated. |
x |
Deprecated. Included for backwards compatibility. |
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
Hyndman, King, Pitrun and Billah (2005) Local linear forecasts using cubic smoothing splines. Australian and New Zealand Journal of Statistics, 47(1), 87-99. https://robjhyndman.com/publications/splinefcast/.
fit <- spline_model(uspop) fcast <- forecast(fit) autoplot(fcast) summary(fcast)fit <- spline_model(uspop) fcast <- forecast(fit) autoplot(fcast) summary(fcast)
Forecasts of STL objects are obtained by applying a non-seasonal forecasting method to the seasonally adjusted data and re-seasonalizing using the last year of the seasonal component.
## S3 method for class 'stl' forecast( object, method = c("ets", "arima", "naive", "rwdrift"), etsmodel = "ZZN", forecastfunction = NULL, h = frequency(object$time.series) * 2, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, xreg = NULL, newxreg = NULL, allow.multiplicative.trend = FALSE, ... ) ## S3 method for class 'stlm' forecast( object, h = 2 * object$m, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), newxreg = NULL, allow.multiplicative.trend = FALSE, ... ) stlf( y, h = frequency(x) * 2, s.window = 7 + 4 * seq_len(6), t.window = NULL, robust = FALSE, lambda = NULL, biasadj = FALSE, x = y, ... )## S3 method for class 'stl' forecast( object, method = c("ets", "arima", "naive", "rwdrift"), etsmodel = "ZZN", forecastfunction = NULL, h = frequency(object$time.series) * 2, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, xreg = NULL, newxreg = NULL, allow.multiplicative.trend = FALSE, ... ) ## S3 method for class 'stlm' forecast( object, h = 2 * object$m, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = attr(lambda, "biasadj"), newxreg = NULL, allow.multiplicative.trend = FALSE, ... ) stlf( y, h = frequency(x) * 2, s.window = 7 + 4 * seq_len(6), t.window = NULL, robust = FALSE, lambda = NULL, biasadj = FALSE, x = y, ... )
object |
An object of class |
method |
Method to use for forecasting the seasonally adjusted series. |
etsmodel |
The ets model specification passed to
|
forecastfunction |
An alternative way of specifying the function for
forecasting the seasonally adjusted series. If |
h |
Number of periods for forecasting. If |
level |
Confidence levels for prediction intervals. |
fan |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
xreg |
Historical regressors to be used in
|
newxreg |
Future regressors to be used in |
allow.multiplicative.trend |
If |
... |
Other arguments passed to |
y |
a numeric vector or univariate time series of class |
s.window |
Either the character string |
t.window |
A number to control the smoothness of the trend. See
|
robust |
If |
x |
Deprecated. Included for backwards compatibility. |
forecast.stlm forecasts the seasonally adjusted data, then
re-seasonalizes the results by adding back the last year of the estimated
seasonal component.
stlf combines stlm() and forecast.stlm. It takes a
ts argument, applies an STL decomposition, models the seasonally
adjusted data, reseasonalizes, and returns the forecasts. However, it allows
more general forecasting methods to be specified via
forecastfunction.
forecast.stl is similar to stlf except that it takes the STL
decomposition as the first argument, instead of the time series.
Note that the prediction intervals ignore the uncertainty associated with the seasonal component. They are computed using the prediction intervals from the seasonally adjusted series, which are then reseasonalized using the last year of the seasonal component. The uncertainty in the seasonal component is ignored.
The forecasting method for the seasonally adjusted data can be specified in
stlf and forecast.stl using either method or
forecastfunction. The method argument provides a shorthand way
of specifying forecastfunction for a few special cases. More
generally, forecastfunction can be any function with first argument a
ts object, and other h and level, which returns an
object of class forecast(). For example,
forecastfunction = thetaf uses the thetaf() function for
forecasting the seasonally adjusted series.
stlm returns an object of class stlm. The other
functions return objects of class forecast.
There are many methods for working with forecast() objects
including summary to obtain and print a summary of the results, while
plot produces a plot of the forecasts and prediction intervals. The
generic accessor functions fitted.values and residuals extract
useful features.
Rob J Hyndman
stats::stl(), forecast.ets(), forecast.Arima().
tsmod <- stlm(USAccDeaths, modelfunction = ar) plot(forecast(tsmod, h = 36)) decomp <- stl(USAccDeaths, s.window = "periodic") plot(forecast(decomp)) plot(stlf(AirPassengers, lambda = 0))tsmod <- stlm(USAccDeaths, modelfunction = ar) plot(forecast(tsmod, h = 36)) decomp <- stl(USAccDeaths, s.window = "periodic") plot(forecast(decomp)) plot(stlf(AirPassengers, lambda = 0))
Returns forecasts and other information for univariate structural time series models.
## S3 method for class 'StructTS' forecast( object, h = if (object$coef["epsilon"] > 1e-10) 2 * object$xtsp[3] else 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, ... )## S3 method for class 'StructTS' forecast( object, h = if (object$coef["epsilon"] > 1e-10) 2 * object$xtsp[3] else 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, ... )
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
... |
Other arguments are ignored. |
This function calls predict.StructTS and constructs an object of
class forecast from the results.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
fit <- StructTS(WWWusage, "level") plot(forecast(fit))fit <- StructTS(WWWusage, "level") plot(forecast(fit))
Returns forecasts and prediction intervals for a theta method forecast.
thetaf() is a convenience function that combines theta_model() and
forecast.theta_model().
The theta method of Assimakopoulos and Nikolopoulos (2000) is equivalent to
simple exponential smoothing with drift (Hyndman and Billah, 2003).
The series is tested for seasonality using the test outlined in A&N. If
deemed seasonal, the series is seasonally adjusted using a classical
multiplicative decomposition before applying the theta method. The resulting
forecasts are then reseasonalized.
Prediction intervals are computed using the underlying state space model.
## S3 method for class 'theta_model' forecast( object, h = if (frequency(object$y) > 1) 2 * frequency(object$y) else 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = FALSE, ... ) thetaf( y, h = if (frequency(y) > 1) 2 * frequency(y) else 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, type = c("multiplicative", "additive"), x = y, ... )## S3 method for class 'theta_model' forecast( object, h = if (frequency(object$y) > 1) 2 * frequency(object$y) else 10, level = c(80, 95), fan = FALSE, lambda = object$lambda, biasadj = FALSE, ... ) thetaf( y, h = if (frequency(y) > 1) 2 * frequency(y) else 10, level = c(80, 95), fan = FALSE, lambda = NULL, biasadj = FALSE, type = c("multiplicative", "additive"), x = y, ... )
object |
An object of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
... |
Other arguments passed to |
y |
a numeric vector or univariate time series of class |
type |
Type of seasonal decomposition. Either |
x |
Deprecated. Included for backwards compatibility. |
More general theta methods are available in the forecTheta package.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
Assimakopoulos, V. and Nikolopoulos, K. (2000). The theta model: a decomposition approach to forecasting. International Journal of Forecasting 16, 521-530.
Hyndman, R.J., and Billah, B. (2003) Unmasking the Theta method. International J. Forecasting, 19, 287-290.
stats::arima(), meanf(), rwf(), ses()
nile_fit <- theta_model(Nile) forecast(nile_fit) |> autoplot()nile_fit <- theta_model(Nile) forecast(nile_fit) |> autoplot()
forecast is a generic function for forecasting from time series or
time series models. The function invokes particular methods which
depend on the class of the first argument.
## S3 method for class 'ts' forecast( object, h = if (frequency(object) > 1) 2 * frequency(object) else 10, level = c(80, 95), fan = FALSE, robust = FALSE, lambda = NULL, biasadj = FALSE, find.frequency = FALSE, allow.multiplicative.trend = FALSE, model = NULL, ... ) ## Default S3 method: forecast(object, ...) ## S3 method for class 'forecast' print(x, ...)## S3 method for class 'ts' forecast( object, h = if (frequency(object) > 1) 2 * frequency(object) else 10, level = c(80, 95), fan = FALSE, robust = FALSE, lambda = NULL, biasadj = FALSE, find.frequency = FALSE, allow.multiplicative.trend = FALSE, model = NULL, ... ) ## Default S3 method: forecast(object, ...) ## S3 method for class 'forecast' print(x, ...)
object |
a time series or time series model for which forecasts are required. |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
robust |
If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
find.frequency |
If |
allow.multiplicative.trend |
If |
model |
An object describing a time series model; e.g., one of class
|
... |
Additional arguments affecting the forecasts produced. If
|
x |
a numeric vector or time series of class |
For example, the function forecast.Arima() makes forecasts based
on the results produced by stats::arima().
If model = NULL, the function forecast.ts() makes forecasts
using ets() models (if the data are non-seasonal or the seasonal
period is 12 or less) or stlf() (if the seasonal period is 13 or
more).
If model is not NULL, forecast.ts will apply the
model to the object time series, and then generate forecasts
accordingly.
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
Other functions which return objects of class forecast are
forecast.ets(), forecast.Arima(), forecast.HoltWinters(),
forecast.StructTS(), meanf(), rwf(), splinef(), thetaf(),
croston(), ses(), holt(), hw().
WWWusage |> forecast() |> plot() fit <- ets(window(WWWusage, end = 60)) fc <- forecast(WWWusage, model = fit)WWWusage |> forecast() |> plot() fit <- ets(window(WWWusage, end = 60)) fc <- forecast(WWWusage, model = fit)
fourier returns a matrix containing terms from a Fourier series, up to
order K, suitable for use in Arima(), auto.arima(), or tslm().
fourier(x, K, h = NULL) fourierf(x, K, h)fourier(x, K, h = NULL) fourierf(x, K, h)
x |
Seasonal time series: a |
K |
Maximum order(s) of Fourier terms |
h |
Number of periods ahead to forecast (optional) |
fourierf is deprecated, instead use the h argument in fourier.
The period of the Fourier terms is determined from the time series
characteristics of x. When h is missing, the length of
x also determines the number of rows for the matrix returned by
fourier. Otherwise, the value of h determines the number of
rows for the matrix returned by fourier, typically used for
forecasting. The values within x are not used.
Typical use would omit h when generating Fourier terms for training a model
and include h when generating Fourier terms for forecasting.
When x is a ts object, the value of K should be an
integer and specifies the number of sine and cosine terms to return. Thus,
the matrix returned has 2*K columns.
When x is a msts object, then K should be a vector of
integers specifying the number of sine and cosine terms for each of the
seasonal periods. Then the matrix returned will have 2*sum(K)
columns.
Numerical matrix.
Rob J Hyndman
library(ggplot2) # Using Fourier series for a "ts" object # K is chosen to minimize the AICc deaths.model <- auto.arima( USAccDeaths, xreg = fourier(USAccDeaths, K = 5), seasonal = FALSE ) deaths.fcast <- forecast( deaths.model, xreg = fourier(USAccDeaths, K = 5, h = 36) ) autoplot(deaths.fcast) + xlab("Year") # Using Fourier series for a "msts" object taylor.lm <- tslm(taylor ~ fourier(taylor, K = c(3, 3))) taylor.fcast <- forecast( taylor.lm, data.frame(fourier(taylor, K = c(3, 3), h = 270)) ) autoplot(taylor.fcast)library(ggplot2) # Using Fourier series for a "ts" object # K is chosen to minimize the AICc deaths.model <- auto.arima( USAccDeaths, xreg = fourier(USAccDeaths, K = 5), seasonal = FALSE ) deaths.fcast <- forecast( deaths.model, xreg = fourier(USAccDeaths, K = 5, h = 36) ) autoplot(deaths.fcast) + xlab("Year") # Using Fourier series for a "msts" object taylor.lm <- tslm(taylor ~ fourier(taylor, K = c(3, 3))) taylor.fcast <- forecast( taylor.lm, data.frame(fourier(taylor, K = c(3, 3), h = 270)) ) autoplot(taylor.fcast)
Australian monthly gas production: 1956–1995.
data(gas)data(gas)
Time series data
Australian Bureau of Statistics.
plot(gas) seasonplot(gas) tsdisplay(gas)plot(gas) seasonplot(gas) tsdisplay(gas)
getResponse is a generic function for extracting the historical data from
a time series model (including Arima, ets, ar, fracdiff), a linear
model of class lm, or a forecast object. The function invokes particular
methods which depend on the class of the first argument.
getResponse(object, ...) ## Default S3 method: getResponse(object, ...) ## S3 method for class 'lm' getResponse(object, ...) ## S3 method for class 'Arima' getResponse(object, ...) ## S3 method for class 'fracdiff' getResponse(object, ...) ## S3 method for class 'ar' getResponse(object, ...) ## S3 method for class 'tbats' getResponse(object, ...) ## S3 method for class 'bats' getResponse(object, ...) ## S3 method for class 'mforecast' getResponse(object, ...) ## S3 method for class 'baggedModel' getResponse(object, ...)getResponse(object, ...) ## Default S3 method: getResponse(object, ...) ## S3 method for class 'lm' getResponse(object, ...) ## S3 method for class 'Arima' getResponse(object, ...) ## S3 method for class 'fracdiff' getResponse(object, ...) ## S3 method for class 'ar' getResponse(object, ...) ## S3 method for class 'tbats' getResponse(object, ...) ## S3 method for class 'bats' getResponse(object, ...) ## S3 method for class 'mforecast' getResponse(object, ...) ## S3 method for class 'baggedModel' getResponse(object, ...)
object |
a time series model or forecast object. |
... |
Additional arguments that are ignored. |
A numerical vector or a time series object of class ts.
Rob J Hyndman
Plots a histogram and density estimates using ggplot.
gghistogram( x, add.normal = FALSE, add.kde = FALSE, add.rug = TRUE, bins = NULL, boundary = 0 )gghistogram( x, add.normal = FALSE, add.kde = FALSE, add.rug = TRUE, bins = NULL, boundary = 0 )
x |
a numerical vector. |
add.normal |
Add a normal density function for comparison |
add.kde |
Add a kernel density estimate for comparison |
add.rug |
Add a rug plot on the horizontal axis |
bins |
The number of bins to use for the histogram. Selected by default
using the Friedman-Diaconis rule given by |
boundary |
A boundary between two bins. |
None.
Rob J Hyndman
graphics::hist(), ggplot2::geom_histogram()
gghistogram(lynx, add.kde = TRUE)gghistogram(lynx, add.kde = TRUE)
Plots a lag plot using ggplot.
gglagplot( x, lags = if (frequency(x) > 9) 16 else 9, set.lags = 1:lags, diag = TRUE, diag.col = "gray", do.lines = TRUE, colour = TRUE, continuous = frequency(x) > 12, labels = FALSE, seasonal = TRUE, ... ) gglagchull( x, lags = if (frequency(x) > 1) min(12, frequency(x)) else 4, set.lags = 1:lags, diag = TRUE, diag.col = "gray", ... )gglagplot( x, lags = if (frequency(x) > 9) 16 else 9, set.lags = 1:lags, diag = TRUE, diag.col = "gray", do.lines = TRUE, colour = TRUE, continuous = frequency(x) > 12, labels = FALSE, seasonal = TRUE, ... ) gglagchull( x, lags = if (frequency(x) > 1) min(12, frequency(x)) else 4, set.lags = 1:lags, diag = TRUE, diag.col = "gray", ... )
x |
a time series object (type |
lags |
number of lag plots desired, see arg set.lags. |
set.lags |
vector of positive integers specifying which lags to use. |
diag |
logical indicating if the x=y diagonal should be drawn. |
diag.col |
color to be used for the diagonal if(diag). |
do.lines |
if |
colour |
logical indicating if lines should be coloured. |
continuous |
Should the colour scheme for years be continuous or discrete? |
labels |
logical indicating if labels should be used. |
seasonal |
Should the line colour be based on seasonal characteristics
( |
... |
Not used (for consistency with lag.plot) |
"gglagplot" will plot time series against lagged versions of themselves. Helps visualising 'auto-dependence' even when auto-correlations vanish.
"gglagchull" will layer convex hulls of the lags, layered on a single plot. This helps visualise the change in 'auto-dependence' as lags increase.
None.
Mitchell O'Hara-Wild
gglagplot(woolyrnq) gglagplot(woolyrnq, seasonal = FALSE) lungDeaths <- cbind(mdeaths, fdeaths) gglagplot(lungDeaths, lags = 2) gglagchull(lungDeaths, lags = 6) gglagchull(woolyrnq)gglagplot(woolyrnq) gglagplot(woolyrnq, seasonal = FALSE) lungDeaths <- cbind(mdeaths, fdeaths) gglagplot(lungDeaths, lags = 2) gglagchull(lungDeaths, lags = 6) gglagchull(woolyrnq)
Plots a subseries plot using ggplot. Each season is plotted as a separate mini time series. The blue lines represent the mean of the observations within each season.
ggmonthplot(x, labels = NULL, times = time(x), phase = cycle(x), ...) ggsubseriesplot(x, labels = NULL, times = time(x), phase = cycle(x), ...)ggmonthplot(x, labels = NULL, times = time(x), phase = cycle(x), ...) ggsubseriesplot(x, labels = NULL, times = time(x), phase = cycle(x), ...)
x |
a time series object (type |
labels |
A vector of labels to use for each 'season' |
times |
A vector of times for each observation |
phase |
A vector of seasonal components |
... |
Not used (for consistency with monthplot) |
The ggmonthplot function is simply a wrapper for ggsubseriesplot as a
convenience for users familiar with stats::monthplot().
Returns an object of class ggplot.
Mitchell O'Hara-Wild
ggsubseriesplot(AirPassengers) ggsubseriesplot(woolyrnq)ggsubseriesplot(AirPassengers) ggsubseriesplot(woolyrnq)
Plots a seasonal plot as described in Hyndman and Athanasopoulos (2014, chapter 2). This is like a time plot except that the data are plotted against the seasons in separate years.
ggseasonplot( x, season.labels = NULL, year.labels = FALSE, year.labels.left = FALSE, type = NULL, col = NULL, continuous = FALSE, polar = FALSE, labelgap = 0.04, ... ) seasonplot( x, s, season.labels = NULL, year.labels = FALSE, year.labels.left = FALSE, type = "o", main = NULL, xlab = NULL, ylab = "", col = 1, labelgap = 0.1, ... )ggseasonplot( x, season.labels = NULL, year.labels = FALSE, year.labels.left = FALSE, type = NULL, col = NULL, continuous = FALSE, polar = FALSE, labelgap = 0.04, ... ) seasonplot( x, s, season.labels = NULL, year.labels = FALSE, year.labels.left = FALSE, type = "o", main = NULL, xlab = NULL, ylab = "", col = 1, labelgap = 0.1, ... )
x |
a numeric vector or time series of class |
season.labels |
Labels for each season in the "year". |
year.labels |
Logical flag indicating whether labels for each year of data should be plotted on the right. |
year.labels.left |
Logical flag indicating whether labels for each year of data should be plotted on the left. |
type |
plot type (as for |
col |
Colour |
continuous |
Should the colour scheme for years be continuous or discrete? |
polar |
Plot the graph on seasonal coordinates |
labelgap |
Distance between year labels and plotted lines |
... |
additional arguments to |
s |
seasonal frequency of x. |
main |
Main title. |
xlab |
X-axis label. |
ylab |
Y-axis label. |
None.
Rob J Hyndman & Mitchell O'Hara-Wild
Hyndman and Athanasopoulos (2018) Forecasting: principles and practice, 2nd edition, OTexts: Melbourne, Australia. https://otexts.com/fpp2/
ggseasonplot(AirPassengers, col = rainbow(12), year.labels = TRUE) ggseasonplot(AirPassengers, year.labels = TRUE, continuous = TRUE) seasonplot(AirPassengers, col = rainbow(12), year.labels = TRUE)ggseasonplot(AirPassengers, col = rainbow(12), year.labels = TRUE) ggseasonplot(AirPassengers, year.labels = TRUE, continuous = TRUE) seasonplot(AirPassengers, col = rainbow(12), year.labels = TRUE)
Plots a time series along with its acf and either its pacf, lagged scatterplot or spectrum.
ggtsdisplay( x, plot.type = c("partial", "histogram", "scatter", "spectrum"), points = TRUE, smooth = FALSE, lag.max = NULL, na.action = na.contiguous, theme = NULL, ... ) tsdisplay( x, plot.type = c("partial", "histogram", "scatter", "spectrum"), points = TRUE, ci.type = c("white", "ma"), lag.max = NULL, na.action = na.contiguous, main = NULL, xlab = "", ylab = "", pch = 1, cex = 0.5, ... )ggtsdisplay( x, plot.type = c("partial", "histogram", "scatter", "spectrum"), points = TRUE, smooth = FALSE, lag.max = NULL, na.action = na.contiguous, theme = NULL, ... ) tsdisplay( x, plot.type = c("partial", "histogram", "scatter", "spectrum"), points = TRUE, ci.type = c("white", "ma"), lag.max = NULL, na.action = na.contiguous, main = NULL, xlab = "", ylab = "", pch = 1, cex = 0.5, ... )
x |
a numeric vector or time series of class |
plot.type |
type of plot to include in lower right corner. |
points |
logical flag indicating whether to show the individual points or not in the time plot. |
smooth |
logical flag indicating whether to show a smooth loess curve superimposed on the time plot. |
lag.max |
the maximum lag to plot for the acf and pacf. A suitable value is selected by default if the argument is missing. |
na.action |
function to handle missing values in acf, pacf and spectrum
calculations. The default is |
theme |
Adds a ggplot element to each plot, typically a theme. |
... |
additional arguments to |
ci.type |
type of confidence limits for ACF that is passed to
|
main |
Main title. |
xlab |
X-axis label. |
ylab |
Y-axis label. |
pch |
Plotting character. |
cex |
Character size. |
ggtsdisplay will produce the equivalent plot using ggplot graphics.
None.
Rob J Hyndman
Hyndman and Athanasopoulos (2018) Forecasting: principles and practice, 2nd edition, OTexts: Melbourne, Australia. https://otexts.com/fpp2/
stats::plot.ts(), Acf(), stats::spec.ar()
library(ggplot2) ggtsdisplay(USAccDeaths, plot.type = "scatter", theme = theme_bw()) tsdisplay(diff(WWWusage)) ggtsdisplay(USAccDeaths, plot.type = "scatter")library(ggplot2) ggtsdisplay(USAccDeaths, plot.type = "scatter", theme = theme_bw()) tsdisplay(diff(WWWusage)) ggtsdisplay(USAccDeaths, plot.type = "scatter")
Daily morning gold prices in US dollars. 1 January 1985 – 31 March 1989.
data(gold)data(gold)
Time series data
tsdisplay(gold)tsdisplay(gold)
Returns true if the model object is of a particular type
is.acf(x) is.Arima(x) is.baggedModel(x) is.bats(x) is.ets(x) is.modelAR(x) is.stlm(x) is.nnetar(x) is.nnetarmodels(x)is.acf(x) is.Arima(x) is.baggedModel(x) is.bats(x) is.ets(x) is.modelAR(x) is.stlm(x) is.nnetar(x) is.nnetarmodels(x)
x |
object to be tested |
Returns true if the object's numerical values do not vary.
is.constant(x)is.constant(x)
x |
Object to be tested. |
Returns true if the forecast object is of a particular type
is.forecast(x) is.mforecast(x) is.splineforecast(x)is.forecast(x) is.mforecast(x) is.splineforecast(x)
x |
object to be tested |
ma computes a simple moving average smoother of a given time series.
ma(x, order, centre = TRUE)ma(x, order, centre = TRUE)
x |
Univariate time series |
order |
Order of moving average smoother |
centre |
If |
The moving average smoother averages the nearest order periods of
each observation. As neighbouring observations of a time series are likely
to be similar in value, averaging eliminates some of the randomness in the
data, leaving a smooth trend-cycle component.
where .
When an even order is specified, the observations averaged will
include one more observation from the future than the past (k is rounded
up). If centre is TRUE, the value from two moving averages (where k is
rounded up and down respectively) are averaged, centering the moving
average.
Numerical time series object containing the simple moving average smoothed values.
Rob J Hyndman
plot(wineind) sm <- ma(wineind, order = 12) lines(sm, col = "red")plot(wineind) sm <- ma(wineind, order = 12) lines(sm, col = "red")
Fits a Gaussian iid model to a univariate time series.
mean_model(y, lambda = NULL, biasadj = FALSE)mean_model(y, lambda = NULL, biasadj = FALSE)
y |
a numeric vector or univariate time series of class |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
The model assumes that the data are independent and identically distributed
Forecasts are given by
where is estimated by the sample mean.
The function summary() is used to obtain and print a summary of the
results, while the function plot() produces a plot of the forecasts and
prediction intervals.
The generic accessor functions stats::fitted() and stats::residuals()
extract useful features of the object returned by mean_model().
An object of class mean_model.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
forecast.mean_model(), meanf()
fit_nile <- mean_model(Nile) fit_nile |> forecast(h = 10) |> autoplot()fit_nile <- mean_model(Nile) fit_nile |> forecast(h = 10) |> autoplot()
Experimental function to forecast univariate time series with a user-defined model
modelAR( y, p, P = 1, FUN, predict.FUN, xreg = NULL, lambda = NULL, model = NULL, subset = NULL, scale.inputs = FALSE, x = y, ... )modelAR( y, p, P = 1, FUN, predict.FUN, xreg = NULL, lambda = NULL, model = NULL, subset = NULL, scale.inputs = FALSE, x = y, ... )
y |
a numeric vector or univariate time series of class |
p |
Embedding dimension for non-seasonal time series. Number of non-seasonal lags used as inputs. For non-seasonal time series, the default is the optimal number of lags (according to the AIC) for a linear AR(p) model. For seasonal time series, the same method is used but applied to seasonally adjusted data (from an stl decomposition). |
P |
Number of seasonal lags used as inputs. |
FUN |
Function used for model fitting. Must accept argument |
predict.FUN |
Prediction function used to apply |
xreg |
Optionally, a numerical vector or matrix of external regressors,
which must have the same number of rows as |
lambda |
Box-Cox transformation parameter. If |
model |
Output from a previous call to |
subset |
Optional vector specifying a subset of observations to be used
in the fit. Can be an integer index vector or a logical vector the same
length as |
scale.inputs |
If |
x |
Deprecated. Included for backwards compatibility. |
... |
Other arguments passed to |
This is an experimental function and only recommended for advanced users.
The selected model is fitted with lagged values of y as inputs. The inputs
are for lags 1 to p, and lags m to mP where m = frequency(y). If
xreg is provided, its columns are also used as inputs. If there are
missing values in y or xreg, the corresponding rows (and any others
which depend on them as lags) are omitted from the fit. The model is trained
for one-step forecasting. Multi-step forecasts are computed recursively.
Returns an object of class modelAR.
The function summary is used to obtain and print a summary of the
results.
The generic accessor functions fitted.values and residuals
extract useful features of the value returned by modelAR.
model |
A list containing information about the fitted model |
method |
The name of the forecasting method as a character string |
x |
The original time series. |
xreg |
The external regressors used in fitting (if given). |
residuals |
Residuals from the fitted model. That is x minus fitted values. |
fitted |
Fitted values (one-step forecasts) |
... |
Other arguments |
Rob J Hyndman and Gabriel Caceres
## Set up functions my_lm <- function(x, y) { structure(lsfit(x,y), class = "lsfit") } predict.lsfit <- function(object, newdata = NULL) { n <- length(object$qr$qt) if(is.null(newdata)) { z <- numeric(n) z[seq_len(object$qr$rank)] <- object$qr$qt[seq_len(object$qr$rank)] as.numeric(qr.qy(object$qr, z)) } else { sum(object$coefficients * c(1, newdata)) } } # Fit an AR(2) model fit <- modelAR( y = lynx, p = 2, FUN = my_lm, predict.FUN = predict.lsfit, lambda = 0.5, scale.inputs = TRUE ) forecast(fit, h = 20) |> autoplot()## Set up functions my_lm <- function(x, y) { structure(lsfit(x,y), class = "lsfit") } predict.lsfit <- function(object, newdata = NULL) { n <- length(object$qr$qt) if(is.null(newdata)) { z <- numeric(n) z[seq_len(object$qr$rank)] <- object$qr$qt[seq_len(object$qr$rank)] as.numeric(qr.qy(object$qr, z)) } else { sum(object$coefficients * c(1, newdata)) } } # Fit an AR(2) model fit <- modelAR( y = lynx, p = 2, FUN = my_lm, predict.FUN = predict.lsfit, lambda = 0.5, scale.inputs = TRUE ) forecast(fit, h = 20) |> autoplot()
Compute model degrees of freedom
modeldf(object, ...)modeldf(object, ...)
object |
A time series model. |
... |
Other arguments currently ignored. |
Returns number of days in each month or quarter of the observed time period.
monthdays(x)monthdays(x)
x |
time series |
Useful for month length adjustments
Time series
Rob J Hyndman
par(mfrow = c(2, 1)) plot( ldeaths, xlab = "Year", ylab = "pounds", main = "Monthly deaths from lung disease (UK)" ) ldeaths.adj <- ldeaths / monthdays(ldeaths) * 365.25 / 12 plot( ldeaths.adj, xlab = "Year", ylab = "pounds", main = "Adjusted monthly deaths from lung disease (UK)" )par(mfrow = c(2, 1)) plot( ldeaths, xlab = "Year", ylab = "pounds", main = "Monthly deaths from lung disease (UK)" ) ldeaths.adj <- ldeaths / monthdays(ldeaths) * 365.25 / 12 plot( ldeaths.adj, xlab = "Year", ylab = "pounds", main = "Adjusted monthly deaths from lung disease (UK)" )
Decompose a time series into seasonal, trend and remainder components.
Seasonal components are estimated iteratively using STL. Multiple seasonal periods are
allowed. The trend component is computed for the last iteration of STL.
Non-seasonal time series are decomposed into trend and remainder only.
In this case, stats::supsmu() is used to estimate the trend.
Optionally, the time series may be Box-Cox transformed before decomposition.
Unlike stats::stl(), mstl is completely automated.
mstl( x, lambda = NULL, biasadj = FALSE, iterate = 2, s.window = 7 + 4 * seq_len(6), ... )mstl( x, lambda = NULL, biasadj = FALSE, iterate = 2, s.window = 7 + 4 * seq_len(6), ... )
x |
Univariate time series of class |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
iterate |
Number of iterations to use to refine the seasonal component. |
s.window |
Seasonal windows to be used in the decompositions. If scalar, the same value is used for all seasonal components. Otherwise, it should be a vector of the same length as the number of seasonal components (or longer). |
... |
Other arguments are passed to |
library(ggplot2) mstl(taylor) |> autoplot() mstl(AirPassengers, lambda = "auto") |> autoplot()library(ggplot2) mstl(taylor) |> autoplot() mstl(AirPassengers, lambda = "auto") |> autoplot()
msts is an S3 class for multi seasonal time series objects, intended to be used for models that support multiple seasonal periods. The msts class inherits from the ts class and has an additional "msts" attribute which contains the vector of seasonal periods. All methods that work on a ts class, should also work on a msts class.
msts(data, seasonal.periods, ts.frequency = floor(max(seasonal.periods)), ...)msts(data, seasonal.periods, ts.frequency = floor(max(seasonal.periods)), ...)
data |
A numeric vector, ts object, matrix or data frame. It is intended that the time series data is univariate, otherwise treated the same as ts(). |
seasonal.periods |
A vector of the seasonal periods of the msts. |
ts.frequency |
The seasonal period that should be used as frequency of
the underlying ts object. The default value is |
... |
Arguments to be passed to the underlying call to |
An object of class c("msts", "ts"). If there is only one
seasonal period (i.e., length(seasonal.periods) == 1), then the object
is of class ts.
Slava Razbash and Rob J Hyndman
x <- msts(taylor, seasonal.periods = c(2 * 24, 2 * 24 * 7, 2 * 24 * 365), start = 2000 + 22 / 52) y <- msts(USAccDeaths, seasonal.periods = 12, start = 1949)x <- msts(taylor, seasonal.periods = c(2 * 24, 2 * 24 * 7, 2 * 24 * 365), start = 2000 + 22 / 52) y <- msts(USAccDeaths, seasonal.periods = 12, start = 1949)
By default, uses linear interpolation for non-seasonal series. For seasonal series, a robust STL decomposition is first computed. Then a linear interpolation is applied to the seasonally adjusted data, and the seasonal component is added back.
na.interp( x, lambda = NULL, linear = (frequency(x) <= 1 || sum(!is.na(x)) <= 2 * frequency(x)) )na.interp( x, lambda = NULL, linear = (frequency(x) <= 1 || sum(!is.na(x)) <= 2 * frequency(x)) )
x |
Time series. |
lambda |
Box-Cox transformation parameter. If |
linear |
Should a linear interpolation be used. |
A more general and flexible approach is available using na.approx in
the zoo package.
Time series
Rob J Hyndman
data(gold) plot(na.interp(gold))data(gold) plot(na.interp(gold))
Functions to estimate the number of differences required to make a given
time series stationary. ndiffs estimates the number of first
differences necessary.
ndiffs( x, alpha = 0.05, test = c("kpss", "adf", "pp"), type = c("level", "trend"), max.d = 2, ... )ndiffs( x, alpha = 0.05, test = c("kpss", "adf", "pp"), type = c("level", "trend"), max.d = 2, ... )
x |
A univariate time series |
alpha |
Level of the test, possible values range from 0.01 to 0.1. |
test |
Type of unit root test to use |
type |
Specification of the deterministic component in the regression |
max.d |
Maximum number of non-seasonal differences allowed |
... |
Additional arguments to be passed on to the unit root test |
ndiffs uses a unit root test to determine the number of differences
required for time series x to be made stationary. If
test = "kpss", the KPSS test is used with the null hypothesis that
x has a stationary root against a unit-root alternative. Then the
test returns the least number of differences required to pass the test at
the level alpha. If test = "adf", the Augmented Dickey-Fuller
test is used and if test = "pp" the Phillips-Perron test is used. In
both of these cases, the null hypothesis is that x has a unit root
against a stationary root alternative. Then the test returns the least
number of differences required to fail the test at the level alpha.
An integer indicating the number of differences required for stationarity.
Rob J Hyndman, Slava Razbash & Mitchell O'Hara-Wild
Dickey DA and Fuller WA (1979), "Distribution of the Estimators for Autoregressive Time Series with a Unit Root", Journal of the American Statistical Association 74:427-431.
Kwiatkowski D, Phillips PCB, Schmidt P and Shin Y (1992) "Testing the Null Hypothesis of Stationarity against the Alternative of a Unit Root", Journal of Econometrics 54:159-178.
Osborn, D.R. (1990) "A survey of seasonality in UK macroeconomic variables", International Journal of Forecasting, 6:327-336.
Phillips, P.C.B. and Perron, P. (1988) "Testing for a unit root in time series regression", Biometrika, 72(2), 335-346.
Said E and Dickey DA (1984), "Testing for Unit Roots in Autoregressive Moving Average Models of Unknown Order", Biometrika 71:599-607.
auto.arima() and ndiffs()
ndiffs(WWWusage) ndiffs(diff(log(AirPassengers), 12))ndiffs(WWWusage) ndiffs(diff(log(AirPassengers), 12))
Feed-forward neural networks with a single hidden layer and lagged inputs for forecasting univariate time series.
nnetar( y, p, P = 1, size = NULL, repeats = 20, xreg = NULL, lambda = NULL, model = NULL, subset = NULL, scale.inputs = TRUE, parallel = FALSE, num.cores = 2, x = y, ... )nnetar( y, p, P = 1, size = NULL, repeats = 20, xreg = NULL, lambda = NULL, model = NULL, subset = NULL, scale.inputs = TRUE, parallel = FALSE, num.cores = 2, x = y, ... )
y |
a numeric vector or univariate time series of class |
p |
Embedding dimension for non-seasonal time series. Number of non-seasonal lags used as inputs. For non-seasonal time series, the default is the optimal number of lags (according to the AIC) for a linear AR(p) model. For seasonal time series, the same method is used but applied to seasonally adjusted data (from an stl decomposition). If set to zero to indicate that no non-seasonal lags should be included, then P must be at least 1 and a model with only seasonal lags will be fit. |
P |
Number of seasonal lags used as inputs. |
size |
Number of nodes in the hidden layer. Default is half of the number of input nodes (including external regressors, if given) plus 1. |
repeats |
Number of networks to fit with different random starting weights. These are then averaged when producing forecasts. |
xreg |
Optionally, a numerical vector or matrix of external regressors,
which must have the same number of rows as |
lambda |
Box-Cox transformation parameter. If |
model |
Output from a previous call to |
subset |
Optional vector specifying a subset of observations to be used
in the fit. Can be an integer index vector or a logical vector the same
length as |
scale.inputs |
If |
parallel |
If |
num.cores |
Allows the user to specify the amount of parallel processes
to be used if |
x |
Deprecated. Included for backwards compatibility. |
... |
Other arguments passed to |
A feed-forward neural network is fitted with lagged values of y as inputs
and a single hidden layer with size nodes. The inputs are for lags 1 to
p, and lags m to mP where m = frequency(y). If xreg is provided,
its columns are also used as inputs. If there are missing values in y or
xreg, the corresponding rows (and any others which depend on them as lags)
are omitted from the fit. A total of repeats networks are fitted, each
with random starting weights. These are then averaged when computing
forecasts. The network is trained for one-step forecasting. Multi-step
forecasts are computed recursively.
For non-seasonal data, the fitted model is denoted as an NNAR(p,k) model, where k is the number of hidden nodes. This is analogous to an AR(p) model but with nonlinear functions. For seasonal data, the fitted model is called an NNAR(p,P,k)[m] model, which is analogous to an ARIMA(p,0,0)(P,0,0)[m] model but with nonlinear functions.
Returns an object of class nnetar.
The function summary is used to obtain and print a summary of the
results.
The generic accessor functions fitted.values and residuals
extract useful features of the value returned by nnetar.
model |
A list containing information about the fitted model |
method |
The name of the forecasting method as a character string |
x |
The original time series. |
xreg |
The external regressors used in fitting (if given). |
residuals |
Residuals from the fitted model. That is x minus fitted values. |
fitted |
Fitted values (one-step forecasts) |
... |
Other arguments |
Rob J Hyndman and Gabriel Caceres
fit <- nnetar(lynx) fcast <- forecast(fit) plot(fcast) ## Arguments can be passed to nnet() fit <- nnetar(lynx, decay = 0.5, maxit = 150) plot(forecast(fit)) lines(lynx) ## Fit model to first 100 years of lynx data fit <- nnetar(window(lynx, end = 1920), decay = 0.5, maxit = 150) plot(forecast(fit, h = 14)) lines(lynx) ## Apply fitted model to later data, including all optional arguments fit2 <- nnetar(window(lynx, start = 1921), model = fit)fit <- nnetar(lynx) fcast <- forecast(fit) plot(fcast) ## Arguments can be passed to nnet() fit <- nnetar(lynx, decay = 0.5, maxit = 150) plot(forecast(fit)) lines(lynx) ## Fit model to first 100 years of lynx data fit <- nnetar(window(lynx, end = 1920), decay = 0.5, maxit = 150) plot(forecast(fit, h = 14)) lines(lynx) ## Apply fitted model to later data, including all optional arguments fit2 <- nnetar(window(lynx, start = 1921), model = fit)
Functions to estimate the number of differences required to make a given
time series stationary. nsdiffs estimates the number of seasonal differences
necessary.
nsdiffs( x, alpha = 0.05, m = frequency(x), test = c("seas", "ocsb", "hegy", "ch"), max.D = 1, ... )nsdiffs( x, alpha = 0.05, m = frequency(x), test = c("seas", "ocsb", "hegy", "ch"), max.D = 1, ... )
x |
A univariate time series |
alpha |
Level of the test, possible values range from 0.01 to 0.1. |
m |
Deprecated. Length of seasonal period |
test |
Type of unit root test to use |
max.D |
Maximum number of seasonal differences allowed |
... |
Additional arguments to be passed on to the unit root test |
nsdiffs uses seasonal unit root tests to determine the number of
seasonal differences required for time series x to be made stationary
(possibly with some lag-one differencing as well).
Several different tests are available:
If test = "seas" (default), a measure of seasonal strength is used, where differencing is
selected if the seasonal strength (Wang, Smith & Hyndman, 2006) exceeds 0.64
(based on minimizing MASE when forecasting using auto.arima on M3 and M4 data).
If test = "ch", the Canova-Hansen (1995) test is used
(with null hypothesis of deterministic seasonality)
If test = "hegy", the Hylleberg, Engle, Granger & Yoo (1990) test is used.
If test = "ocsb", the Osborn-Chui-Smith-Birchenhall
(1988) test is used (with null hypothesis that a seasonal unit root exists).
An integer indicating the number of differences required for stationarity.
Rob J Hyndman, Slava Razbash and Mitchell O'Hara-Wild
Wang, X, Smith, KA, Hyndman, RJ (2006) "Characteristic-based clustering for time series data", Data Mining and Knowledge Discovery, 13(3), 335-364.
Osborn DR, Chui APL, Smith J, and Birchenhall CR (1988) "Seasonality and the order of integration for consumption", Oxford Bulletin of Economics and Statistics 50(4):361-377.
Canova F and Hansen BE (1995) "Are Seasonal Patterns Constant over Time? A Test for Seasonal Stability", Journal of Business and Economic Statistics 13(3):237-252.
Hylleberg S, Engle R, Granger C and Yoo B (1990) "Seasonal integration and cointegration.", Journal of Econometrics 44(1), pp. 215-238.
auto.arima(), ndiffs(), ocsb.test(), uroot::hegy.test(), and uroot::ch.test()
nsdiffs(AirPassengers)nsdiffs(AirPassengers)
An implementation of the Osborn, Chui, Smith, and Birchenhall (OCSB) test.
ocsb.test(x, lag.method = c("fixed", "AIC", "BIC", "AICc"), maxlag = 0)ocsb.test(x, lag.method = c("fixed", "AIC", "BIC", "AICc"), maxlag = 0)
x |
a univariate seasonal time series. |
lag.method |
a character specifying the lag order selection method. |
maxlag |
the maximum lag order to be considered by |
The regression equation may include lags of the dependent variable. When lag.method = "fixed", the lag order is fixed to maxlag; otherwise, maxlag is the maximum number of lags considered in a lag selection procedure that minimises the lag.method criterion, which can be AIC or BIC or corrected AIC, AICc, obtained as AIC + (2k(k+1))/(n-k-1), where k is the number of parameters and n is the number of available observations in the model.
Critical values for the test are based on simulations, which have been smoothed over to produce critical values for all seasonal periods.
ocsb.test returns a list of class "OCSBtest" with the following components:
statistics the value of the test statistics.
pvalues the p-values for each test statistics.
method a character string describing the type of test.
data.name a character string giving the name of the data.
fitted.model the fitted regression model.
Osborn DR, Chui APL, Smith J, and Birchenhall CR (1988) "Seasonality and the order of integration for consumption", Oxford Bulletin of Economics and Statistics 50(4):361-377.
ocsb.test(AirPassengers)ocsb.test(AirPassengers)
Produces a plot of the inverse AR and MA roots of an ARIMA model. Inverse roots outside the unit circle are shown in red.
## S3 method for class 'Arima' plot( x, type = c("both", "ar", "ma"), main, xlab = "Real", ylab = "Imaginary", ... ) ## S3 method for class 'ar' plot(x, main, xlab = "Real", ylab = "Imaginary", ...) ## S3 method for class 'Arima' autoplot(object, type = c("both", "ar", "ma"), ...) ## S3 method for class 'ar' autoplot(object, ...)## S3 method for class 'Arima' plot( x, type = c("both", "ar", "ma"), main, xlab = "Real", ylab = "Imaginary", ... ) ## S3 method for class 'ar' plot(x, main, xlab = "Real", ylab = "Imaginary", ...) ## S3 method for class 'Arima' autoplot(object, type = c("both", "ar", "ma"), ...) ## S3 method for class 'ar' autoplot(object, ...)
x |
Object of class “Arima” or “ar”. |
type |
Determines if both AR and MA roots are plotted, of if just one set is plotted. |
main |
Main title. Default is "Inverse AR roots" or "Inverse MA roots". |
xlab |
X-axis label. |
ylab |
Y-axis label. |
... |
Other plotting parameters passed to |
object |
Object of class “Arima” or “ar”. Used for ggplot graphics (S3 method consistency). |
autoplot will produce an equivalent plot as a ggplot object.
None. Function produces a plot
Rob J Hyndman & Mitchell O'Hara-Wild
library(ggplot2) fit <- Arima(WWWusage, order = c(3, 1, 0)) plot(fit) autoplot(fit) fit <- Arima(woolyrnq, order = c(2, 0, 0), seasonal = c(2, 1, 1)) plot(fit) autoplot(fit) plot(ar.ols(gold[1:61])) autoplot(ar.ols(gold[1:61]))library(ggplot2) fit <- Arima(WWWusage, order = c(3, 1, 0)) plot(fit) autoplot(fit) fit <- Arima(woolyrnq, order = c(2, 0, 0), seasonal = c(2, 1, 1)) plot(fit) autoplot(fit) plot(ar.ols(gold[1:61])) autoplot(ar.ols(gold[1:61]))
Produces a plot of the level, slope and seasonal components from a BATS or TBATS model. The plotted components are Box-Cox transformed using the estimated transformation parameter.
## S3 method for class 'bats' plot(x, main = "Decomposition by BATS model", ...) ## S3 method for class 'tbats' autoplot(object, range.bars = FALSE, ...) ## S3 method for class 'bats' autoplot(object, range.bars = FALSE, ...) ## S3 method for class 'tbats' plot(x, main = "Decomposition by TBATS model", ...)## S3 method for class 'bats' plot(x, main = "Decomposition by BATS model", ...) ## S3 method for class 'tbats' autoplot(object, range.bars = FALSE, ...) ## S3 method for class 'bats' autoplot(object, range.bars = FALSE, ...) ## S3 method for class 'tbats' plot(x, main = "Decomposition by TBATS model", ...)
x |
Object of class “bats/tbats”. |
main |
Main title for plot. |
... |
Other plotting parameters passed to |
object |
Object of class “bats/tbats”. |
range.bars |
Logical indicating if each plot should have a bar at its
right side representing relative size. If |
None. Function produces a plot
Rob J Hyndman
## Not run: fit <- tbats(USAccDeaths) plot(fit) autoplot(fit, range.bars = TRUE) ## End(Not run)## Not run: fit <- tbats(USAccDeaths) plot(fit) autoplot(fit, range.bars = TRUE) ## End(Not run)
Produces a plot of the level, slope and seasonal components from an ETS model.
## S3 method for class 'ets' plot(x, ...) ## S3 method for class 'ets' autoplot(object, range.bars = NULL, ...)## S3 method for class 'ets' plot(x, ...) ## S3 method for class 'ets' autoplot(object, range.bars = NULL, ...)
x |
Object of class “ets”. |
... |
Other plotting parameters to affect the plot. |
object |
Object of class “ets”. Used for ggplot graphics (S3 method consistency). |
range.bars |
Logical indicating if each plot should have a bar at its
right side representing relative size. If |
autoplot will produce an equivalent plot as a ggplot object.
None. Function produces a plot
Rob J Hyndman & Mitchell O'Hara-Wild
fit <- ets(USAccDeaths) plot(fit) plot(fit, plot.type = "single", ylab = "", col = 1:3) library(ggplot2) autoplot(fit)fit <- ets(USAccDeaths) plot(fit) plot(fit, plot.type = "single", ylab = "", col = 1:3) library(ggplot2) autoplot(fit)
Plots historical data with forecasts and prediction intervals.
## S3 method for class 'forecast' plot( x, include, PI = TRUE, showgap = TRUE, shaded = TRUE, shadebars = (length(x$mean) < 5), shadecols = NULL, col = 1, fcol = 4, pi.col = 1, pi.lty = 2, ylim = NULL, main = NULL, xlab = "", ylab = "", type = "l", flty = 1, flwd = 2, ... ) ## S3 method for class 'forecast' autoplot( object, include, PI = TRUE, shadecols = c("#596DD5", "#D5DBFF"), fcol = "#0000AA", flwd = 0.5, ... ) ## S3 method for class 'splineforecast' autoplot(object, PI = TRUE, ...) ## S3 method for class 'forecast' autolayer(object, series = NULL, PI = TRUE, showgap = TRUE, ...) ## S3 method for class 'splineforecast' plot(x, fitcol = 2, type = "o", pch = 19, ...)## S3 method for class 'forecast' plot( x, include, PI = TRUE, showgap = TRUE, shaded = TRUE, shadebars = (length(x$mean) < 5), shadecols = NULL, col = 1, fcol = 4, pi.col = 1, pi.lty = 2, ylim = NULL, main = NULL, xlab = "", ylab = "", type = "l", flty = 1, flwd = 2, ... ) ## S3 method for class 'forecast' autoplot( object, include, PI = TRUE, shadecols = c("#596DD5", "#D5DBFF"), fcol = "#0000AA", flwd = 0.5, ... ) ## S3 method for class 'splineforecast' autoplot(object, PI = TRUE, ...) ## S3 method for class 'forecast' autolayer(object, series = NULL, PI = TRUE, showgap = TRUE, ...) ## S3 method for class 'splineforecast' plot(x, fitcol = 2, type = "o", pch = 19, ...)
x |
Forecast object produced by |
include |
number of values from time series to include in plot. Default is all values. |
PI |
Logical flag indicating whether to plot prediction intervals. |
showgap |
If |
shaded |
Logical flag indicating whether prediction intervals should be
shaded ( |
shadebars |
Logical flag indicating if prediction intervals should be
plotted as shaded bars (if |
shadecols |
Colors for shaded prediction intervals. To get default
colors used prior to v3.26, set |
col |
Colour for the data line. |
fcol |
Colour for the forecast line. |
pi.col |
If |
pi.lty |
If |
ylim |
Limits on y-axis. |
main |
Main title. |
xlab |
X-axis label. |
ylab |
Y-axis label. |
type |
1-character string giving the type of plot desired. As for
|
flty |
Line type for the forecast line. |
flwd |
Line width for the forecast line. |
... |
Other plotting parameters to affect the plot. |
object |
Forecast object produced by |
series |
Matches an unidentified forecast layer with a coloured object on the plot. |
fitcol |
Line colour for fitted values. |
pch |
Plotting character (if |
autoplot will produce a ggplot object.
plot.splineforecast autoplot.splineforecast
None.
Rob J Hyndman & Mitchell O'Hara-Wild
Hyndman and Athanasopoulos (2018) Forecasting: principles and practice, 2nd edition, OTexts: Melbourne, Australia. https://otexts.com/fpp2/
library(ggplot2) wine.fit <- hw(wineind, h = 48) plot(wine.fit) autoplot(wine.fit) fit <- tslm(wineind ~ fourier(wineind, 4)) fcast <- forecast(fit, newdata = data.frame(fourier(wineind, 4, 20))) autoplot(fcast) fcast <- splinef(airmiles, h = 5) plot(fcast) autoplot(fcast)library(ggplot2) wine.fit <- hw(wineind, h = 48) plot(wine.fit) autoplot(wine.fit) fit <- tslm(wineind ~ fourier(wineind, 4)) fcast <- forecast(fit, newdata = data.frame(fourier(wineind, 4, 20))) autoplot(fcast) fcast <- splinef(airmiles, h = 5) plot(fcast) autoplot(fcast)
Returns time series of residuals from a fitted model.
## S3 method for class 'forecast' residuals(object, type = c("innovation", "response"), ...) ## S3 method for class 'ar' residuals(object, type = c("innovation", "response"), ...) ## S3 method for class 'Arima' residuals(object, type = c("innovation", "response", "regression"), h = 1, ...) ## S3 method for class 'bats' residuals(object, type = c("innovation", "response"), h = 1, ...) ## S3 method for class 'tbats' residuals(object, type = c("innovation", "response"), h = 1, ...) ## S3 method for class 'ets' residuals(object, type = c("innovation", "response"), h = 1, ...) ## S3 method for class 'ARFIMA' residuals(object, type = c("innovation", "response"), ...) ## S3 method for class 'nnetar' residuals(object, type = c("innovation", "response"), h = 1, ...) ## S3 method for class 'stlm' residuals(object, type = c("innovation", "response"), ...) ## S3 method for class 'tslm' residuals( object, type = c("innovation", "response", "working", "deviance"), ... )## S3 method for class 'forecast' residuals(object, type = c("innovation", "response"), ...) ## S3 method for class 'ar' residuals(object, type = c("innovation", "response"), ...) ## S3 method for class 'Arima' residuals(object, type = c("innovation", "response", "regression"), h = 1, ...) ## S3 method for class 'bats' residuals(object, type = c("innovation", "response"), h = 1, ...) ## S3 method for class 'tbats' residuals(object, type = c("innovation", "response"), h = 1, ...) ## S3 method for class 'ets' residuals(object, type = c("innovation", "response"), h = 1, ...) ## S3 method for class 'ARFIMA' residuals(object, type = c("innovation", "response"), ...) ## S3 method for class 'nnetar' residuals(object, type = c("innovation", "response"), h = 1, ...) ## S3 method for class 'stlm' residuals(object, type = c("innovation", "response"), ...) ## S3 method for class 'tslm' residuals( object, type = c("innovation", "response", "working", "deviance"), ... )
object |
An object containing a time series model of class |
type |
Type of residual. The |
... |
Other arguments not used. |
h |
If |
Innovation residuals correspond to the white noise process that drives the
evolution of the time series model. Response residuals are the difference
between the observations and the fitted values (equivalent to h-step
forecasts). For functions with no h argument, h = 1. For
homoscedastic models, the innovation residuals and the response residuals
for h = 1 are identical. Regression residuals are available for
regression models with ARIMA errors, and are equal to the original data
minus the effect of the regression variables. If there are no regression
variables, the errors will be identical to the original series (possibly
adjusted to have zero mean). arima.errors is a deprecated function
which is identical to residuals.Arima(object, type="regression").
For nnetar objects, when type = "innovations" and lambda is used, a
matrix of time-series consisting of the residuals from each of the fitted neural networks is returned.
A ts object.
Rob J Hyndman
fitted.Arima(), checkresiduals().
fit <- Arima(lynx, order = c(4, 0, 0), lambda = 0.5) plot(residuals(fit)) plot(residuals(fit, type = "response"))fit <- Arima(lynx, order = c(4, 0, 0), lambda = 0.5) plot(residuals(fit)) plot(residuals(fit, type = "response"))
Fit a generalized random walk with Gaussian errors (and optional drift) to a univariate time series.
rw_model(y, lag = 1, drift = FALSE, lambda = NULL, biasadj = FALSE)rw_model(y, lag = 1, drift = FALSE, lambda = NULL, biasadj = FALSE)
y |
a numeric vector or univariate time series of class |
lag |
Lag parameter. |
drift |
Logical flag. If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
The model assumes that
where is the lag parameter,
is the drift parameter, and
are iid.
The model without drift has .
In the model with drift, is estimated
by the sample mean of the differences .
If , this is equivalent to an ARIMA(0,1,0) model with
an optional drift coefficient. For , it is equivalent to an
ARIMA(0,0,0)(0,1,0)p model.
The forecasts are given by
where is the integer part of .
For a regular random walk, and , so all forecasts are equal to the last observation.
Forecast standard errors allow for uncertainty in estimating the drift parameter
(unlike the corresponding forecasts obtained by fitting an ARIMA model
directly).
The generic accessor functions stats::fitted() and stats::residuals()
extract useful features of the object returned.
An object of class rw_model.
forecast.rw_model(), rwf(), naive(), snaive()
model <- rw_model(gold) forecast(model, h = 50) |> autoplot()model <- rw_model(gold) forecast(model, h = 50) |> autoplot()
Returns seasonally adjusted data constructed by removing the seasonal component.
seasadj(object, ...) ## S3 method for class 'stl' seasadj(object, ...) ## S3 method for class 'mstl' seasadj(object, ...) ## S3 method for class 'decomposed.ts' seasadj(object, ...) ## S3 method for class 'tbats' seasadj(object, ...) ## S3 method for class 'seas' seasadj(object, ...)seasadj(object, ...) ## S3 method for class 'stl' seasadj(object, ...) ## S3 method for class 'mstl' seasadj(object, ...) ## S3 method for class 'decomposed.ts' seasadj(object, ...) ## S3 method for class 'tbats' seasadj(object, ...) ## S3 method for class 'seas' seasadj(object, ...)
object |
Object created by |
... |
Other arguments not currently used. |
Univariate time series.
Rob J Hyndman
stats::stl(), stats::decompose(), tbats().
plot(AirPassengers) lines(seasadj(decompose(AirPassengers, "multiplicative")), col = 4)plot(AirPassengers) lines(seasadj(decompose(AirPassengers, "multiplicative")), col = 4)
Returns a univariate time series equal to either a seasonal component, trend-cycle component or remainder component from a time series decomposition.
seasonal(object) trendcycle(object) remainder(object)seasonal(object) trendcycle(object) remainder(object)
object |
Object created by |
Univariate time series.
Rob J Hyndman
stats::stl(), stats::decompose(), tbats(), seasadj().
plot(USAccDeaths) fit <- stl(USAccDeaths, s.window = "periodic") lines(trendcycle(fit), col = "red") library(ggplot2) autoplot( cbind( Data = USAccDeaths, Seasonal = seasonal(fit), Trend = trendcycle(fit), Remainder = remainder(fit) ), facets = TRUE ) + labs(x = "Year", y = "")plot(USAccDeaths) fit <- stl(USAccDeaths, s.window = "periodic") lines(trendcycle(fit), col = "red") library(ggplot2) autoplot( cbind( Data = USAccDeaths, Seasonal = seasonal(fit), Trend = trendcycle(fit), Remainder = remainder(fit) ), facets = TRUE ) + labs(x = "Year", y = "")
seasonaldummy returns a matrix of dummy variables suitable for use in
Arima(), auto.arima() or tslm(). The last season is omitted and used
as the control.
seasonaldummy(x, h = NULL) seasonaldummyf(x, h)seasonaldummy(x, h = NULL) seasonaldummyf(x, h)
x |
Seasonal time series: a |
h |
Number of periods ahead to forecast (optional) |
seasonaldummyf is deprecated, instead use the h argument in
seasonaldummy.
The number of dummy variables is determined from the time series
characteristics of x. When h is missing, the length of
x also determines the number of rows for the matrix returned by
seasonaldummy. the value of h determines the number of rows
for the matrix returned by seasonaldummy, typically used for
forecasting. The values within x are not used.
Numerical matrix.
Rob J Hyndman
plot(ldeaths) # Using seasonal dummy variables month <- seasonaldummy(ldeaths) deaths.lm <- tslm(ldeaths ~ month) tsdisplay(residuals(deaths.lm)) ldeaths.fcast <- forecast( deaths.lm, data.frame(month = I(seasonaldummy(ldeaths, 36))) ) plot(ldeaths.fcast) # A simpler approach to seasonal dummy variables deaths.lm <- tslm(ldeaths ~ season) ldeaths.fcast <- forecast(deaths.lm, h = 36) plot(ldeaths.fcast)plot(ldeaths) # Using seasonal dummy variables month <- seasonaldummy(ldeaths) deaths.lm <- tslm(ldeaths ~ month) tsdisplay(residuals(deaths.lm)) ldeaths.fcast <- forecast( deaths.lm, data.frame(month = I(seasonaldummy(ldeaths, 36))) ) plot(ldeaths.fcast) # A simpler approach to seasonal dummy variables deaths.lm <- tslm(ldeaths ~ season) ldeaths.fcast <- forecast(deaths.lm, h = 36) plot(ldeaths.fcast)
Returns forecasts and other information for exponential smoothing forecasts
applied to y.
ses( y, h = 10, level = c(80, 95), fan = FALSE, initial = c("optimal", "simple"), alpha = NULL, lambda = NULL, biasadj = FALSE, x = y, ... ) holt( y, h = 10, damped = FALSE, level = c(80, 95), fan = FALSE, initial = c("optimal", "simple"), exponential = FALSE, alpha = NULL, beta = NULL, phi = NULL, lambda = NULL, biasadj = FALSE, x = y, ... ) hw( y, h = 2 * frequency(x), seasonal = c("additive", "multiplicative"), damped = FALSE, level = c(80, 95), fan = FALSE, initial = c("optimal", "simple"), exponential = FALSE, alpha = NULL, beta = NULL, gamma = NULL, phi = NULL, lambda = NULL, biasadj = FALSE, x = y, ... )ses( y, h = 10, level = c(80, 95), fan = FALSE, initial = c("optimal", "simple"), alpha = NULL, lambda = NULL, biasadj = FALSE, x = y, ... ) holt( y, h = 10, damped = FALSE, level = c(80, 95), fan = FALSE, initial = c("optimal", "simple"), exponential = FALSE, alpha = NULL, beta = NULL, phi = NULL, lambda = NULL, biasadj = FALSE, x = y, ... ) hw( y, h = 2 * frequency(x), seasonal = c("additive", "multiplicative"), damped = FALSE, level = c(80, 95), fan = FALSE, initial = c("optimal", "simple"), exponential = FALSE, alpha = NULL, beta = NULL, gamma = NULL, phi = NULL, lambda = NULL, biasadj = FALSE, x = y, ... )
y |
a numeric vector or univariate time series of class |
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
level |
Confidence levels for prediction intervals. |
fan |
If |
initial |
Method used for selecting initial state values. If
|
alpha |
Value of smoothing parameter for the level. If |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
x |
Deprecated. Included for backwards compatibility. |
... |
Other arguments passed to |
damped |
If |
exponential |
If |
beta |
Value of smoothing parameter for the trend. If |
phi |
Value of damping parameter if |
seasonal |
Type of seasonality in |
gamma |
Value of smoothing parameter for the seasonal component. If
|
ses, holt and hw are simply convenient wrapper functions for
forecast(ets(...)).
An object of class forecast.
An object of class forecast is a list usually containing at least
the following elements:
A list containing information about the fitted model
The name of the forecasting method as a character string
Point forecasts as a time series
Lower limits for prediction intervals
Upper limits for prediction intervals
The confidence values associated with the prediction intervals
The original time series.
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values.
Fitted values (one-step forecasts)
The function summary can be used to obtain and print a summary of the
results, while the functions plot and autoplot produce plots of the forecasts and
prediction intervals. The generic accessor functions fitted.values and residuals
extract various useful features from the underlying model.
Rob J Hyndman
Hyndman, R.J., Koehler, A.B., Ord, J.K., Snyder, R.D. (2008) Forecasting with exponential smoothing: the state space approach, Springer-Verlag: New York. https://robjhyndman.com/expsmooth/.
Hyndman and Athanasopoulos (2018) Forecasting: principles and practice, 2nd edition, OTexts: Melbourne, Australia. https://otexts.com/fpp2/
ets(), stats::HoltWinters(), rwf(), stats::arima().
fcast <- holt(airmiles) plot(fcast) deaths.fcast <- hw(USAccDeaths, h = 48) plot(deaths.fcast)fcast <- holt(airmiles) plot(fcast) deaths.fcast <- hw(USAccDeaths, h = 48) plot(deaths.fcast)
Returns a time series based on the model object object.
## S3 method for class 'ets' simulate( object, nsim = length(object$x), seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, ... ) ## S3 method for class 'Arima' simulate( object, nsim = length(object$x), seed = NULL, xreg = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'ar' simulate( object, nsim = object$n.used, seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, ... ) ## S3 method for class 'rw_model' simulate( object, nsim = length(object$x), seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'fracdiff' simulate( object, nsim = object$n, seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'nnetar' simulate( object, nsim = length(object$x), seed = NULL, xreg = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'modelAR' simulate( object, nsim = length(object$x), seed = NULL, xreg = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'tbats' simulate( object, nsim = length(object$y), seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, ... ) ## S3 method for class 'spline_model' simulate( object, nsim = length(object$y), seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... )## S3 method for class 'ets' simulate( object, nsim = length(object$x), seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, ... ) ## S3 method for class 'Arima' simulate( object, nsim = length(object$x), seed = NULL, xreg = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'ar' simulate( object, nsim = object$n.used, seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, ... ) ## S3 method for class 'rw_model' simulate( object, nsim = length(object$x), seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'fracdiff' simulate( object, nsim = object$n, seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'nnetar' simulate( object, nsim = length(object$x), seed = NULL, xreg = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'modelAR' simulate( object, nsim = length(object$x), seed = NULL, xreg = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... ) ## S3 method for class 'tbats' simulate( object, nsim = length(object$y), seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, ... ) ## S3 method for class 'spline_model' simulate( object, nsim = length(object$y), seed = NULL, future = TRUE, bootstrap = FALSE, innov = NULL, lambda = object$lambda, ... )
object |
An object representing a fitted time series model. For example,
it may be of class |
nsim |
Number of periods for the simulated series. Ignored if either
|
seed |
Either |
future |
Produce sample paths that are future to and conditional on the
data in |
bootstrap |
Do simulation using resampled errors rather than normally
distributed errors or errors provided as |
innov |
A vector of innovations to use as the error series. Ignored if
|
... |
Other arguments, not currently used. |
xreg |
New values of |
lambda |
Box-Cox transformation parameter. If |
With simulate.Arima(), the object should be produced by Arima() or
auto.arima(), rather than stats::arima(). By default, the error series
is assumed normally distributed and generated using stats::rnorm(). If
innov is present, it is used instead. If bootstrap = TRUE and
innov = NULL, the residuals are resampled instead.
When future = TRUE, the sample paths are conditional on the data. When
future = FALSE and the model is stationary, the sample paths do not
depend on the data at all. When future = FALSE and the model is
non-stationary, the location of the sample paths is arbitrary, so they all
start at the value of the first observation.
An object of class ts.
Rob J Hyndman
ets(), Arima(), auto.arima(), ar(), arfima(), nnetar().
fit <- ets(USAccDeaths) plot(USAccDeaths, xlim = c(1973, 1982)) lines(simulate(fit, 36), col = "red")fit <- ets(USAccDeaths) plot(USAccDeaths, xlim = c(1973, 1982)) lines(simulate(fit, 36), col = "red")
Returns vector containing the seasonal index for h future periods. If
the seasonal index is non-periodic, it uses the last values of the index.
sindexf(object, h)sindexf(object, h)
object |
Output from |
h |
Number of periods ahead to forecast. |
Time series
Rob J Hyndman
uk.stl <- stl(UKDriverDeaths, "periodic") uk.sa <- seasadj(uk.stl) uk.fcast <- holt(uk.sa, 36) seasf <- sindexf(uk.stl, 36) uk.fcast$mean <- uk.fcast$mean + seasf uk.fcast$lower <- uk.fcast$lower + cbind(seasf, seasf) uk.fcast$upper <- uk.fcast$upper + cbind(seasf, seasf) uk.fcast$x <- UKDriverDeaths plot(uk.fcast, main = "Forecasts from Holt's method with seasonal adjustment")uk.stl <- stl(UKDriverDeaths, "periodic") uk.sa <- seasadj(uk.stl) uk.fcast <- holt(uk.sa, 36) seasf <- sindexf(uk.stl, 36) uk.fcast$mean <- uk.fcast$mean + seasf uk.fcast$lower <- uk.fcast$lower + cbind(seasf, seasf) uk.fcast$upper <- uk.fcast$upper + cbind(seasf, seasf) uk.fcast$x <- UKDriverDeaths plot(uk.fcast, main = "Forecasts from Holt's method with seasonal adjustment")
Fits a state space model based on cubic smoothing splines. The cubic smoothing spline model is equivalent to an ARIMA(0,2,2) model but with a restricted parameter space. The advantage of the spline model over the full ARIMA model is that it provides a smooth historical trend as well as a linear forecast function. Hyndman, King, Pitrun, and Billah (2002) show that the forecast performance of the method is hardly affected by the restricted parameter space.
spline_model(y, method = c("gcv", "mle"), lambda = NULL, biasadj = FALSE)spline_model(y, method = c("gcv", "mle"), lambda = NULL, biasadj = FALSE)
y |
a numeric vector or univariate time series of class |
method |
Method for selecting the smoothing parameter. If
|
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
An object of class spline_model.
Rob J Hyndman
Hyndman, King, Pitrun and Billah (2005) Local linear forecasts using cubic smoothing splines. Australian and New Zealand Journal of Statistics, 47(1), 87-99. https://robjhyndman.com/publications/splinefcast/.
stats::smooth.spline(), stats::arima(), holt().
fit <- spline_model(uspop) fit fit |> forecast() |> autoplot()fit <- spline_model(uspop) fit fit |> forecast() |> autoplot()
Generates forecasts from forecast.ts and adds them to the plot.
Forecasts can be modified via sending forecast specific arguments above.
StatForecast GeomForecast geom_forecast( mapping = NULL, data = NULL, stat = "forecast", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, PI = TRUE, showgap = TRUE, series = NULL, ... )StatForecast GeomForecast geom_forecast( mapping = NULL, data = NULL, stat = "forecast", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, PI = TRUE, showgap = TRUE, series = NULL, ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The stat object used to calculate the data. |
position |
Position adjustment, either as a string, or the result of a call to a position adjustment function. |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
PI |
If |
showgap |
If |
series |
Matches an unidentified forecast layer with a coloured object on the plot. |
... |
Additional arguments for |
Multivariate forecasting is supported by having each time series on a different group.
You can also pass geom_forecast a forecast object to add it to
the plot.
The aesthetics required for the forecasting to work includes forecast
observations on the y axis, and the time of the observations on the x
axis. Refer to the examples below. To automatically set up aesthetics, use
autoplot.
A layer for a ggplot graph.
Mitchell O'Hara-Wild
generics::forecast(), ggplot2::ggproto()
## Not run: library(ggplot2) autoplot(USAccDeaths) + geom_forecast() lungDeaths <- cbind(mdeaths, fdeaths) autoplot(lungDeaths) + geom_forecast() # Using fortify.ts p <- ggplot(aes(x = x, y = y), data = USAccDeaths) p <- p + geom_line() p + geom_forecast() # Without fortify.ts data <- data.frame(USAccDeaths = as.numeric(USAccDeaths), time = as.numeric(time(USAccDeaths))) p <- ggplot(aes(x = time, y = USAccDeaths), data = data) p <- p + geom_line() p + geom_forecast() p + geom_forecast(h = 60) p <- ggplot(aes(x = time, y = USAccDeaths), data = data) p + geom_forecast(level = c(70, 98)) p + geom_forecast(level = c(70, 98), colour = "lightblue") #Add forecasts to multivariate series with colour groups lungDeaths <- cbind(mdeaths, fdeaths) autoplot(lungDeaths) + geom_forecast(forecast(mdeaths), series = "mdeaths") ## End(Not run)## Not run: library(ggplot2) autoplot(USAccDeaths) + geom_forecast() lungDeaths <- cbind(mdeaths, fdeaths) autoplot(lungDeaths) + geom_forecast() # Using fortify.ts p <- ggplot(aes(x = x, y = y), data = USAccDeaths) p <- p + geom_line() p + geom_forecast() # Without fortify.ts data <- data.frame(USAccDeaths = as.numeric(USAccDeaths), time = as.numeric(time(USAccDeaths))) p <- ggplot(aes(x = time, y = USAccDeaths), data = data) p <- p + geom_line() p + geom_forecast() p + geom_forecast(h = 60) p <- ggplot(aes(x = time, y = USAccDeaths), data = data) p + geom_forecast(level = c(70, 98)) p + geom_forecast(level = c(70, 98), colour = "lightblue") #Add forecasts to multivariate series with colour groups lungDeaths <- cbind(mdeaths, fdeaths) autoplot(lungDeaths) + geom_forecast(forecast(mdeaths), series = "mdeaths") ## End(Not run)
Forecasts of STL objects are obtained by applying a non-seasonal forecasting
model to the seasonally adjusted data and re-seasonalizing using the last
year of the seasonal component. stlm takes a time series y, applies an STL decomposition, and
models the seasonally adjusted data using the model passed as
modelfunction or specified using method. It returns an object
that includes the original STL decomposition and a time series model fitted
to the seasonally adjusted data. This object can be passed to the
forecast.stlm for forecasting.
stlm( y, s.window = 7 + 4 * seq_len(6), t.window = NULL, robust = FALSE, method = c("ets", "arima"), modelfunction = NULL, model = NULL, etsmodel = "ZZN", lambda = NULL, biasadj = FALSE, xreg = NULL, allow.multiplicative.trend = FALSE, x = y, ... )stlm( y, s.window = 7 + 4 * seq_len(6), t.window = NULL, robust = FALSE, method = c("ets", "arima"), modelfunction = NULL, model = NULL, etsmodel = "ZZN", lambda = NULL, biasadj = FALSE, xreg = NULL, allow.multiplicative.trend = FALSE, x = y, ... )
y |
a numeric vector or univariate time series of class |
s.window |
Either the character string |
t.window |
A number to control the smoothness of the trend. See
|
robust |
If |
method |
Method to use for forecasting the seasonally adjusted series. |
modelfunction |
An alternative way of specifying the function for
modelling the seasonally adjusted series. If |
model |
Output from a previous call to |
etsmodel |
The ets model specification passed to
|
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
xreg |
Historical regressors to be used in
|
allow.multiplicative.trend |
If |
x |
Deprecated. Included for backwards compatibility. |
... |
Other arguments passed to |
The time series model for the seasonally adjusted data can be specified in
stlm using either method or modelfunction. The
method argument provides a shorthand way of specifying
modelfunction for a few special cases. More generally,
modelfunction can be any function with first argument a ts
object, that returns an object that can be passed to forecast().
For example, modelfunction = ar uses the ar() function
for modelling the seasonally adjusted series.
An object of class stlm.
Rob J Hyndman
tsmod <- stlm(USAccDeaths, modelfunction = ar) forecast(tsmod, h = 36) |> autoplot() decomp <- stl(USAccDeaths, s.window = "periodic") forecast(decomp) |> autoplot()tsmod <- stlm(USAccDeaths, modelfunction = ar) forecast(tsmod, h = 36) |> autoplot() decomp <- stl(USAccDeaths, s.window = "periodic") forecast(decomp) |> autoplot()
Various types of subsetting of a time series. Allows subsetting by index
values (unlike stats::window()). Also allows extraction of the
values of a specific season or subset of seasons in each year. For example,
to extract all values for the month of May from a time series.
## S3 method for class 'ts' subset( x, subset = NULL, month = NULL, quarter = NULL, season = NULL, start = NULL, end = NULL, ... ) ## S3 method for class 'msts' subset(x, subset = NULL, start = NULL, end = NULL, ...)## S3 method for class 'ts' subset( x, subset = NULL, month = NULL, quarter = NULL, season = NULL, start = NULL, end = NULL, ... ) ## S3 method for class 'msts' subset(x, subset = NULL, start = NULL, end = NULL, ...)
x |
A univariate time series to be subsetted. |
subset |
Optional logical expression indicating elements to keep;
missing values are taken as false. |
month |
Numeric or character vector of months to retain. Partial matching on month names used. |
quarter |
Numeric or character vector of quarters to retain. |
season |
Numeric vector of seasons to retain. |
start |
Index of start of contiguous subset. |
end |
Index of end of contiguous subset. |
... |
Other arguments, unused. |
If character values for months are used, either upper or lower case may be
used, and partial unambiguous names are acceptable. Possible character
values for quarters are "Q1", "Q2", "Q3", and "Q4".
If subset is used, a numeric vector is returned with no ts
attributes. If start and/or end are used, a ts object is
returned consisting of x[start:end], with the appropriate time series
attributes retained. Otherwise, a ts object is returned with frequency equal
to the length of month, quarter or season.
Rob J Hyndman
plot(subset(gas, month = "November")) subset(woolyrnq, quarter = 3) subset(USAccDeaths, start = 49)plot(subset(gas, month = "November")) subset(woolyrnq, quarter = 3) subset(USAccDeaths, start = 49)
Half-hourly electricity demand in England and Wales from Monday 5 June 2000 to Sunday 27 August 2000. Discussed in Taylor (2003), and kindly provided by James W Taylor. Units: Megawatts
data(taylor)data(taylor)
Time series data
James W Taylor
Taylor, J.W. (2003) Short-term electricity demand forecasting using double seasonal exponential smoothing. Journal of the Operational Research Society, 54, 799-805.
plot(taylor)plot(taylor)
Fits a TBATS model applied to y, as described in De Livera, Hyndman &
Snyder (2011). Parallel processing is used by default to speed up the
computations.
tbats( y, use.box.cox = NULL, use.trend = NULL, use.damped.trend = NULL, seasonal.periods = NULL, use.arma.errors = TRUE, use.parallel = length(y) > 1000, num.cores = 2, bc.lower = 0, bc.upper = 1, biasadj = FALSE, model = NULL, ... )tbats( y, use.box.cox = NULL, use.trend = NULL, use.damped.trend = NULL, seasonal.periods = NULL, use.arma.errors = TRUE, use.parallel = length(y) > 1000, num.cores = 2, bc.lower = 0, bc.upper = 1, biasadj = FALSE, model = NULL, ... )
y |
The time series to be forecast. Can be |
use.box.cox |
|
use.trend |
|
use.damped.trend |
|
seasonal.periods |
If |
use.arma.errors |
|
use.parallel |
|
num.cores |
The number of parallel processes to be used if using
parallel processing. If |
bc.lower |
The lower limit (inclusive) for the Box-Cox transformation. |
bc.upper |
The upper limit (inclusive) for the Box-Cox transformation. |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
model |
Output from a previous call to |
... |
Additional arguments to be passed to |
An object with class c("tbats", "bats"). The generic accessor
functions fitted.values() and residuals() extract useful features
of the value returned by bats() and associated functions. The fitted
model is designated TBATS(omega, p,q, phi, <m1,k1>,...,<mJ,kJ>) where omega
is the Box-Cox parameter and phi is the damping parameter; the error is
modelled as an ARMA(p,q) process and m1,...,mJ list the seasonal periods
used in the model and k1,...,kJ are the corresponding number of Fourier
terms used for each seasonality.
Slava Razbash and Rob J Hyndman
De Livera, A.M., Hyndman, R.J., & Snyder, R. D. (2011), Forecasting time series with complex seasonal patterns using exponential smoothing, Journal of the American Statistical Association, 106(496), 1513-1527.
## Not run: fit <- tbats(USAccDeaths) plot(forecast(fit)) taylor.fit <- tbats(taylor) plot(forecast(taylor.fit)) ## End(Not run)## Not run: fit <- tbats(USAccDeaths) plot(forecast(fit)) taylor.fit <- tbats(taylor) plot(forecast(taylor.fit)) ## End(Not run)
Extract the level, slope and seasonal components of a TBATS model. The extracted components are Box-Cox transformed using the estimated transformation parameter.
tbats.components(x)tbats.components(x)
x |
A tbats object created by |
A multiple time series (mts) object. The first series is the observed time series. The second series is the trend component of the fitted model. Series three onwards are the seasonal components of the fitted model with one time series for each of the seasonal components. All components are transformed using estimated Box-Cox parameter.
Slava Razbash and Rob J Hyndman
De Livera, A.M., Hyndman, R.J., & Snyder, R. D. (2011), Forecasting time series with complex seasonal patterns using exponential smoothing, Journal of the American Statistical Association, 106(496), 1513-1527.
## Not run: fit <- tbats(USAccDeaths, use.parallel = FALSE) components <- tbats.components(fit) plot(components) ## End(Not run)## Not run: fit <- tbats(USAccDeaths, use.parallel = FALSE) components <- tbats.components(fit) plot(components) ## End(Not run)
The theta method of Assimakopoulos and Nikolopoulos (2000) is equivalent to simple exponential smoothing with drift (Hyndman and Billah, 2003). This function fits the theta model to a time series. The series is tested for seasonality using the test outlined in A&N. If deemed seasonal, the series is seasonally adjusted using a classical multiplicative decomposition before fitting the theta model.
theta_model( y, lambda = NULL, biasadj = FALSE, type = c("multiplicative", "additive") )theta_model( y, lambda = NULL, biasadj = FALSE, type = c("multiplicative", "additive") )
y |
a numeric vector or univariate time series of class |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
type |
Type of seasonal decomposition. Either |
More general theta methods are available in the forecTheta package.
An object of class theta_model.
Rob J Hyndman
Assimakopoulos, V. and Nikolopoulos, K. (2000). The theta model: a decomposition approach to forecasting. International Journal of Forecasting 16, 521-530.
Hyndman, R.J., and Billah, B. (2003) Unmasking the Theta method. International J. Forecasting, 19, 287-290.
nile_fit <- theta_model(Nile) forecast(nile_fit) |> autoplot()nile_fit <- theta_model(Nile) forecast(nile_fit) |> autoplot()
Uses supsmu for non-seasonal series and a robust STL decomposition for seasonal series. To estimate missing values and outlier replacements, linear interpolation is used on the (possibly seasonally adjusted) series
tsclean(x, replace.missing = TRUE, iterate = 2, lambda = NULL)tsclean(x, replace.missing = TRUE, iterate = 2, lambda = NULL)
x |
Time series. |
replace.missing |
If |
iterate |
The number of iterations required. |
lambda |
Box-Cox transformation parameter. If |
Time series
Rob J Hyndman
Hyndman (2021) "Detecting time series outliers" https://robjhyndman.com/hyndsight/tsoutliers/.
na.interp(), tsoutliers(), stats::supsmu()
cleangold <- tsclean(gold)cleangold <- tsclean(gold)
tsCV computes the forecast errors obtained by applying
forecastfunction to subsets of the time series y using a
rolling forecast origin.
tsCV(y, forecastfunction, h = 1, window = NULL, xreg = NULL, initial = 0, ...)tsCV(y, forecastfunction, h = 1, window = NULL, xreg = NULL, initial = 0, ...)
y |
a numeric vector or univariate time series of class |
forecastfunction |
Function to return an object of class
|
h |
Number of periods for forecasting. Default value is twice the largest seasonal period (for seasonal data) or ten (for non-seasonal data). |
window |
Length of the rolling window, if NULL, a rolling window will not be used. |
xreg |
Exogenous predictor variables passed to the forecast function if required. |
initial |
Initial period of the time series where no cross-validation is performed. |
... |
Other arguments are passed to |
Let y contain the time series . Then
forecastfunction is applied successively to the time series
, for , making predictions
. The errors are given by . If h=1, these are returned as a
vector, . For h>1, they are returned as a matrix with
the hth column containing errors for forecast horizon h.
The first few errors may be missing as
it may not be possible to apply forecastfunction to very short time
series.
Numerical time series object containing the forecast errors as a vector (if h=1) and a matrix otherwise. The time index corresponds to the last period of the training data. The columns correspond to the forecast horizons.
Rob J Hyndman
CV(), CVar(), residuals.Arima(), https://robjhyndman.com/hyndsight/tscv/.
#Fit an AR(2) model to each rolling origin subset far2 <- function(x, h) forecast(Arima(x, order = c(2, 0, 0)), h = h) e <- tsCV(lynx, far2, h = 1) #Fit the same model with a rolling window of length 30 e <- tsCV(lynx, far2, h = 1, window = 30) #Example with exogenous predictors far2_xreg <- function(x, h, xreg, newxreg) { forecast(Arima(x, order = c(2, 0, 0), xreg = xreg), xreg = newxreg) } y <- ts(rnorm(50)) xreg <- matrix(rnorm(100), ncol = 2) e <- tsCV(y, far2_xreg, h = 3, xreg = xreg)#Fit an AR(2) model to each rolling origin subset far2 <- function(x, h) forecast(Arima(x, order = c(2, 0, 0)), h = h) e <- tsCV(lynx, far2, h = 1) #Fit the same model with a rolling window of length 30 e <- tsCV(lynx, far2, h = 1, window = 30) #Example with exogenous predictors far2_xreg <- function(x, h, xreg, newxreg) { forecast(Arima(x, order = c(2, 0, 0), xreg = xreg), xreg = newxreg) } y <- ts(rnorm(50)) xreg <- matrix(rnorm(100), ncol = 2) e <- tsCV(y, far2_xreg, h = 3, xreg = xreg)
tslm is used to fit linear models to time series including trend and
seasonality components.
tslm(formula, data, subset, lambda = NULL, biasadj = FALSE, ...)tslm(formula, data, subset, lambda = NULL, biasadj = FALSE, ...)
formula |
An object of class "formula" (or one that can be coerced to that class): a symbolic description of the model to be fitted. |
data |
An optional data frame, list or environment (or object coercible by as.data.frame to a data frame) containing the variables in the model. If not found in data, the variables are taken from environment(formula), typically the environment from which lm is called. |
subset |
An optional subset containing rows of data to keep. For best
results, pass a logical vector of rows to keep. Also supports |
lambda |
Box-Cox transformation parameter. If |
biasadj |
Use adjusted back-transformed mean for Box-Cox
transformations. If transformed data is used to produce forecasts and fitted
values, a regular back transformation will result in median forecasts. If
biasadj is |
... |
Other arguments passed to |
tslm is largely a wrapper for stats::lm() except that
it allows variables "trend" and "season" which are created on the fly from
the time series characteristics of the data. The variable "trend" is a
simple time trend and "season" is a factor indicating the season (e.g., the
month or the quarter depending on the frequency of the data).
Returns an object of class "lm".
Mitchell O'Hara-Wild and Rob J Hyndman
y <- ts(rnorm(120, 0, 3) + 1:120 + 20 * sin(2 * pi * (1:120) / 12), frequency = 12) fit <- tslm(y ~ trend + season) plot(forecast(fit, h = 20))y <- ts(rnorm(120, 0, 3) + 1:120 + 20 * sin(2 * pi * (1:120) / 12), frequency = 12) fit <- tslm(y ~ trend + season) plot(forecast(fit, h = 20))
Uses supsmu for non-seasonal series and a periodic stl decomposition with seasonal series to identify outliers and estimate their replacements.
tsoutliers(x, iterate = 2, lambda = NULL)tsoutliers(x, iterate = 2, lambda = NULL)
x |
Time series. |
iterate |
The number of iterations required. |
lambda |
Box-Cox transformation parameter. If |
index |
Indicating the index of outlier(s) |
replacement |
Suggested numeric values to replace identified outliers |
Rob J Hyndman
Hyndman (2021) "Detecting time series outliers" https://robjhyndman.com/hyndsight/tsoutliers/.
data(gold) tsoutliers(gold)data(gold) tsoutliers(gold)
Australian total wine sales by wine makers in bottles <= 1 litre. Jan 1980 – Aug 1994.
data(wineind)data(wineind)
Time series data
Time Series Data Library. https://pkg.yangzhuoranyang.com/tsdl/
tsdisplay(wineind)tsdisplay(wineind)
Quarterly production of woollen yarn in Australia: tonnes. Mar 1965 – Sep 1994.
data(woolyrnq)data(woolyrnq)
Time series data
Time Series Data Library. https://pkg.yangzhuoranyang.com/tsdl/
tsdisplay(woolyrnq)tsdisplay(woolyrnq)