% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tscv.R
\name{tsCV}
\alias{tsCV}
\title{Time series cross-validation}
\usage{
tsCV(y, forecastfunction, h = 1, window = NULL, xreg = NULL, initial = 0, ...)
}
\arguments{
\item{y}{a numeric vector or univariate time series of class \code{ts}}

\item{forecastfunction}{Function to return an object of class
\code{forecast}. Its first argument must be a univariate time series, and it
must have an argument \code{h} for the forecast horizon. If exogenous predictors are used,
then it must also have \code{xreg} and \code{newxreg} arguments corresponding to the
training and test periods.}

\item{h}{Number of periods for forecasting. Default value is twice the
largest seasonal period (for seasonal data) or ten (for non-seasonal data).}

\item{window}{Length of the rolling window, if NULL, a rolling window will not be used.}

\item{xreg}{Exogenous predictor variables passed to the forecast function if required.}

\item{initial}{Initial period of the time series where no cross-validation is performed.}

\item{...}{Other arguments are passed to \code{forecastfunction}.}
}
\value{
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.
}
\description{
\code{tsCV} computes the forecast errors obtained by applying
\code{forecastfunction} to subsets of the time series \code{y} using a
rolling forecast origin.
}
\details{
Let \code{y} contain the time series \eqn{y_1,\dots,y_T}{y[1:T]}. Then
\code{forecastfunction} is applied successively to the time series
\eqn{y_1,\dots,y_t}{y[1:t]}, for \eqn{t=1,\dots,T-h}, making predictions
\eqn{\hat{y}_{t+h|t}}{f[t+h]}. The errors are given by \eqn{e_{t+h} =
y_{t+h}-\hat{y}_{t+h|t}}{e[t+h] = y[t+h]-f[t+h]}. If h=1, these are returned as a
vector, \eqn{e_1,\dots,e_T}{e[1:T]}. 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 \code{forecastfunction} to very short time
series.
}
\examples{

#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)

}
\seealso{
\code{\link[=CV]{CV()}}, \code{\link[=CVar]{CVar()}}, \code{\link[=residuals.Arima]{residuals.Arima()}}, \url{https://robjhyndman.com/hyndsight/tscv/}.
}
\author{
Rob J Hyndman
}
\keyword{ts}
