\name{ARMAacf}
\alias{ARMAacf}
\title{Compute Theoretical ACF for an ARMA Process}
\description{
 Compute the theoretical autocorrelation function or partial
 autocorrelation function for an ARMA process.
}
\usage{
ARMAacf(ar = numeric(0), ma = numeric(0), lag.max = r, pacf = FALSE)
}
\arguments{
  \item{ar}{numeric vector of AR coefficients}
  \item{ma}{numeric vector of MA coefficients}
  \item{lag.max}{integer. Maximum lage required. Defaults to
    \code{max(p, q+1)}, where \code{p, q} are the numbers of AR and MA
    terms respectively.}
  \item{pacf}{logical. Should the partial autocorrelations be returned?}
}
\details{
  The methods used follow Brockwell \& Davis (1991, section 3.3).  Their
  equations (3.3.8) are solved for the autocovariances at lags
  \eqn{0, \dots, \max(p, q+1)}, and the remaining autocorrelations are
  given by a recursive filter.
}
\value{
  A vector of (partial) autocorrelations, named by the lags.  
}
\author{B. D. Ripley}

\references{
  Brockwell, P. J. and Davis, R. A. (1991) \emph{Time Series: Theory and
    Methods}, Second Edition.  Springer.
}
\seealso{\code{\link{arima}}, \code{\link{ARMAtoMA}}, \code{\link{filter}}.}

\examples{
ARMAacf(c(1.0, -0.25), 1.0, lag.max = 10)
## Example from Brockwell & Davis (1991, pp.92-4)
## answer 2^(-n) * (32/3 + 8 * n) /(32/3)
n <- 1:10; 2^(-n) * (32/3 + 8 * n) /(32/3)
ARMAacf(c(1.0, -0.25), 1.0, lag.max = 10, pacf = TRUE)
ARMAacf(c(1.0, -0.25), lag.max = 10, pacf = TRUE)
}
\keyword{ts}
\name{ARMAtoMA}
\alias{ARMAtoMA}
\title{Convert ARMA Process to Infinite MA Process}
\description{
  Convert ARMA process to infinite MA process.
}
\usage{
ARMAtoMA(ar = numeric(0), ma = numeric(0), lag.max)
}
\arguments{
  \item{ar}{numeric vector of AR coefficients}
  \item{ma}{numeric vector of MA coefficients}
  \item{lag.max}{Largest MA(Inf) coefficient required.}
}
\value{
  A vector of coefficients.
}
\author{B. D. Ripley}

\references{
  Brockwell, P. J. and Davis, R. A. (1991) \emph{Time Series: Theory and
    Methods}, Second Edition.  Springer.
}

\seealso{\code{\link{arima}}, \code{\link{ARMAacf}}.}

\examples{
ARMAtoMA(c(1.0, -0.25), 1.0, 10)
## Example from Brockwell & Davis (1991, p.92)
## answer (1 + 3*n)*2^(-n)
n <- 1:10; (1 + 3*n)*2^(-n)
}
\keyword{ts}

\name{AirPassengers}
\docType{data}
\alias{AirPassengers}
\title{Monthly Airline Passenger Numbers 1949-1960}
\description{
 The classic Box \& Jenkins airline data.  Monthly totals of
 international airline passengers, 1949 to 1960.
}
\usage{data(AirPassengers)}
\format{
  A monthly time series, in thousands.
}
\source{
  Box, G. E. P., Jenkins, G. M. and Reinsel, G. C. (1976)
  \emph{Time Series Analysis, Forecasting and Control.}
  Third Edition. Holden-Day. Series G.
}
 \examples{
\dontrun{## These are quite slow and so not run by example(AirPassengers)

data(AirPassengers)
## The classic `airline model', by full ML
(fit <- arima(log10(AirPassengers), c(0, 1, 1),
              seasonal = list(order=c(0, 1 ,1), period=12)))
update(fit, method = "CSS")
update(fit, x=window(log10(AirPassengers), start = 1954))
pred <- predict(fit, n.ahead = 24)
tl <- pred$pred - 1.96 * pred$se
tu <- pred$pred + 1.96 * pred$se
ts.plot(AirPassengers, 10^tl, 10^tu, log = "y", lty = c(1,2,2))

## full ML fit is the same if the series is reversed, CSS fit is not
ap0 <- rev(log10(AirPassengers))
attributes(ap0) <- attributes(AirPassengers)
arima(ap0, c(0, 1, 1), seasonal = list(order=c(0, 1 ,1), period=12))
arima(ap0, c(0, 1, 1), seasonal = list(order=c(0, 1 ,1), period=12),
      method = "CSS")

## Structural Time Series
ap <- log10(AirPassengers) - 2
(fit <- StructTS(ap, type= "BSM"))
par(mfrow=c(1,2))
plot(cbind(ap, fitted(fit)), plot.type = "single")
plot(cbind(ap, tsSmooth(fit)), plot.type = "single")
}}
\keyword{datasets}
\name{BJsales}
\alias{BJsales}
\alias{BJsales.lead}
\title{
  Sales Data with Leading Indicator.
}
\usage{
data(BJsales)
}
\description{
  The sales time series \code{BJsales} and leading indicator
  \code{BJsales.lead} each contain 150 observations.
  The objects are of class \code{"ts"}.
}
\source{
  The data are given in Box & Jenkins (1976).
  Obtained from the Time Series Data Library at
  \url{http://www-personal.buseco.monash.edu.au/~hyndman/TSDL/}
}

\references{
  G. E. P. Box and G. M. Jenkins (1976): \emph{Time Series
    Analysis, Forecasting and Control}, Holden-Day, San
  Francisco, p. 537.

  P. J. Brockwell and R. A. Davis (1991): \emph{Time Series:
    Theory and Methods}, Second edition, Springer Verlag, NY, pp. 414.
}
\keyword{datasets}
\name{EuStockMarkets}
\alias{EuStockMarkets}
\title{
  Daily Closing Prices of Major European Stock Indices, 1991-1998.
}
\usage{
data(EuStockMarkets)
}
\format{
  A multivariate time series with 1860 observations on 4 variables.
  The object is of class \code{"mts"}.
}
\description{
   Contains the daily closing prices of major European stock indices:
   Germany DAX (Ibis), Switzerland SMI, France CAC, and UK FTSE. The data
   are sampled in business time, i.e., weekends and holidays are omitted.
}

\source{
  The data were kindly provided by Erste Bank AG, Vienna, Austria.
}
\keyword{datasets}


\name{HoltWinters}
\alias{HoltWinters}
\alias{print.HoltWinters}
\alias{residuals.HoltWinters}
\title{Holt-Winters Filtering}
\description{
  Computes Holt-Winters Filtering of a given time series.
  Unknown parameters are determined by minimizing the squared
  prediction error.
}
\usage{
HoltWinters(x, alpha = NULL, beta = NULL, gamma = NULL,
          seasonal = "additive", start.periods = 3,
          l.start = NULL, b.start = NULL, s.start = NULL)
}
\arguments{
  \item{x}{An object of class \code{ts}}
  \item{alpha}{\eqn{alpha} parameter of Holt-Winters Filter}
  \item{beta}{\eqn{beta} parameter of Holt-Winters Filter. If set to 0,
    the function will do exponential smoothing.}
  \item{gamma}{\eqn{gamma} parameter used for the seasonal component.
    If set to 0, an non-seasonal model is fitted.}
  \item{seasonal}{Selects an \code{"additive"} or \code{"multiplicative"}
    seasonal model. (Only takes effect if \code{gamma} is non-zero).}
  \item{start.periods}{Start periods used in the autodetection of start
    values. Must be at least 3.}
  \item{l.start}{Start value for level (a[0]).}
  \item{b.start}{Start value for trend (b[0]).}
  \item{s.start}{Vector of start values for the seasonal component
    (\eqn{s_1[0]...s_p[0]}{s_1[0]...s_p[0]})}
}
\details{
  The additive Holt-Winters prediction function (for time series with
  period length p) is
  \deqn{\hat Y[t+h] = a[t] + h b[t] + s[t + 1 + (h - 1) \bmod p],}{
    Yhat[t+h] = a[t] + h * b[t] + s[t + 1 + (h - 1) mod p],}
  where \eqn{a[t]}, \eqn{b[t]} and \eqn{s[t]} are given by
  \deqn{a[t] = \alpha (Y[t] - s[t-p])  + (1-\alpha) (a[t-1] + b[t-1])}{
  a[t] = \alpha (Y[t] - s[t-p])  + (1-\alpha) (a[t-1] + b[t-1])}
  \deqn{b[t] = \beta (a[t] -a[t-1]) + (1-\beta)  b[t-1]}{
  b[t] = \beta (a[t] - a[t-1]) + (1-\beta) b[t-1]}
  \deqn{s[t] = \gamma (Y[t] - a[t])   + (1-\gamma) s[t-p]}{
  s[t] = \gamma (Y[t] - a[t]) + (1-\gamma) s[t-p]}

  The multiplicative Holt-Winters prediction function (for time series
  with period length p) is
  \deqn{\hat Y[t+h] = (a[t] + h b[t]) \times s[t + 1 + (h - 1) \bmod p].}{
    Yhat[t+h] = (a[t] + h * b[t]) * s[t + 1 + (h - 1) mod p],}
  where \eqn{a[t]}, \eqn{b[t]} and \eqn{s[t]} are given by
  \deqn{a[t] = \alpha (Y[t] / s[t-p])  + (1-\alpha) (a[t-1] + b[t-1])}{
  a[t] = \alpha (Y[t] / s[t-p])  + (1-\alpha) (a[t-1] + b[t-1])}
  \deqn{b[t] = \beta (a[t] - a[t-1]) + (1-\beta) b[t-1]}{
  b[t] = \beta (a[t] - a[t-1]) + (1-\beta) b[t-1]}
  \deqn{s[t] = \gamma (Y[t] / a[t])   + (1-\gamma) s[t-p]}{
  s[t] = \gamma  (Y[t] / a[t])  + (1-\gamma) s[t-p]}

  The function tries to find the optimal values of \eqn{\alpha} and/or
  \eqn{\beta} and/or \eqn{\gamma} by minimizing the squared
  one-step prediction error if they are omitted.

  For seasonal models, start values for \code{a}, \code{b} and \code{s}
  are detected by performing a simple decomposition in trend and seasonal
  component using moving averages (see function \code{decompose}) on the
  \code{start.periods} first periods (a simple linear regression on the
  trend component is used for starting level and trend.). For
  level/trend-models (no seasonal component), start values for \code{a}
  and \code{b} are \code{x[2]} and \code{x[2] - x[1]}, respectively. For
  level-only models (ordinary exponential smoothing), the start value for
  \code{a} is \code{x[1]}.
}
\value{
  An object of class \code{"HoltWinters"}, a list with components:
  \item{fitted}{The filtered time series}
  \item{x}{The original series}
  \item{alpha}{alpha used for filtering}
  \item{beta}{beta used for filtering}
  \item(gamma){gamma used for filtering}
  \item{coefficients}{A vector with named components \code{a, b, s1, ..., sp}
    containing the estimated values for the level, trend and seasonal
    components}
  \item{seasonal}{The specified \code{seasonal}-parameter}
  \item{SSE}{The final sum of squared errors achieved in optimizing}
  \item{call}{The call used}
}
\references{
  C.C Holt (1957)
  Forecasting seasonals and trends by exponentially weighted
  moving averages,
  ONR Research Memorandum, Carnigie Institute 52.

  P.R Winters (1960)
  Forecasting sales by exponentially weighted moving averages,
  \emph{Management Science} \bold{6}, 324--342.
}
\author{
  David Meyer \email{david.meyer@ci.tuwien.ac.at}
}
\seealso{\code{\link{predict.HoltWinters}}}

\examples{
library(ts)
data(co2)

%% Seasonal Holt-Winters
(m <- HoltWinters(co2))
plot(m)

data(AirPassengers)
(m <- HoltWinters(AirPassengers, seasonal = "mult"))
plot(m)

%% Non-Seasonal Holt-Winters
data(uspop)
x <- uspop + rnorm(uspop, sd = 5)
m <- HoltWinters(x, gamma = 0)
plot(m)

%% Exponential Smoothing
m2 <- HoltWinters(x, gamma = 0, beta = 0)
lines(fitted(m2), col = 3)
}
\keyword{ts}



\name{JohnsonJohnson}
\docType{data}
\alias{JohnsonJohnson}
\title{Quarterly Earnings per Johnson \& Johnson Share}
\description{
  Quarterly earnings (dollars) per Johnson \& Johnson share 1960--80.
}
\usage{data(JohnsonJohnson)}
\format{
  A quarterly time series
}
\source{
  Shumway, R. H. and Stoffer, D. S. (2000)
  \emph{Time Series Analysis and its Applications}.
  Second Edition.  Springer.  Example 1.1.
}
\examples{
data(JohnsonJohnson)
JJ <- log10(JohnsonJohnson)
plot(JJ)
(fit <- StructTS(JJ, type="BSM"))
tsdiag(fit)
sm <- tsSmooth(fit)
plot(cbind(JJ, sm[, 1], sm[, 3]-0.5), plot.type = "single",
     col = c("black", "green", "blue"))
abline(h = -0.5, col = "grey60")

monthplot(fit)
}
\keyword{datasets}
\name{KalmanLike}
\alias{KalmanLike}
\alias{KalmanRun}
\alias{KalmanSmooth}
\alias{KalmanForecast}
\alias{makeARIMA}
\title{Kalman Filtering}
\description{
  Use Kalman Filtering to find the (Gaussian) log-likelihood, or for
  forecasting or smoothing.
}
\usage{
KalmanLike(y, mod, nit = 0)
KalmanRun(y, mod, nit = 0)
KalmanSmooth(y, mod, nit = 0)
KalmanForecast(n.ahead = 10, mod)
makeARIMA(phi, theta, Delta, kappa = 1e6)
}
\arguments{
  \item{y}{a univariate time series.}
  \item{mod}{A list describing the state-space model: see Details.}
  \item{nit}{The time at which the initialization is computed.
    \code{nit = 0} implies that the initialization is for a one-step
    prediction, so \code{Pn} should not be computed at the first step.}
  \item{n.ahead}{The number of steps ahead for which prediction is
    required.}
  \item{phi, theta}{numeric vectors of length \eqn{\ge 0}{>=0} giving AR
    and MA parameters.}
  \item{Delta}{vector of differencing coefficients, so an ARMA model is
    fitted to \code{y[t] - Delta[1]*y[t-1] - \dots}.}
  \item{kappa}{the prior variance (as a multiple of the innovations
    variance) for the past observations in a differenced model.}
}
\details{
  These functions work with a general univariate state-space model
  with state vector \code{a}, transitions \code{a <- T a + e}, \eqn{e ~
    N(0, \kappa Q)} and observation equation \code{y = Z'a + R eta},
  \eqn{eta ~ N(0, \kappa h)}.  The likelihood is a profile likelihood
  after estimation of \eqn{\kappa}.

  The model is specified as a list with at least components
  \describe{
    \item{\code{T}}{the transition matrix}
    \item{\code{Z}}{the observation coeficients}
    \item{\code{h}}{the observation variance}
    \item{\code{V}}{\code{RQR'}}
    \item{\code{a}}{the current state estimate}
    \item{\code{P}}{the current estimate of the state uncertainty matrix}
    \item{\code{Pn}}{the estimate at time \eqn{t-1} of the state
      uncertainty matrix}
  }

  \code{KalmanSmooth} is the workhorse function for
  \code{\link{tsSmooth}}.
  
  \code{makeARIMA} constructs the state-space model for an ARIMA model.
}

\value{
  For \code{KalmanLike}, a list with components \code{Lik} (the
  log-likelihood less some constants) and \code{s2}, the estimate of
  of \eqn{\kappa}.

  For \code{KalmanRun}, a list with components \code{values}, a vector
  of length 2 giving the output of \code{KalmanLike}, \code{resid} (the
  residuals) and \code{states}, the contemporaneous state estimates,
  a matrix with one row for each time.

  For \code{KalmanSmooth}, a list with two components.
  Component \code{smooth} is a \code{n} by \code{p} matrix of state
  estimates based on all the observations, with one row for each time.
  Component \code{smooth} is a \code{n} by \code{p} by \code{p} array of
  variance matrices.
  
  For \code{KalmanForecast}, a list with components \code{pred}, the
  predictions, and \code{var}, the unscaled variances of the prediction
  errors (to be muliplied by \code{s2}).

  For \code{makeARIMA}, a model list including components for
  its arguments.
}

\section{Warning}{
  These functions are designed to be called from other functions which
  check the validity of the arguments passed, so very little checking is
  done.
}

\references{
  Durbin, J. and Koopman, S. J. (2001) \emph{Time Series Analysis by
    State Space Methods.}  Oxford University Press.
}
\author{B. D. Ripley}

\seealso{
   \code{\link{arima}}, \code{\link{StructTS}}. \code{\link{tsSmooth}}.
 }
\keyword{ts}
\name{LakeHuron}
\alias{LakeHuron}
\title{Level of Lake Huron 1875--1972}
\description{
  Annual measurements of the level, in feet, of Lake Huron 1875--1972.
}
\usage{data(LakeHuron)}
\format{
  A time series of length 98.
}
\source{
  Brockwell, P. J. & Davis, R. A. (1991).
  \emph{Time Series and Forecasting Methods}.
  Second edition. Springer, New York. Series A, page 555.

  Brockwell, P. J. & Davis, R. A. (1996).
  \emph{Introduction to Time Series and Forecasting}.
  Springer, New York.
  Sections 5.1 and 7.6.
}
\keyword{datasets}
\name{Nile}
\docType{data}
\alias{Nile}
\title{Flow of the River Nile}
\usage{data(Nile)}
\description{
  Measurements of the annual flow of the river Nile at Ashwan 1871--1970.
}
\format{
  A time series of length 100.
}
\source{
  Durbin, J. and Koopman, S. J. (2001) \emph{Time Series Analysis by
    State Space Methods.}  Oxford University Press.
  \url{http://www.ssfpack.com/dkbook/}
}
\references{
  Balke, N. S. (1993) Detecting level shifts in time series.
  \emph{Journal of Business and Economic Statistics} \bold{11}, 81--92.
  
  Cobb, G. W. (1978) The problem of the Nile: conditional solution to a
  change-point problem.  \emph{Biometrika} \bold{65}, 243--51.
}
\examples{
data(Nile)
par(mfrow = c(2,2))
plot(Nile)
acf(Nile)
pacf(Nile)
ar(Nile) # selects order 2
cpgram(ar(Nile)$resid)
par(mfrow = c(1,1))
arima(Nile, c(2, 0, 0))

## Now consider missing values, following Durbin & Koopman
NileNA <- Nile
NileNA[c(21:40, 61:80)] <- NA
arima(NileNA, c(2, 0, 0))
plot(NileNA)
pred <- predict(arima(window(NileNA, 1871, 1890), c(2, 0, 0)), n.ahead = 20)
lines(pred$pred, lty = 3, col = "red")
lines(pred$pred + 2*pred$se, lty=2, col="blue")
lines(pred$pred - 2*pred$se, lty=2, col="blue")
pred <- predict(arima(window(NileNA, 1871, 1930), c(2, 0, 0)), n.ahead = 20)
lines(pred$pred, lty = 3, col = "red")
lines(pred$pred + 2*pred$se, lty=2, col="blue")
lines(pred$pred - 2*pred$se, lty=2, col="blue")

## Structural time series models
data(Nile, package = "ts")
par(mfrow = c(3, 1))
plot(Nile)
## local level model
(fit <- StructTS(Nile, type = "level"))
lines(fitted(fit), lty = 2)              # contempareneous smoothing
lines(tsSmooth(fit), lty = 2, col = 4)   # fixed-interval smoothing
plot(residuals(fit)); abline(h = 0, lty = 3)
## local trend model
(fit2 <- StructTS(Nile, type = "trend")) ## constant trend fitted
pred <- predict(fit, n.ahead = 30)
## with 50\% confidence interval
ts.plot(Nile, pred$pred, pred$pred + 0.67*pred$se, pred$pred -0.67*pred$se)

## Now consider missing values
plot(NileNA)
(fit3 <- StructTS(NileNA, type = "level"))
lines(fitted(fit3), lty = 2)
lines(tsSmooth(fit3), lty = 3)
plot(residuals(fit3)); abline(h = 0, lty = 3)
}
\keyword{datasets}
\name{StructTS}
\alias{StructTS}
\alias{print.StructTS}
\alias{predict.StructTS}
\title{Fit Structural Time Series}
\description{
  Fit a structural model for a time series by maximum likelihood.
}
\usage{
StructTS(x, type = c("level", "trend", "BSM"), init = NULL,
         fixed = NULL, optim.control = NULL)
}
\arguments{
  \item{x}{a univariate time series. Missing values are allowed.}

  \item{type}{the class of structural model.  If omitted, a BSM is used
    for a time series with \code{frequency(x) > 1}, and a local trend
    model otherwise.}

  \item{init}{initial values of the variance parameters.}

  \item{fixed}{optional numeric vector of the same length as the total
    number of parameters.  If supplied, only non-\code{NA} entries in
    \code{fixed} will be varied.  Probably most useful for setting
    variances to zero.}

  \item{optim.control}{List of control parameters for
    \code{\link{optim}}.  Method \code{"L-BFGS-B"} is used.}
}
\details{
 \emph{Structural time series} models are (linear Gaussian) state-space
 models for (univariate) time series based on a decomposition of the
 series into a number of components. They are specified by a set of
 error variances, some of which may be zero.

 The simplest model is the \emph{local level} model specified by
 \code{type = "level"}.  This has an underlying level \eqn{\mu_t}{m[t]} which
 evolves by
 \deqn{\mu_{t+1} = \mu_t + \xi_t,  \qquad \xi_t \sim N(0, \sigma^2_\xi)}{%
   m[t+1] = m[t] + xi[t], xi[t] ~ N(0, sigma^2_xi)}
 The observations are
 \deqn{x_t = \mu_t + \epsilon_t, \qquad \epsilon_t \sim  N(0, \sigma^2_\epsilon)}{%
   x[t] = m[t] + eps[t], exp[t] ~  N(0, sigma^2_eps)}
 There are two parameters, \eqn{\sigma^2_\xi}{sigma^2_xi}
 and \eqn{\sigma^2_\epsilon}{sigma^2_eps}.  It is an ARIMA(0,1,1) model,
 but with restrictions on the parameter set.

 The \emph{local linear trend model}, \code{type = "trend"}, has the same
 measurement equation, but with a time-varying slope in the dynamics for
 \eqn{\mu_t}{m[t]}, given by
 \deqn{
   \mu_{t+1} = \mu_t + \nu_t + \xi_t, \qquad  \xi_t \sim N(0, \sigma^2_\xi)
 }{%
   m[t+1] = m[t] + n[t] + xi[t], xi[t] ~ N(0, sigma^2_xi)
 }
 \deqn{
   \nu_{t+1} = \nu_t + \zeta_t, \qquad \zeta_t \sim N(0, \sigma^2_\zeta)
 }{%
   n[t+1] = n[t] + zeta[t],  zeta[t] ~ N(0, sigma^2_zeta)
 }
 with three variance parameters.  It is not uncommon to find
 \eqn{\sigma^2_\zeta = 0}{sigma^2_zeta = 0} (which reduces to the local
 level model) or \eqn{\sigma^2_\xi = 0}{sigma^2_xi = 0}, which ensures a
 smooth trend.  This is a restricted ARIMA(0,2,2) model.

 The \emph{basic structural model}, \code{type = "BSM"}, is a local
 trend model with an additional seasonal component. Thus the measurement
 equation is
 \deqn{x_t = \mu_t + \gamma_t + \epsilon_t, \qquad \epsilon_t \sim  N(0, \sigma^2_\epsilon)}{%
   x[t] = m[t] + s[t] + eps[t], exp[t] ~  N(0, sigma^2_eps)}
 where \eqn{\gamma_t}{s[t]} is a seasonal component with dynamics
 \deqn{
   \gamma_{t+1} = -\gamma_t + \cdots + \gamma_{t-s+2} + \omega_t, \qquad
   \omega_t \sim N(0, \sigma^2_\omega)
 }{%
   s[t+1] = -s[t] - \dots - s[t - s + 2] + w[t],  w[t] ~ N(0, sigma^2_w)
 }
 The boundary case \eqn{\sigma^2_\omega = 0}{sigma^2_w = 0} corresponds
 to a deterministic (but arbitrary) seasonal pattern.  (This is
 sometimes known as the `dummy variable' version of the BSM.)
}
\value{
  A list of class \code{"StructTS"} with components:

  \item{coef}{the estimated variances of the components.}
  \item{loglik}{the maximized log-likelihood.  Note that as all these
    models are non-stationary this includes a diffuse prior for some
    observations and hence is not comparable with \code{\link{arima}}
    nor different types of structural models.}
  \item{data}{the time series \code{x}.}
  \item{residuals}{the standardized residuals.}
  \item{fitted}{a multiple time series with one component for the level,
    slope and seasonal components, estimated contemporaneously (that is
    at time \eqn{t} and not at the end of the series.}
  \item{call}{the matched call.}
  \item{series}{the name of the series \code{x}.}
  \item{convergence}{the value returned by \code{\link{optim}}.}
  \item{model, model0}{Lists representing the Kalman Filter used in the
    fitting.  See \code{\link{KalmanLike}}.  \code{model0} is the
    initial state of the filter, \code{model} its final state.}
  \item{xtsp}{the \code{tsp} attributes of \code{x}.}
}
\references{
  Brockwell, P. J. & Davis, R. A. (1996).
  \emph{Introduction to Time Series and Forecasting}.
  Springer, New York.
  Sections 8.2 and 8.5.

  Durbin, J. and Koopman, S. J. (2001) \emph{Time Series Analysis by
    State Space Methods.}  Oxford University Press.
  
  Harvey, A. C. (1989)
  \emph{Forecasting, Structural Time Series Models and the Kalman Filter}.
  Cambridge University Press.

  Harvey, A. C. (1993) \emph{Time Series Models}.
  2nd Edition, Harvester Wheatsheaf.
}
\author{B. D. Ripley}

\note{
  Optimization of structural models is a lot harder than many of the
  references admit. For example, the \code{\link{AirPassengers}} data
  are considered in Brockwell \& Davis (1996): their solution appears to
  be a local maximum, but nowhere near as good a fit as that produced by
  \code{StructTS}.  It is quite common to find fits with one or more
  variances zero, and this can include \eqn{\sigma^2_\epsilon}{sigma^2_eps}.
}

\seealso{
  \code{\link{KalmanLike}}, \code{\link{tsSmooth}}
}

\examples{
## see also JohnsonJohnson, Nile and AirPassengers

data(treering)
trees <- window(treering, start=0)
(fit <- StructTS(trees, type = "level"))
plot(trees)
lines(fitted(fit), col = "green")
tsdiag(fit)

data(UKgas)
(fit <- StructTS(log10(UKgas), type = "BSM"))
par(mfrow = c(4, 1))
plot(log10(UKgas))
plot(cbind(fitted(fit), resids=resid(fit)), main = "UK gas consumption")
}
\keyword{ts}
\name{UKDriverDeaths}
\alias{UKDriverDeaths}
\alias{Seatbelts}
\title{
  Road Casualties in Great Britain 1969--84
}
\description{
  \code{UKDriverDeaths} is a time series giving the monthly totals
  of car drivers in
  Great Britain killed or seriously injured Jan 1969 to Dec 1984.
  Compulsory wearing of seat belts was introduced on 31 Jan 1983.

  \code{Seatbelts} is more information on the same problem.
}
\usage{
data(UKDriverDeaths)
data(Seatbelts)
}
\format{
  \code{Seatbelts} is a multiple time series, with columns
  \describe{
    \item{\code{DriversKilled}}{car drivers killed.}
    \item{\code{drivers}}{same as \code{UKDriverDeaths}.}
    \item{\code{front}}{front-seat passengers killed or seriously injured.}
    \item{\code{rear}}{rear-seat passengers killed or seriously injured.}
    \item{\code{kms}}{distance driven.}
    \item{\code{PetrolPrice}}{petrol price.}
    \item{\code{VanKilled}}{number of van (`light goods vehicle') drivers.}
    \item{\code{law}}{0/1: was the law in effect that month?}
  }
}
\source{
  Harvey, A.C. (1989)
  \emph{Forecasting, Structural Time Series Models and the Kalman Filter.}
  Cambridge University Press, pp. 519--523.

  Durbin, J. and Koopman, S. J. (2001) \emph{Time Series Analysis by
    State Space Methods.}  Oxford University Press.
  \url{http://www.ssfpack.com/dkbook/}
}
\references{
  Harvey, A. C. and Durbin, J. (1986) The effects of seat belt
  legislation on British road casualties: A case study in structural
  time series modelling. \emph{Journal of the Royal Statistical Society}
  series B, \bold{149}, 187--227.
}
\examples{
data(UKDriverDeaths)
## work with pre-seatbelt period to identify a model, use logs
work <- window(log10(UKDriverDeaths), end = 1982+11/12)
par(mfrow = c(3,1))
plot(work); acf(work); pacf(work)
par(mfrow = c(1,1))
(fit <- arima(work, c(1,0,0), seasonal = list(order= c(1,0,0))))
z <- predict(fit, n.ahead = 24)
ts.plot(log10(UKDriverDeaths), z$pred, z$pred+2*z$se, z$pred-2*z$se,
        lty = c(1,3,2,2), col = c("black", "red", "blue", "blue"))

## now see the effect of the explanatory variables
data(Seatbelts)
X <- Seatbelts[, c("kms", "PetrolPrice", "law")]
X[, 1] <- log10(X[, 1]) - 4
arima(log10(Seatbelts[, "drivers"]), c(1,0,0),
      seasonal = list(order= c(1,0,0)), xreg = X)
}
\keyword{datasets}
% file UKLungDeaths.Rd
% copyright (C) 1994-9 W. N. Venables and B. D. Ripley
%
\name{UKLungDeaths}
\alias{UKLungDeaths}
\alias{ldeaths}
\alias{fdeaths}
\alias{mdeaths}
\title{
Monthly Deaths from Lung Diseases in the UK
}
\usage{
data(UKLungDeaths)
}
\description{
    Three time series giving the monthly deaths from bronchitis,
    emphysema and asthma in the UK, 1974--1979,
    both sexes (\code{ldeaths}), males (\code{mdeaths}) and
    females (\code{fdeaths}).
}
\source{
P. J. Diggle (1990)
\emph{Time Series: A Biostatistical Introduction.}
Oxford, table A.3
}
\examples{
data(UKLungDeaths)
plot(ldeaths) 
plot(mdeaths, fdeaths) 
## Better labels:
yr <- floor(tt <- time(mdeaths))
plot(mdeaths, fdeaths,
     xy.labels = paste(month.abb[12*(tt - yr)], yr-1900, sep="'"))
}
\keyword{datasets}
\name{UKgas}
\docType{data}
\alias{UKgas}
\title{UK Quarterly Gas Consumption}
\usage{data(UKgas)}
\description{
  Quarterly UK gas consumption from 1960Q1 to 1986Q4, in millions of therms.
}
\format{
  A quarterly time series of length 108.
}
\source{
  Durbin, J. and Koopman, S. J. (2001) \emph{Time Series Analysis by
    State Space Methods.}  Oxford University Press.
  \url{http://www.ssfpack.com/dkbook/}
}
\examples{
data(UKgas)
## maybe str(UKgas) ; plot(UKgas) ...
}
\keyword{datasets}
% file USAccDeaths.Rd
% copyright (C) 1994-9 W. N. Venables and B. D. Ripley
%
\name{USAccDeaths}
\alias{USAccDeaths}
\title{
  Accidental Deaths in the US 1973--1978
}
\description{
  A time series giving the monthly totals of accidental deaths in the
  USA.  The values for the first six months of 1979 are 7798 7406 8363
  8460 9217 9316.
}
\usage{data(USAccDeaths)}
\source{
  P. J. Brockwell and R. A. Davis (1991)
  \emph{Time Series: Theory and Methods.}
  Springer, New York.
}
\keyword{datasets}
\name{WWWusage}
\docType{data}
\alias{WWWusage}
\title{Internet Usage per Minute}
\usage{data(WWWusage)}
\description{
  A time series of the numbers of users connected to the Internet
  through a server every minute.
}
\format{
  A time series of length 100.
}
\source{
  Durbin, J. and Koopman, S. J. (2001) \emph{Time Series Analysis by
    State Space Methods.}  Oxford University Press.
  \url{http://www.ssfpack.com/dkbook/} 
}
\references{
  Makridakis, S., Wheelwright, S. C. and Hyndman, R. J. (1998)
  \emph{Forecasting: Methods and Applications.} Wiley.
}
\examples{
data(WWWusage)
work <- diff(WWWusage)
par(mfrow = c(2,1)); plot(WWWusage); plot(work)
\dontrun{
aics <- matrix(, 6, 6, dimnames=list(p=0:5, q=0:5))
for(q in 1:5) aics[1, 1+q] <- arima(WWWusage, c(0,1,q),
    optim.control = list(maxit = 500))$aic
for(p in 1:5)
   for(q in 0:5) aics[1+p, 1+q] <- arima(WWWusage, c(p,1,q),
       optim.control = list(maxit = 500))$aic
round(aics - min(aics, na.rm=TRUE), 2)
}}
\keyword{datasets}
\name{acf}
\alias{acf}
\alias{ccf}
\alias{pacf}
\alias{pacf.default}
\alias{pacf.ts}
\alias{pacf.mts}
\title{Auto- and Cross- Covariance and -Correlation Function Estimation}
\description{
  The function \code{acf} computes (and by default plots) estimates of
  the autocovariance or autocorrelation function.  Function \code{pacf}
  is the function used for the partial autocorrelations.  Function
  \code{ccf} computes the cross-correlation or cross-covariance of two
  univariate series.
}
\usage{
acf(x, lag.max = NULL,
    type = c("correlation", "covariance", "partial"),
    plot = TRUE, na.action = na.fail, demean = TRUE, \dots)
pacf(x, lag.max = NULL, plot = TRUE, na.action = na.fail, \dots)
ccf(x, y, lag.max = NULL, type = c("correlation", "covariance"),
    plot = TRUE, na.action = na.fail, \dots)
}
\arguments{
  \item{x, y}{a univariate or multivariate (not \code{ccf}) time
    series object or a numeric vector or matrix.}
  \item{lag.max}{maximum number of lags at which to calculate the acf.
    Default is \eqn{10\log_{10}(N)}{10*log10(N)} where \eqn{N} is the
    number of observations.}
  \item{type}{character string giving the type of acf to be computed.
    Allowed values are
    \code{"correlation"} (the default), \code{"covariance"} or
    \code{"partial"}.}
  \item{plot}{logical. If \code{TRUE} the acf is plotted.}
  \item{na.action}{function to be called to handle missing
    values. \code{na.pass} can be used.}
  \item{demean}{logical.  Should the covariances be about the sample
    means?}
  \item{\dots}{further arguments to be passed to \code{plot.acf}.}
}
\value{
  An object of class \code{"acf"}, which is a list with the following
  elements:

  \item{lag}{A three dimensional array containing the lags at which
    the acf is estimated.}
  \item{acf}{An array with the same dimensions as \code{lag} containing
    the estimated acf.}
  \item{type}{The type of correlation (same as the \code{type}
    argument).}
  \item{n.used}{The number of observations in the time series.}
  \item{series}{The name of the series \code{x}.}
  \item{snames}{The series names for a multivariate time series.}

  The result is returned invisibly if \code{plot} is \code{TRUE}.
}
\details{
  For \code{type} = \code{"correlation"} and \code{"covariance"}, the
  estimates are based on the sample covariance.

  By default, no missing values are allowed.  If the \code{na.action}
  function passes through missing values (as \code{na.pass} does), the
  covariances are computed from the complete cases.  This means that the
  estimate computed may well not be a valid autocorrelation sequence,
  and may contain missing values.  Missing values are not allowed when
  computing the PACF of a multivariate time series.

  The partial correlation coefficient is estimated by fitting
  autoregressive models of successively higher orders up to
  \code{lag.max}.

  The generic function \code{plot} has a method for objects of class
  \code{"acf"}.

  The lag is returned and plotted in units of time, and not numbers of
  observations.
}
\author{
  Original: Paul Gilbert, Martyn Plummer.
  Extensive modifications and univariate case of \code{pacf} by
  B.D. Ripley.
}
\seealso{
  \code{\link{plot.acf}}
}
\examples{
## Examples from Venables & Ripley
data(lh)
acf(lh)
acf(lh, type = "covariance")
pacf(lh)

data(UKLungDeaths)
acf(ldeaths)
acf(ldeaths, ci.type = "ma")
acf(ts.union(mdeaths, fdeaths))
ccf(mdeaths, fdeaths) # just the cross-correlations.

data(presidents) # contains missing values
acf(presidents, na.action = na.pass)
pacf(presidents, na.action = na.pass)
}
\keyword{ts}
\name{acf2AR}
\alias{acf2AR}
\title{Compute an AR Process Exactly Fitting an ACF}
\description{
  Compute an AR process exactly fitting an autocorrelation function.
}
\usage{
acf2AR(acf)
}
\arguments{
  \item{acf}{An autocorrelation or autocovariance sequence.}
}
\value{
  A matrix, with one row for the computed AR(p) coefficients for
  \code{1 <= p <= length(acf)}.
}
\author{B. D. Ripley}
\seealso{
  \code{\link{ARMAacf}}, \code{\link{ar.yw}} which does this from an
  empirical ACF.
}
\examples{
(Acf <- ARMAacf(c(0.6, 0.3, -0.2)))
acf2AR(Acf)
}
\keyword{ts}
\name{ar}
\alias{ar}
\alias{ar.burg}
\alias{ar.burg.default}
\alias{ar.burg.mts}
\alias{ar.yw}
\alias{ar.yw.default}
\alias{ar.yw.mts}
\alias{ar.mle}
\alias{print.ar}
\alias{predict.ar}
\title{Fit Autoregressive Models to Time Series}
\usage{
ar(x, aic = TRUE, order.max = NULL,
   method=c("yule-walker", "burg", "ols", "mle", "yw"), na.action,
   series, \dots)
\method{ar.burg}{default}(x, aic = TRUE, order.max = NULL,
        na.action = na.fail, demean = TRUE, series, var.method = 1, \dots)
\method{ar.yw}{default}(x, aic = TRUE, order.max = NULL,
      na.action = na.fail, demean = TRUE, series, \dots)
ar.mle(x, aic = TRUE, order.max = NULL, na.action = na.fail, demean = TRUE,
       series, \dots)

\method{predict}{ar}(object, newdata, n.ahead = 1, se.fit = TRUE, \dots)
}
\arguments{
  \item{x}{A univariate or multivariate time series.}

  \item{aic}{Logical flag.  If \code{TRUE} then the Akaike Information
    Criterion is used to choose the order of the autoregressive
    model. If \code{FALSE}, the model of order \code{order.max} is
    fitted.}

  \item{order.max}{Maximum order (or order) of model to fit. Defaults
    to \eqn{10\log_{10}(N)}{10*log10(N)} where \eqn{N} is the number
    of observations except for \code{method="mle"} where it is the
    minimum of this quantity and 12.}

  \item{method}{Character string giving the method used to fit the
    model.  Must be one of the strings in the default argument
    (the first few characters are sufficient).  Defaults to
    \code{"yule-walker"}.}

  \item{na.action}{function to be called to handle missing values.}

  \item{demean}{should a mean be estimated during fitting?}

  \item{series}{names for the series.  Defaults to
    \code{deparse(substitute(x))}.}

  \item{var.method}{the method to estimate the innovations variance
    (see Details).}

  \item{\dots}{additional arguments for specific methods.}

  \item{object}{a fit from \code{ar}.}

  \item{newdata}{data to which to apply the prediction.}

  \item{n.ahead}{number of steps ahead at which to predict.}

  \item{se.fit}{logical: return estimated standard errors of the
    prediction error?}
}
\description{
  Fit an autoregressive time series model to the data, by default
  selecting the complexity by AIC.
}
\details{
  For definiteness, note that the AR coefficients have the sign in

  \deqn{x_t - \mu = a_1(x_{t-1} - \mu) + \cdots +  a_p(x_{t-p} - \mu) + e_t}{\code{(x[t] - m) = a[1]*(x[t-1] - m) + \dots +  a[p]*(x[t-p] - m) + e[t]}}

  \code{ar} is just a wrapper for the functions \code{ar.yw},
  \code{ar.burg}, \code{\link{ar.ols}} and \code{ar.mle}.

  Order selection is done by AIC if \code{aic} is true. This is
  problematic, as of the methods here only \code{ar.mle} performs
  true maximum likelihood estimation. The AIC is computed as if the variance
  estimate were the MLE, omitting the determinant term from the
  likelihood. Note that this is not the same as the Gaussian likelihood
  evaluated at the estimated parameter values. In \code{ar.yw} the
  variance matrix of the innovations is computed from the fitted
  coefficients and the autocovariance of \code{x}.

  \code{ar.burg} allows two methods to estimate the innovations
  variance and hence AIC. Method 1 is to use the update given by
  the Levinson-Durbin recursion (Brockwell and Davis, 1991, (8.2.6)
  on page 242), and follows S-PLUS. Method 2 is the mean of the sum
  of squares of the forward and backward prediction errors
  (as in Brockwell and Davis, 1996, page 145). Percival and Walden
  (1998) discuss both. In the multivariate case the estimated
  coefficients will depend (slightly) on the variance estimation method.

  Remember that \code{ar} includes by default a constant in the model, by
  removing the overall mean of \code{x} before fitting the AR model,
  or (\code{ar.mle}) estimating a constant to subtract.
}
\value{
  For \code{ar} and its methods a list of class \code{"ar"} with
  the following elements:
  \item{order}{The order of the fitted model.  This is chosen by
    minimizing the AIC if \code{aic=TRUE}, otherwise it is \code{order.max}.}
  \item{ar}{Estimated autoregression coefficients for the fitted model.}
  \item{var.pred}{The prediction variance: an estimate of the portion of the
    variance of the time series that is not explained by the
    autoregressive model.}
  \item{x.mean}{The estimated mean of the series used in fitting and for
    use in prediction.}
  \item{x.intercept}{(\code{ar.ols} only.) The intercept in the model for
    \code{x - x.mean}.}
  \item{aic}{The value of the \code{aic} argument.}
  \item{n.used}{The number of observations in the time series.}
  \item{order.max}{The value of the \code{order.max} argument.}
  \item{partialacf}{The estimate of the partial autocorrelation function
    up to lag \code{order.max}.}
  \item{resid}{residuals from the fitted model, conditioning on the
    first \code{order} observations. The first \code{order} residuals
    are set to \code{NA}. If \code{x} is a time series, so is \code{resid}.}
  \item{method}{The value of the \code{method} argument.}
  \item{series}{The name(s) of the time series.}
  \item{asy.var.coef}{(univariate case.) The asymptotic-theory
    variance matrix of the coefficient estimates.}

  For \code{predict.ar}, a time series of predictions, or if
  \code{se.fit = TRUE}, a list with components \code{pred}, the
  predictions, and \code{se}, the estimated standard errors. Both
  components are time series.
}
\author{
  Martyn Plummer. Univariate case of \code{ar.yw}, \code{ar.mle}
  and C code for univariate case of \code{ar.burg} by B. D. Ripley.
}

\note{
  Only the univariate case of \code{ar.mle} is implemented.

  Fitting by \code{method="mle"} to long series can be very slow.
}

\seealso{
  \code{\link{ar.ols}}, \code{\link{arima0}} for ARMA models.
}

\references{
  Brockwell, P. J. and Davis, R. A. (1991) \emph{Time
    Series and Forecasting Methods.}  Second edition. Springer, New
  York. Section 11.4.

  Brockwell, P. J. and Davis, R. A. (1996) \emph{Introduction to Time
    Series and Forecasting.} Springer, New York. Sections 5.1 and 7.6.

  Percival, D. P. and Walden, A. T. (1998) \emph{Spectral Analysis
    for Physical Applications.} Cambridge University Press.

  Whittle, P. (1963) On the fitting of multivariate autoregressions
  and the approximate canonical factorization of a spectral density
  matrix. \emph{Biometrika} \bold{40}, 129--134.
}

\examples{
data(lh)
ar(lh)
ar(lh, method="burg")
ar(lh, method="ols")
ar(lh, FALSE, 4) # fit ar(4)

data(sunspot)
(sunspot.ar <- ar(sunspot.year))
predict(sunspot.ar, n.ahead=25)
## try the other methods too

data(BJsales)
ar(ts.union(BJsales, BJsales.lead))
## Burg is quite different here, as is OLS (see ar.ols)
ar(ts.union(BJsales, BJsales.lead), method="burg")
}
\keyword{ts}
\name{ar.ols}
\alias{ar.ols}
\title{Fit Autoregressive Models to Time Series by OLS}
\usage{
ar.ols(x, aic = TRUE, order.max = NULL, na.action = na.fail,
       demean = TRUE, intercept = demean, series, \dots)
}
\arguments{
  \item{x}{A univariate or multivariate time series.}

  \item{aic}{Logical flag.  If \code{TRUE} then the Akaike Information
    Criterion is used to choose the order of the autoregressive
    model. If \code{FALSE}, the model of order \code{order.max} is
    fitted.}

  \item{order.max}{Maximum order (or order) of model to fit. Defaults
    to \eqn{10\log_{10}(N)}{10*log10(N)} where \eqn{N} is the number
    of observations.}

  \item{na.action}{function to be called to handle missing values.}

  \item{demean}{should the AR model be for \code{x} minus its mean?}

  \item{intercept}{should a separate intercept term be fitted?}

  \item{series}{names for the series.  Defaults to
    \code{deparse(substitute(x))}.}

  \item{\dots}{further arguments to be passed to or from methods.}
}
\description{
  Fit an autoregressive time series model to the data by ordinary
  least squares, by default selecting the complexity by AIC.
}
\details{
  \code{ar.ols} fits the general AR model to a possibly non-stationary
  and/or multivariate system of series \code{x}. The resulting
  unconstrained least squares estimates are consistent, even if
  some of the series are non-stationary and/or co-integrated.
  For definiteness, note that the AR coefficients have the sign in

  \deqn{x_t - \mu = a_0 + a_1(x_{t-1} - \mu) + \cdots + a_p(x_{t-p} - \mu) + e_t}{\code{(x[t] - m) = a[0] + a[1]*(x[t-1] - m) + \dots +  a[p]*(x[t-p] - m) + e[t]}}

  where \eqn{a_0}{a[0]} is zero unless \code{intercept} is true, and
  \eqn{\mu}{m} is the sample mean if \code{demean} is true, zero
  otherwise.

  Order selection is done by AIC if \code{aic} is true. This is
  problematic, as \code{ar.ols} does not perform
  true maximum likelihood estimation. The AIC is computed as if
  the variance estimate (computed from the variance matrix of the
  residuals) were the MLE, omitting the determinant term from the
  likelihood. Note that this is not the same as the Gaussian
  likelihood evaluated at the estimated parameter values.

  Some care is needed if \code{intercept} is true and \code{demean} is
  false. Only use this is the series are roughly centred on
  zero. Otherwise the computations may be inaccurate or fail entirely.
}
\value{
  A list of class \code{"ar"} with the following elements:
  \item{order}{The order of the fitted model.  This is chosen by
    minimizing the AIC if \code{aic=TRUE}, otherwise it is
    \code{order.max}.}
  \item{ar}{Estimated autoregression coefficients for the fitted
    model.}
  \item{var.pred}{The prediction variance: an estimate of the portion of
    the variance of the time series that is not explained by the
    autoregressive model.}
  \item{x.mean}{The estimated mean (or zero if \code{demean} is false)
    of the series used in fitting and for use in prediction.}
  \item{x.intercept}{The intercept in the model for
    \code{x - x.mean}, or zero if \code{intercept} is false.}
  \item{aic}{The value of the \code{aic} argument.}
  \item{n.used}{The number of observations in the time series.}
  \item{order.max}{The value of the \code{order.max} argument.}
  \item{partialacf}{\code{NULL}.  For compatibility with \code{ar}.}
  \item{resid}{residuals from the fitted model, conditioning on the
    first \code{order} observations.  The first \code{order} residuals
    are set to \code{NA}. If \code{x} is a time series, so is
    \code{resid}.}
  \item{method}{The character string \code{"Unconstrained LS"}.}
  \item{series}{The name(s) of the time series.}
  \item{asy.se.coef}{The asymptotic-theory standard errors of the
    coefficient estimates.}
}
\author{Adrian Trapletti, Brian Ripley.}
\seealso{
  \code{\link{ar}}
}
\references{
  Luetkepohl, H. (1991): \emph{Introduction to Multiple Time Series
    Analysis.} Springer Verlag, NY, pp. 368--370.
}
\examples{
data(lh)
ar(lh, method="burg")
ar.ols(lh)
ar.ols(lh, FALSE, 4) # fit ar(4)

data(BJsales)
ar.ols(ts.union(BJsales, BJsales.lead))

data(EuStockMarkets)
x <- diff(log(EuStockMarkets))
ar.ols(x, order.max=6, demean=FALSE, intercept=TRUE)
}
\keyword{ts}
\name{arima}
\alias{arima}
\alias{print.Arima}
\title{ARIMA Modelling of Time Series}
\description{
  Fit an ARIMA model to a univariate time series.
}
\usage{
arima(x, order = c(0, 0, 0),
      seasonal = list(order = c(0, 0, 0), period = NA),
      xreg = NULL, include.mean = TRUE, transform.pars = TRUE,
      fixed = NULL, init = NULL, method = c("CSS-ML", "ML", "CSS"),
      n.cond, optim.control = list(), kappa = 1e6)
}
\arguments{
  \item{x}{a univariate time series}

  \item{order}{A specification of the non-seasonal part of the ARIMA
    model: the three components \eqn{(p, d, q)} are the AR order, the
    degree of differencing, and the MA order.}

  \item{seasonal}{A specification of the seasonal part of the ARIMA
    model, plus the period (which defaults to \code{frequency(x)}).
    This should be a list with components \code{order} and
    \code{period}, but a specification of just a numeric vector of
    length 3 will be turned into a suitable list with the specification
    as the \code{order}.}

  \item{xreg}{Optionally, a vector or matrix of external regressors,
    which must have the same number of rows as \code{x}.}

  \item{include.mean}{Should the ARIMA model include
    a mean term? The default is \code{TRUE} for undifferenced series,
    \code{FALSE} for differenced ones (where a mean would not affect
    the fit nor predictions).}

  \item{transform.pars}{Logical.  If true, the AR parameters are
    transformed to ensure that they remain in the region of
    stationarity.  Not used for \code{method = "CSS"}.}

  \item{fixed}{optional numeric vector of the same length as the total
    number of parameters.  If supplied, only non-\code{NA} entries in
    \code{fixed} will be varied.  \code{transform.pars = TRUE}
    will be overridden if any AR parameters are fixed.}

  \item{init}{optional numeric vector of initial parameter
    values. Missing values will be filled in, by zeroes except for
    regression coefficients.}

  \item{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.}

  \item{n.cond}{Only used if fitting by conditional-sum-of-squares: the
    number of initial observations to ignore.  It will be ignored if
    less than the maximum lag of an AR term.}

  \item{optim.control}{List of control parameters for \code{\link{optim}}.}

  \item{kappa}{the prior variance (as a multiple of the innovations
    variance) for the past observations in a differenced model.  Do not
    reduce this.}
}
\details{
  Different definitions of ARMA models have different signs for the
  AR and/or MA coefficients. The definition here has

  \deqn{X_t = a_1X_{t-1} + \cdots + a_pX_{t-p} + e_t + b_1e_{t-1} + \dots + b_qe_{t-q}}{\code{X[t] = a[1]X[t-1] + \dots + a[p]X[t-p] + e[t] + b[1]e[t-1] + \dots + b[q]e[t-q]}}

  and so the MA coefficients differ in sign from those of
  S-PLUS.  Further, if \code{include.mean} is true, this formula
  applies to \eqn{X-m} rather than \eqn{X}.  For ARIMA models with
  differencing, the differenced series follows a zero-mean ARMA model.

  The variance matrix of the estimates is found from the Hessian of
  the log-likelihood, and so may only be a rough guide.

  Optimization is done by \code{\link{optim}}. It will work
  best if the columns in \code{xreg} are roughly scaled to zero mean
  and unit variance, but does attempt to estimate suitable scalings.
}
\section{Fitting methods}{
  The exact likelihood is computed via a state-space representation of
  the ARIMA process, and the innovations and their variance found by a
  Kalman filter.  The initialization of the differenced ARMA process uses
  stationarity and is based on Gardner \emph{et al.} (1980).  For a
  differenced process the non-stationary components are given a diffuse
  prior (controlled by \code{kappa}).  Observations which are still
  controlled by the diffuse prior (determined by having a Kalman gain of
  at least \code{1e4}) are excluded from the likelihood calculations.
  (This gives comparable results to \code{\link{arima0}} in the absence
  of missing values, when the observations excluded are precisely those
  dropped by the differencing.)
  
  Missing values are allowed, and are handled exactly in method \code{"ML"}.

  If \code{transform.pars} is true, the optimization is done using an
  alternative parametrization which is a variation on that suggested by
  Jones (1980) and ensures that the model is stationary.  For an AR(p)
  model the parametrization is via the inverse tanh of the partial
  autocorrelations: the same procedure is applied (separately) to the
  AR and seasonal AR terms.  The MA terms are not constrained to be
  invertible during optimization, but they will be converted to
  invertible form after optimization if \code{transform.pars} is true.

  Conditional sum-of-squares is provided mainly for expositional
  purposes.  This computes the sum of squares of the fitted innovations
  from observation \code{n.cond} on, (where \code{n.cond} is at least
  the maximum lag of an AR term), treating all earlier innovations to
  be zero.  Argument \code{n.cond} can be used to allow comparability
  between different fits.  The ``part log-likelihood'' is the first
  term, half the log of the estimated mean square.  Missing values
  are allowed, but will cause many of the innovations to be missing.

  When regressors are specified, they are orthogonalized prior to
  fitting unless any of the coefficients is fixed.  It can be helpful to
  roughly scale the regressors to zero mean and unit variance.
}
\value{
  A list of class \code{"Arima"} with components:

  \item{coef}{a vector of AR, MA and regression coefficients,}

  \item{sigma2}{the MLE of the innovations variance.}

  \item{var.coef}{the estimated variance matrix of the coefficients
    \code{coef}.}

  \item{loglik}{the maximized log-likelihood (of the differenced data),
    or the approximation to it used.}

  \item{arma}{A compact form of the specification, as a vector giving
    the number of AR, MA, seasonal AR and seasonal MA coefficients,
    plus the period and the number of non-seasonal and seasonal
    differences.}

  \item{aic}{the AIC value corresponding to the log-likelihood. Only
    valid for \code{method = "ML"} fits.}

  \item{residuals}{the standardized residuals.}

  \item{call}{the matched call.}

  \item{series}{the name of the series \code{x}.}

  \item{convergence}{the value returned by \code{\link{optim}}.}

  \item{n.cond}{the number of initial observations not used in the fitting.}

  \item{model}{A list representing the Kalman Filter used in the
    fitting.  See \code{\link{KalmanLike}}.}
}
\references{
  Brockwell, P. J. and Davis, R. A. (1996) \emph{Introduction to Time
    Series and Forecasting.} Springer, New York. Sections 3.3 and 8.3.

  Durbin, J. and Koopman, S. J. (2001) \emph{Time Series Analysis by
    State Space Methods.}  Oxford University Press.

  Gardner, G, Harvey, A. C. and Phillips, G. D. A. (1980) Algorithm
  AS154. An algorithm for exact maximum likelihood estimation of
  autoregressive-moving average models by means of Kalman filtering.
  \emph{Applied Statistics} \bold{29}, 311--322.

  Harvey, A. C. (1993) \emph{Time Series Models},
  2nd Edition, Harvester Wheatsheaf, sections 3.3 and 4.4.

  Jones, R. H. (1980) Maximum likelihood fitting of ARMA models to time
  series with missing observations. \emph{Technometrics} \bold{20} 389--395.
}

\author{B. D. Ripley}
\note{
  The results are likely to be different from S-PLUS's
  \code{arima.mle}, which computes a conditional likelihood and does
  not include a mean in the model.  Further, the convention used by
  \code{arima.mle} reverses the signs of the MA coefficients.

  \code{arima} is very similar to \code{\link{arima0}} for
  ARMA models or for differenced models without missing values,
  but handles differenced models with missing values exactly.
  It is somewhat slower than \code{arima0}, particularly for seasonally
  differenced models.
}

\seealso{
  \code{\link{predict.Arima}}, \code{\link{tsdiag}},
  \code{\link{arima0}}, \code{\link{ar}}
}

\examples{
data(lh)
\dontrun{arima(lh, order = c(1,0,0))}
\testonly{(fit <- arima(lh, c(1,0,0))); tsdiag(fit)}
arima(lh, order = c(3,0,0))
arima(lh, order = c(1,0,1))

arima(lh, order = c(3,0,0), method = "CSS")

data(USAccDeaths)
arima(USAccDeaths, order = c(0,1,1), seasonal = list(order=c(0,1,1)))
arima(USAccDeaths, order = c(0,1,1), seasonal = list(order=c(0,1,1)),
      method = "CSS") # drops first 13 observations.
# for a model with as few years as this, we want full ML

data(LakeHuron)
arima(LakeHuron, order = c(2,0,0), xreg = time(LakeHuron)-1920)

data(presidents) # contains NAs
## graphs in example(acf) suggest order 1 or 3
(fit1 <- arima(presidents, c(1, 0, 0)))
tsdiag(fit1)
(fit3 <- arima(presidents, c(3, 0, 0)))  # smaller AIC
tsdiag(fit3)
}
\keyword{ts}
\name{arima.sim}
\alias{arima.sim}
\title{Simulate from an ARIMA Model}
\description{
  Simulate from an ARIMA model.
}
\usage{
arima.sim(model, n, rand.gen = rnorm, innov = rand.gen(n, ...),
          n.start = NA, ...)
}
\arguments{
  \item{model}{A list with component \code{ar} and/or \code{ma} giving
    the AR and MA coeffcients respectively.  Optionally a component
    \code{order} can be used.}
  \item{n}{length of output series.}
  \item{rand.gen}{optional: a function to generate the innovations.}
  \item{innov}{an optional times series of innovations.  If not
    provided, \code{rand.gen} is used.}
  \item{n.start}{length of ``burn-in'' period.  If \code{NA}, the
    default, a reasonable value is computed.}
  \item{\dots}{additional arguments for \code{rand.gen}.  Most usefully,
    the standard deviation of the innovations generated by \code{rnorm}
    can be specified by \code{sd}.}
}
\details{
  The ARMA model is checked for stationarity.

  ARIMA models are specified via the \code{order} component of
  \code{model}, in the same way as for \code{\link{arima}}.  Other
  aspects of the \code{order} component are ignored.
}
\value{
  A time-series object of class \code{"ts"}.
}
\seealso{
  \code{\link{arima.sim}}
}
\examples{
arima.sim(n = 63, list(ar = c(0.8897, -0.4858), ma = c(-0.2279, 0.2488)),
          sd = sqrt(0.1796))
# mildly long-tailed
arima.sim(n = 63, list(ar=c(0.8897, -0.4858), ma=c(-0.2279, 0.2488)),
          rand.gen = function(n, ...) sqrt(0.1796) * rt(n, df = 5))

# An ARIMA simulation
ts.sim <- arima.sim(list(order = c(1,1,0), ar = 0.7), n = 200)
ts.plot(ts.sim)
}
\keyword{ts}
\name{arima0}
\alias{arima0}
\alias{print.arima0}
\alias{predict.arima0}
\title{ARIMA Modelling of Time Series -- Preliminary Version}
\description{
  Fit an ARIMA model to a univariate time series, and forecast from
  the fitted model.
}
\usage{
arima0(x, order = c(0, 0, 0),
       seasonal = list(order = c(0, 0, 0), period = NA),
       xreg = NULL, include.mean = TRUE, delta = 0.01,
       transform.pars = TRUE, fixed = NULL, init = NULL,
       method = c("ML", "CSS"), n.cond, optim.control = list())

\method{predict}{arima0}(object, n.ahead = 1, newxreg, se.fit = TRUE, ...)
}
\arguments{
  \item{x}{a univariate time series}

  \item{order}{A specification of the non-seasonal part of the ARIMA
    model: the three components \eqn{(p, d, q)} are the AR order, the
    degree of differencing, and the MA order.}

  \item{seasonal}{A specification of the seasonal part of the ARIMA
    model, plus the period (which defaults to \code{frequency(x)}).
    This should be a list with components \code{order} and
    \code{period}, but a specification of just a numeric vector of
    length 3 will be turned into a suitable list with the specification
    as the \code{order}.}

  \item{xreg}{Optionally, a vector or matrix of external regressors,
    which must have the same number of rows as \code{x}.}

  \item{include.mean}{Should the ARIMA model include
    a mean term? The default is \code{TRUE} for undifferenced series,
    \code{FALSE} for differenced ones (where a mean would not affect
    the fit nor predictions).}

  \item{delta}{A value to indicate at which point `fast recursions'
    should be used. See the Details section.}

  \item{transform.pars}{Logical.  If true, the AR parameters are
    transformed to ensure that they remain in the region of
    stationarity.  Not used for \code{method = "CSS"}.}

  \item{fixed}{optional numeric vector of the same length as the total
    number of parameters.  If supplied, only non-\code{NA} entries in
    \code{fixed} will be varied.  \code{transform.pars = TRUE}
    will be overridden if any ARMA parameters are fixed.}

  \item{init}{optional numeric vector of initial parameter
    values. Missing values will be filled in, by zeroes except for
    regression coefficients.}

  \item{method}{Fitting method: maximum likelihood or minimize
    conditional sum-of-squares.}

  \item{n.cond}{Only used if fitting by conditional-sum-of-squares: the
    number of initial observations to ignore.  It will be ignored if
    less than the maximum lag of an AR term.}

  \item{optim.control}{List of control parameters for \code{\link{optim}}.}

  \item{object, fit}{The result of an \code{arima0} fit.}

  \item{newxreg}{New values of \code{xreg} to be used for
    prediction. Must have at least \code{n.ahead} rows.}

  \item{n.ahead}{The number of steps ahead for which prediction is required.}

  \item{se.fit}{Logical: should standard errors of prediction be returned?}

  \item{gof.lag}{Number of lags to be used in goodness-of-fit test.}

  \item{\dots}{arguments passed to or from other methods.}
}
\details{
  Different definitions of ARMA models have different signs for the
  AR and/or MA coefficients. The definition here has

  \deqn{X_t = a_1X_{t-1} + \cdots + a_pX_{t-p} + e_t + b_1e_{t-1} + \dots + b_qe_{t-q}}{\code{X[t] = a[1]X[t-1] + \dots + a[p]X[t-p] + e[t] + b[1]e[t-1] + \dots + b[q]e[t-q]}}

  and so the MA coefficients differ in sign from those of
  S-PLUS.  Further, if \code{include.mean} is true, this formula
  applies to \eqn{X-m} rather than \eqn{X}.  For ARIMA models with
  differencing, the differenced series follows a zero-mean ARMA model.

  The variance matrix of the estimates is found from the Hessian of
  the log-likelihood, and so may only be a rough guide, especially for
  fits close to the boundary of invertibility.

  Optimization is done by \code{\link{optim}}. It will work
  best if the columns in \code{xreg} are roughly scaled to zero mean
  and unit variance, but does attempt to estimate suitable scalings.

  Finite-history prediction is used. This is only statistically
  efficient if the MA part of the fit is invertible, so
  \code{predict.arima0} will give a warning for non-invertible MA
  models.
}
\section{Fitting methods}{
  The exact likelihood is computed via a state-space representation of
  the ARMA process, and the innovations and their variance found by a
  Kalman filter based on Gardner \emph{et al.} (1980).  This has
  the option to switch to `fast recursions' (assume
  an effectively infinite past) if the innovations variance is close
  enough to its asymptotic bound. The argument \code{delta} sets the
  tolerance: at its default value the approximation is normally
  negligible and the speed-up considerable.  Exact computations can be
  ensured by setting \code{delta} to a negative value.

  If \code{transform.pars} is true, the optimization is done using an
  alternative parametrization which is a variation on that suggested by
  Jones (1980) and ensures that the model is stationary.  For an AR(p)
  model the parametrization is via the inverse tanh of the partial
  autocorrelations: the same procedure is applied (separately) to the
  AR and seasonal AR terms.  The MA terms are also constrained to be
  invertible during optimization by the same transformation if
  \code{transform.pars} is true.  Note that the MLE for MA terms does
  sometimes occur for MA polynomials with unit roots: such models can be
  fitted by using \code{transform.pars = FALSE} and specifying a good
  set of initial values (often obtainable from a fit with
  \code{transform.pars = TRUE}).

  As from \R 1.5.0 missing values are allowed, but any missing values
  will force \code{delta} to be ignored and full recursions used.
  Note that missing values will be propogated by differencing, so the
  procedure used in this function is not fully efficient in that case.

  Conditional sum-of-squares is provided mainly for expositional
  purposes.  This computes the sum of squares of the fitted innovations
  from observation
  \code{n.cond} on, (where \code{n.cond} is at least the maximum lag of
  an AR term), treating all earlier innovations to be zero.  Argument
  \code{n.cond} can be used to allow comparability between different
  fits.  The ``part log-likelihood'' is the first term, half the log of the
  estimated mean square.  Missing values are allowed, but will cause
  many of the innovations to be missing.

  When regressors are specified, they are orthogonalized prior to
  fitting unless any of the coefficients is fixed.  It can be helpful to
  roughly scale the regressors to zero mean and unit variance.
}
\value{
  For \code{arima0}, a list of class \code{"arima0"} with components:

  \item{coef}{a vector of AR, MA and regression coefficients,}

  \item{sigma2}{the MLE of the innovations variance.}

  \item{var.coef}{the estimated variance matrix of the coefficients
    \code{coef}.}

  \item{loglik}{the maximized log-likelihood (of the differenced data),
    or the approximation to it used.}

  \item{arma}{A compact form of the specification, as a vector giving
    the number of AR, MA, seasonal AR and seasonal MA coefficients,
    plus the period and the number of non-seasonal and seasonal
    differences.}

  \item{aic}{the AIC value corresponding to the log-likelihood. Only
    valid for \code{method = "ML"} fits.  Prior to \R 1.5.0 this omitted
    \code{2} for the estimation of the innovations variance.}

  \item{residuals}{the standardized residuals. (Was \code{resid}
    prior to \R 1.5.0.)}

  \item{call}{the matched call.}

  \item{series}{the name of the series \code{x}.}

  \item{convergence}{the value returned by \code{\link{optim}}.}

  \item{n.cond}{the number of initial observations not used in the fitting.}

  For \code{predict.arima0}, a time series of predictions, or if
  \code{se.fit = TRUE}, a list with components \code{pred}, the
  predictions, and \code{se}, the estimated standard errors. Both
  components are time series.
}
\references{
  Brockwell, P. J. and Davis, R. A. (1996) \emph{Introduction to Time
    Series and Forecasting.} Springer, New York. Sections 3.3 and 8.3.

  Gardner, G, Harvey, A. C. and Phillips, G. D. A. (1980) Algorithm
  AS154. An algorithm for exact maximum likelihood estimation of
  autoregressive-moving average models by means of Kalman filtering.
  \emph{Applied Statistics} \bold{29}, 311--322.

  Harvey, A. C. (1993) \emph{Time Series Models},
  2nd Edition, Harvester Wheatsheaf, sections 3.3 and  4.4.

  Harvey, A. C. and McKenzie, C. R. (1982) Algorithm AS182.
  An algorithm for finite sample prediction from ARIMA processes.
  \emph{Applied Statistics} \bold{31}, 180--187.

  Jones, R. H. (1980) Maximum likelihood fitting of ARMA models to time
  series with missing observations. \emph{Technometrics} \bold{20} 389--395.
}

\author{B. D. Ripley}
\note{
  This is a preliminary version, and will be replaced by \code{\link{arima}}.

  The standard errors of prediction exclude the uncertainty in the
  estimation of the ARMA model and the regression coefficients.

  The results are likely to be different from S-PLUS's
  \code{arima.mle}, which computes a conditional likelihood and does
  not include a mean in the model.  Further, the convention used by
  \code{arima.mle} reverses the signs of the MA coefficients.
}

\seealso{\code{\link{arima}}, \code{\link{ar}}, \code{\link{tsdiag}}}

\examples{
data(lh)
\dontrun{arima0(lh, order = c(1,0,0))}
\testonly{(fit <- arima0(lh, c(1,0,0))); tsdiag(fit)}
arima0(lh, order = c(3,0,0))
arima0(lh, order = c(1,0,1))
predict(arima0(lh, order = c(3,0,0)), n.ahead = 12)

arima0(lh, order = c(3,0,0), method = "CSS")

data(USAccDeaths)
# for a model with as few years as this, we want full ML
(fit <- arima0(USAccDeaths, order = c(0,1,1),
               seasonal = list(order=c(0,1,1)), delta = -1))
predict(fit, n.ahead = 6)

data(LakeHuron)
arima0(LakeHuron, order = c(2,0,0), xreg = time(LakeHuron)-1920)
\dontrun{
data(presidents) # contains NAs
## graphs in example(acf) suggest order 1 or 3
(fit1 <- arima0(presidents, c(1, 0, 0), delta = -1))  # avoid warning
tsdiag(fit1)
(fit3 <- arima0(presidents, c(3, 0, 0), delta = -1))  # smaller AIC
tsdiag(fit3)}
}
\keyword{ts}
% file austres.Rd
% copyright (C) 1994-9 W. N. Venables and B. D. Ripley
%
\name{austres}
\alias{austres}
\title{
  Quarterly Time Series of the Number of Australian Residents
}
\description{
  Numbers (in thousands) of Australian residents measured quarterly from
  March 1971 to March 1994.  The object is of class \code{"ts"}.
}
\usage{data(austres)}
\source{
  P. J. Brockwell and R. A. Davis (1996)
  \emph{Introduction to Time Series and Forecasting.}
  Springer
}
\keyword{datasets}
% file beavers.Rd
% copyright (C) 1994-9 W. N. Venables and B. D. Ripley
%
\name{beavers}
\alias{beavers}
\alias{beaver1}
\alias{beaver2}
\title{Body Temperature Series of Two Beavers}
\usage{data(beavers)}
\description{
  Reynolds (1994) describes a small part of a study of the long-term
  temperature dynamics of beaver \emph{Castor canadensis} in
  north-central Wisconsin.  Body temperature was measured by telemetry
  every 10 minutes for four females, but data from a one period of
  less than a day for each of two animals is used there. 
}
\format{
  The \code{beaver1} data frame has 114 rows and 4 columns on body
  temperature measurements at 10 minute intervals.

  The \code{beaver2} data frame has 100 rows and 4 columns on body
  temperature measurements at 10 minute intervals.

  The variables are as follows:
  \describe{
    \item{day}{Day of observation (in days since the beginning of
      1990), December 12--13 (\code{beaver1}) and November 3--4
      (\code{beaver2}).}
    \item{time}{Time of observation, in the form \code{0330} for
      3:30am}
    \item{temp}{Measured body temperature in degrees Celsius.}
    \item{activ}{Indicator of activity outside the retreat.}
  }
}
\note{
  The observation at 22:20 is missing in \code{beaver1}.
}
\source{
  P. S. Reynolds (1994) Time-series analyses of beaver body
  temperatures.  Chapter 11 of Lange, N., Ryan, L., Billard, L.,
  Brillinger, D., Conquest, L. and Greenhouse, J. eds (1994)
  \emph{Case Studies in Biometry.}
  New York: John Wiley and Sons.
}
\examples{
data(beavers)
%% consider converting times to POSIXct (using `yday' ?)

(yl <- range(beaver1$temp, beaver2$temp))

beaver.plot <- function(bdat, ...) {
  nam <- deparse(substitute(bdat))  
  attach(bdat)
  # Hours since start of day:
  hours <- time \%/\% 100 + 24*(day - day[1]) + (time \%\% 100)/60
  plot (hours, temp, type = "l", ...,
        main = paste(nam, "body temperature"))
  abline(h = 37.5, col = "gray", lty = 2)
  is.act <- activ == 1
  points(hours[is.act], temp[is.act], col = 2, cex = .8)
}
op <- par(mfrow = c(2,1), mar = c(3,3,4,2), mgp = .9* 2:0)
 beaver.plot(beaver1, ylim = yl)
 beaver.plot(beaver2, ylim = yl)
par(op)
}
\keyword{datasets}
\name{Box.test}
\alias{Box.test}
\title{Box--Pierce and Ljung--Box Tests}
\usage{
Box.test (x, lag = 1, type=c("Box-Pierce", "Ljung-Box"))
}
\arguments{
  \item{x}{a numeric vector or univariate time series.}
  \item{lag}{the statistic will be based on \code{lag}
    autocorrelation coefficients.}
  \item{type}{test to be performed: partial matching is used.}
}
\description{
  Compute the Box--Pierce or Ljung--Box test statistic
  for examining the null hypothesis of independence in the
  time series \code{x} is computed.
}
\note{
  Missing values are not handled.
}
\value{
  A list with class \code{"htest"} containing the following components:
  \item{statistic}{the value of the test statistic.}
  \item{parameter}{the degrees of freedom of the approximate chi-squared
    distribution of the test statistic.}
  \item{p.value}{the p-value of the test.}
  \item{method}{a character string indicating which type of test was
    performed.}
  \item{data.name}{a character string giving the name of the data.}
}
\references{
  Box, G. E. P. and Pierce, D. A. (1970) Distribution of residual
  correlations in autoregressive-integrated moving average time series
  models. \emph{Journal of the American Statistical Association}
  \bold{65}, 1509--1526.
    
  Ljung, G. M. and Box, G. E. P. (1978) On a measure of lack of fit in
  time series models. \emph{Biometrika} \bold{65}, 553--564.
  
  Harvey, A. C. (1993) \emph{Time Series Models},
  2nd Edition, Harvester Wheatsheaf, NY, pp. 44, 45.
}
\author{A. Trapletti}
\examples{
x <- rnorm (100)
Box.test (x, lag = 1)
Box.test (x, lag = 1, type="Ljung")
}
\keyword{ts}

% file cpgram.Rd
% copyright (C) 1994-9 W. N. Venables and B. D. Ripley
%
\name{cpgram}
\alias{cpgram}
\title{
  Plot Cumulative Periodogram
}
\description{
  Plots a cumulative periodogram.
}
\usage{
cpgram(ts, taper=0.1, main=
         paste("Series: ", deparse(substitute(ts))), ci.col="blue")
}
\arguments{
  \item{ts}{a univariate time series}
  \item{taper}{proportion tapered in forming the periodogram}
  \item{main}{main title}
  \item{ci.col}{colour for confidence band.}
}
\value{
  None.
}
\section{Side Effects}{
  Plots the cumulative periodogram in a square plot.
}
\author{B.D. Ripley}
\note{
  From package \file{MASS}.
}
\examples{
par(pty = "s", mfrow = c(1,2))
data(lh)
cpgram(lh)
lh.ar <- ar(lh, order.max = 9)
cpgram(lh.ar$resid, main = "AR(3) fit to lh")

data(UKLungDeaths)
cpgram(ldeaths)
}
\keyword{ts}
\keyword{hplot}
\name{decompose}
\alias{decompose}
\alias{plot.decomposed.ts}
\title{
  Classical Seasonal Decomposition by Moving Averages
}
\description{
  Decompose a time series into seasonal, trend and irregular components
  using moving averages.  Deals with additive or multiplicative
  seasonal component.
}
\usage{
decompose(x, type = c("additive", "multiplicative"))
}
\arguments{
  \item{x}{A time series.}
  \item{type}{The type of seasonal component.}
}
\details{
The additive model used is:

Y[t] = T[t] + S[t] + e[t]

The multiplicative model used is:

Y[t] = T[t] * S[t] + e[t]
}
\note{
  The function \code{\link{stl}} provides a much more sophisticated
  decomposition.
}
\value{
  An object of class \code{"decomposed.ts"} with following components:
  \item{seasonal}{The seasonal component (i.e., the repeated seasonal figure)}
  \item{figure}{The estimated seasonal figure only}
  \item{trend}{The trend component}
  \item{random}{The remainder part}
  \item{type}{The value of \code{type}}
}
\author{
  David Meyer \email{david.meyer@ci.tuwien.ac.at}
}
\seealso{\code{\link{stl}}}

\examples{
data(co2)
m <- decompose(co2)
m$figure
plot(m)
}
\keyword{ts}
\name{diffinv}
\alias{diffinv}
\alias{diffinv.default}
\alias{diffinv.ts}
\alias{diffinv.vector}
\title{Discrete Integrals: Inverse of Differencing}
\description{
  Computes the inverse function of the lagged differences function
  \code{\link{diff}}. 
}
\synopsis{
diffinv(x, ...)
diffinv.default(x, lag = 1, differences = 1,
    xi = rep(0, lag * differences * dim(as.matrix(x))[2]), ...) 
diffinv.ts(x, lag = 1, differences = 1,
    xi = rep(0, lag * differences * NCOL(x)), ...) 
diffinv.vector(x, lag = 1, differences = 1,
    xi = rep(0, lag * differences), ...)
}
\usage{
diffinv(x, lag = 1, differences = 1,
        xi = rep(0.0, lag*differences*NCOL(x)), ...)
}
\arguments{
  \item{x}{a numeric vector, matrix, or time series.}
  \item{lag}{a scalar lag parameter.}
  \item{differences}{an integer representing the order of the
    difference.}
  \item{xi}{a numeric vector, matrix, or time series containing the
    initial values for the integrals.}
  \item{\dots}{arguments passed to or from other methods.}
}
\details{
  \code{diffinv} is a generic function with methods for class \code{"ts"}
  and \code{default} for vectors and matrices.

  Missing values are not handled.
}
\value{
  A numeric vector, matrix, or time series representing the discrete
  integral of \code{x}. 
}
\author{A. Trapletti}
\seealso{
  \code{\link{diff}}
}
\examples{
s <- 1:10
d <- diff(s)
diffinv(d, xi = 1)
}
\keyword{ts}
\name{embed}
\title{Embedding a Time Series}
\usage{
embed (x, dimension = 1) 
}
\alias{embed}
\arguments{
  \item{x}{a numeric vector, matrix, or time series.}
  \item{dimension}{a scalar representing the embedding dimension.}
}
\description{
  Embeds the time series \code{x} into a low-dimensional
  Euclidean space.
}
\details{
  Each row of the resulting matrix consists of sequences
  \code{x[t]}, \code{x[t-1]}, \dots, \code{x[t-dimension+1]}, where
  \code{t} is the original index of \code{x}. If \code{x} is a matrix,
  i.e., \code{x} contains more than one variable, then \code{x[t]}
  consists of the \code{t}th observation on each variable.
}
\value{
  A matrix containing the embedded time series \code{x}.
}
\author{A. Trapletti, B.D. Ripley}
\examples{
x <- 1:10
embed (x, 3)
}
\keyword{ts}

\name{filter}
\alias{filter}
\title{Linear Filtering on a Time Series}
\usage{
filter(x, filter, method = c("convolution", "recursive"),
       sides = 2, circular = FALSE, init)
}
\arguments{
  \item{x}{a univariate or multivariate time series.}

  \item{filter}{a vector of filter coefficients in reverse time order
    (as for AR or MA coefficients).}

  \item{method}{Either \code{"convolution"} or \code{"recursive"} (and
    can be abbreviated). If \code{"convolution"} a moving average is
    used: if \code{"recursive"} an autoregression is used.}

  \item{sides}{for convolution filters only. If \code{sides=1} the
    filter coefficients are for past values only; if \code{sides=2}
    they are centred around lag 0. In this case the length of the
    filter should be odd, but if it is even, more of the filter
    is forward in time than backward.}

  \item{circular}{for convolution filters only.  If \code{TRUE}, wrap
    the filter around the ends of the series, otherwise assume
    external values are missing (\code{NA}).}

  \item{init}{for recursive filters only. Specifies the initial values
    of the time series just prior to the start value, in reverse
    time order. The default is a set of zeros.}
}
\description{
  Applies linear filtering to a univariate time series or to each series
  separately of a multivariate time series.
}
\value{
  A time series object.
}
\details{
  Missing values are allowed in \code{x} but not in \code{filter}
  (where they would lead to missing values everywhere in the output).

  Note that there is an implied coefficient 1 at lag 0 in the
  recursive filter, which gives
  \deqn{y_i = x_i + f_1y_{i-1} + \cdots + f_py_{i-p}}{\code{y[i] =
      x[i] + f[1]*y[i-1] + \dots + f[p]*y[i-p]}}
  No check is made to see if recursive filter is invertible:
  the output may diverge if it is not.

  The convolution filter is
  \deqn{y_i = f_1x_{i+o} + \cdots + f_px_{i+o-p-1}}{\code{y[i] = f[1]*x[i+o] + \dots + f[p]*x[i+o-p-1]}}

  where \code{o} is the offset: see \code{sides} for how it is determined.
}
\note{
  \code{\link{convolve}(, type="filter")} uses the FFT for computations
  and so \emph{may} be faster for long filters on univariate series,
  but it does not return a time series (and so the  time alignment is
  unclear), nor does it handle missing values.  \code{filter} is
  faster for a filter of length 100 on a series of length 1000,
  for example.
}
\author{B.D. Ripley}

\seealso{
  \code{\link{convolve}}, \code{\link{arima.sim}}
}

\examples{
x <- 1:100
filter(x, rep(1, 3))
filter(x, rep(1, 3), sides = 1)
filter(x, rep(1, 3), sides = 1, circular = TRUE)
data(presidents)
filter(presidents, rep(1,3))
}
\keyword{ts}
\name{kernapply}
\title{Apply Smoothing Kernel}
\alias{kernapply}
\alias{kernapply.default}
\alias{kernapply.ts}
\alias{kernapply.tskernel}
\alias{kernapply.vector}
\synopsis{
kernapply(x, ...)
kernapply.default(x, k, circular = FALSE, ...)
kernapply.ts(x, k, circular = FALSE, ...)
kernapply.vector(x, k, circular = FALSE, ...)
kernapply.tskernel(k1, k2)
}
\usage{
kernapply(x, k, circular = FALSE, ...) 
kernapply(k1, k2)
}
\arguments{
  \item{k, k1, k2}{smoothing \code{"tskernel"} objects.}
  \item{x}{an input vector, matrix, or time series to be smoothed.}
  \item{circular}{a logical indicating whether the input sequence to be
    smoothed is treated as circular, i.e., periodic.}
  \item{\dots}{arguments passed to or from other methods.}
}
\description{
  \code{kernapply} computes the convolution between an input sequence 
  and a specific kernel.
}
\value{
  A smoothed version of the input sequence.
}
\author{A. Trapletti}
\seealso{
  \code{\link{kernel}}, \code{\link{convolve}}, \code{\link{filter}},
  \code{\link{spectrum}}
}
\examples{
## see `kernel' for examples
}
\keyword{ts}
\name{kernel}
\alias{kernel}
\alias{bandwidth.kernel}
\alias{df.kernel}
\alias{is.tskernel}
\alias{print.tskernel}
\alias{plot.tskernel}
\alias{[.tskernel}
\title{Smoothing Kernel Objects}
\description{
  The \code{"tskernel"} class is designed to represent discrete
  symmetric normalized smoothing kernels.  These kernels can be used to
  smooth vectors, matrices, or time series objects.
}
\usage{
kernel(coef, m, r, name)

df.kernel(k)
bandwidth.kernel(k)
is.tskernel(k)

\method{print}{tskernel}(x, digits = max(3,getOption("digits")-3), ...)
\method{plot}{tskernel}(x, ...)
}
\arguments{
  \item{coef}{the upper half of the smoothing kernel coefficients
    (inclusive of coefficient zero) \emph{or} the name of a kernel
    (currently \code{"daniell"}, \code{"dirichlet"}, \code{"fejer"} or
    \code{"modified.daniell"}.}
  \item{m}{the kernel dimension. The number of kernel coefficients is
    \code{2*m+1}.}
  \item{name}{the name of the kernel.}
  \item{r}{the kernel order for a Fejer kernel.}
  \item{digits}{the number of digits to format real numbers.}
  \item{k, x}{a \code{"tskernel"} object.}
  \item{\dots}{arguments passed to or from other methods.}
}
\details{
  \code{kernel} is used to construct a general kernel or
  named specific kernels. The modified Daniell kernel
  halves the end coefficients (as used by S-PLUS).
  
  \code{df.kernel} returns the ``equivalent degrees of freedom'' of a
  smoothing kernel as defined in Brockwell and Davies (1991), page 362,
  and \code{bandwidth.kernel} returns the equivalent bandwidth as
  defined in Bloomfield (1991), p. 201, with a continuity correction.
}
\value{
  \code{kernel} returns a list with class \code{"tskernel"}, and
  components the coefficients \code{coef} and the kernel dimension
  \code{m}.  An additional attribute is \code{"name"}.
}
\author{A. Trapletti; modifications by B.D. Ripley}
\seealso{
    \code{\link{kernapply}}
}
\references{
  Bloomfield, P. (1976) \emph{Fourier Analysis of Time Series: An
    Introduction.} Wiley.

  Brockwell, P.J. and Davis, R.A. (1991) \emph{Time Series: Theory and
    Methods.} Second edition. Springer, pp. 350--365.
}
\examples{
data(EuStockMarkets)    # Demonstrate a simple trading strategy for the 
x <- EuStockMarkets[,1]  # financial time series German stock index DAX.
k1 <- kernel("daniell", 50)  # a long moving average
k2 <- kernel("daniell", 10)  # and a short one
plot(k1) 
plot(k2)
x1 <- kernapply(x, k1)
x2 <- kernapply(x, k2)
plot(x)
lines(x1, col = "red")    # go long if the short crosses the long upwards
lines(x2, col = "green")  # and go short otherwise

data(sunspot)     # Reproduce example 10.4.3 from Brockwell and Davies (1991)
spectrum(sunspot.year, kernel=kernel("daniell", c(11,7,3)), log="no")
}
\keyword{ts}

\name{lag}
\alias{lag}
\alias{lag.default}
\title{Lag a Time Series}
\description{
  Computed a lagged version of a time series, shifting the time base
  back by a given number of observations.
}
\usage{
\method{lag}{default}(x, k = 1, \dots)
}
\arguments{
  \item{x}{A vector or matrix or univariate or multivariate time series}
  \item{k}{The number of lags (in units of observations).}
  \item{\dots}{further arguments to be passed to or from methods.}
}
\details{
  Vector or matrix arguments \code{x} are coerced to time series.

  \code{lag} is a generic function; this page documents its default
  method.
}
\value{
  A time series object.
}
\author{B.D. Ripley}

\note{
  Note the sign of \code{k}: a series lagged by a positive \code{k}
  starts \emph{earlier}.
}

\seealso{\code{\link{diff}}, \code{\link{deltat}} }

\examples{
data(UKLungDeaths)
lag(ldeaths, 12) # starts one year earlier
}
\keyword{ts}
\name{lag.plot}
\alias{lag.plot}
\title{Time Series Lag Plots}
\description{
  Plot time series against lagged versions of themselves.
  Helps visualizing ``auto-dependence'' even when auto-correlations vanish.
}
\usage{
lag.plot(x, lags = 1, layout = NULL, set.lags = 1:lags,
         main = NULL, asp = 1,
         font.main=par("font.main"), cex.main=par("cex.main"),
         diag = TRUE, diag.col="gray", type="p", oma =NULL, ask =NULL,
         do.lines = n <= 150, labels = do.lines, \dots)
}
\arguments{
  \item{x}{time-series (univariate or multivariate)}
  \item{lags}{number of lag plots desired, see arg \code{set.lags}.}
  \item{layout}{the layout of multiple plots, basically the \code{mfrow}
    \code{\link{par}()} argument.  The default uses about a square
    layout (see \code{\link{n2mfrow}} such that all plots are on one page.}
  \item{set.lags}{positive integer vector allowing to specify the set of
  lags used; defaults to \code{1:lags}.}
  \item{main}{character with a main header title to be done on the top
    of each page.}
  \item{asp}{Aspect ratio to be fixed, see \code{\link{plot.default}}.}
  \item{font.main, cex.main}{attributes for the title, see \code{par()}.}
  \item{diag}{logical indicating if the x=y diagonal should be drawn.}
  \item{diag.col}{color to be used for the diagonal \code{if(diag)}.}
  \item{type}{plot type to be used, but see \code{\link{plot.ts}} about
    its restricted meaning.}
  \item{oma}{outer margins, see \code{\link{par}}.}
  \item{ask}{logical; if true, the user is asked before a new page is started.}
  \item{do.lines}{logical indicating if lines should be drawn.}
  \item{labels}{logical indicating if labels should be used.}
  \item{\dots}{Further arguments to \code{\link{plot.ts}}.}
}
\note{
  It is more flexible and has different default behaviour than
  the S version.  We use \code{main =} instead of \code{head = } for
  internal consistency.
}
\author{Martin Maechler}
\seealso{\code{\link{plot.ts}} which is the basic work horse.}
}
\examples{
data(nhtemp)
lag.plot(nhtemp, 8, diag.col = "forest green")
lag.plot(nhtemp, 5, main="Average Temperatures in New Haven")
## ask defaults to TRUE when we have more than one page:
lag.plot(nhtemp, 6, layout = c(2,1), asp = NA,
         main = "New Haven Temperatures", col.main = "blue")

## Multivariate (but non-stationary! ...)
data(freeny)
lag.plot(freeny.x, lag = 3)
\dontrun{
data(sunspots) # no lines for long series :
lag.plot(sqrt(sunspots), set = c(1:4, 9:12), pch = ".", col = "gold")
}
}
\keyword{hplot}
\keyword{ts}
% file lh.Rd
% copyright (C) 1994-9 W. N. Venables and B. D. Ripley
%
\name{lh}
\alias{lh}
\title{
  Luteinizing Hormone in Blood Samples
}
\description{
  A regular time series giving the luteinizing hormone in blood
  samples at 10 mins intervals from a human female, 48 samples.
}
\usage{data(lh)}
\source{
  P.J. Diggle (1990)
  \emph{Time Series: A Biostatistical Introduction.}
  Oxford, table A.1, series 3
}
\keyword{datasets}
\name{lynx}
\alias{lynx}
\title{Annual Canadian Lynx trappings 1821--1934}
\description{
  Annual numbers of lynx trappings for 1821--1934 in Canada. Taken from
  Brockwell & Davis (1991), this appears to be the series considered
  by Campbell & Walker (1977).
}
\usage{data(lynx)}
\source{
  Brockwell, P. J. and Davis, R. A. (1991) \emph{Time
    Series and Forecasting Methods.}  Second edition.
  Springer. Series G (page 557).
}
\references{
  Campbell, M. J.and A. M.  Walker (1977).  A Survey of
  statistical work on the Mackenzie River series of annual
  Canadian lynx trappings for the years  1821--1934 and
  a new analysis.
  \emph{Journal of the Royal Statistical Society series A},
  \bold{140}, 411--431.
}
\keyword{datasets}
\name{monthplot}
\alias{monthplot}
\alias{monthplot.default}
\alias{monthplot.ts}
\alias{monthplot.stl}
\alias{monthplot.StructTS}

\title{
  Plot a Seasonal or other Subseries
}
\description{
  These functions plot seasonal (or other) subseries of a time series.
  For each season (or other category), a time series is plotted.
}
\synopsis{
monthplot(x, ...)
monthplot.StructTS(x, labels = NULL, ylab = choice, choice = "sea", ...)
monthplot.stl(x, labels = NULL, ylab = choice, choice = "seasonal", ...)
monthplot.ts(x, labels = NULL, times = time(x), phase = cycle(x),
             ylab = deparse(substitute(x)), ...)
monthplot.default(x, labels = 1:12,
              times = 1:length(x),
              phase = (times - 1)\%\%length(labels) + 1,
              base = mean,
              xlim = c(0.55, f + 0.45), ylim = range(x, na.rm = TRUE),
              axes = TRUE, xlab = "", ylab = deparse(substitute(x)),
              type = "l", box = TRUE, add = FALSE, ...)
}
\usage{
monthplot(x, labels = NULL, times, phase, base, choice, \ldots)
}
\arguments{
  \item{x}{Time series or related object.}
  \item{labels}{Labels to use for each ``season''.}
  \item{times}{Time of each observation.}
  \item{phase}{Indicator for each ``season''.}
  \item{base}{Function to use for reference line for subseries.}
  \item{choice}{Which series of an \code{stl} or \code{StructTS} object?}
  \item{\dots}{Graphical parameters.}
}
\details{
  These functions extract subseries from a time series and plot them
  all in one frame.  The \code{\link{ts}}, \code{\link{stl}}, and
  \code{\link{StructTS}} methods use the internally recorded frequency and
  start and finish times to set the scale and the seasons.  The default
  method assumes observations come in groups of 12 (though this can be
  changed).

  If the \code{labels} are not given but the \code{phase} is given, then
  the \code{labels} default to the unique values of the \code{phase}.  If
  both are given, then the \code{phase} values are assumed to be indices
  into the \code{labels} array, i.e. they should be in the range
  from 1 to \code{length(labels)}.
}
\value{
  These functions are executed for their side effect of
  drawing a seasonal subseries plot on the current graphical
  window.
}
\author{Duncan Murdoch}
\seealso{
  \code{\link{ts}}, \code{\link{stl}}, \code{\link{StructTS}}
}

\examples{
## The CO2 data
data(co2)
fit <- stl(log(co2), s.window = 20, t.window = 20)
plot(fit)
op <- par(mfrow = c(2,2))
monthplot(co2, ylab = "data", cex.axis = 0.8)
monthplot(fit, choice = "seasonal", cex.axis = 0.8)
monthplot(fit, choice = "trend", cex.axis = 0.8)
monthplot(fit, choice = "remainder", type = "h", cex.axis = 0.8)
par(op)

## The CO2 data, grouped quarterly
quarter <- (cycle(co2) - 1) \%/\% 3
monthplot(co2, phase = quarter)

## see also JohnsonJohnson
}
\keyword{ hplot }
\keyword{ ts }
\name{na.contiguous}
\alias{na.contiguous}
\title{NA Handling Routines for Time Series}
\description{
  Find the longest consecutive stretch of non-missing values in a time
  series object.  (In the event of a tie, the first such stretch.)
}
\usage{
na.contiguous(frame)
}
\arguments{
  \item{frame}{a univariate or multivariate time series.}
}
\value{
  A time series without missing values.  The class of \code{frame} will
  be preserved.
}
\author{B. D. Ripley}
\seealso{
  \code{\link{na.omit}} and \code{\link{na.omit.ts}};
  \code{\link{na.fail}}
}
\examples{
data(presidents)
na.contiguous(presidents)
}
\keyword{ts}
\name{nottem}
\alias{nottem}
\title{
  Average Monthly Temperatures at Nottingham, 1920--1939
}
\description{
  A time series object containing average air temperatures at
  Nottingham Castle in degrees Fahrenheit for 20 years.
}
\usage{data(nottem)}
\source{
  Anderson, O. D. (1976)
  \emph{Time Series Analysis and Forecasting: The Box-Jenkins approach.}
  Butterworths. Series R.
}
\examples{
\dontrun{data(nottem)
nott <- window(nottem, end=c(1936,12))
fit <- arima(nott,order=c(1,0,0), list(order=c(2,1,0), period=12))
nott.fore <- predict(fit, n.ahead=36)
ts.plot(nott, nott.fore$pred, nott.fore$pred+2*nott.fore$se,
        nott.fore$pred-2*nott.fore$se, gpars=list(col=c(1,1,4,4)))
}}
\keyword{datasets}
\name{plot.HoltWinters}
\alias{plot.HoltWinters}
\title{Plot function for HoltWinters objects}
\description{
  Produces a chart of the original time series along with the fitted
  values. Optionally, predicted values (and their confidence bounds) can
  also be plotted.
}
\usage{
\method{plot}{HoltWinters}(x, predicted.values = NA, intervals = TRUE,
        separator = TRUE, col = 1, col.predicted = 2,
        col.intervals = 4, col.separator = 1, lty = 1,
        lty.predicted = 1, lty.intervals = 1, lty.separator = 3,
        ylab = "Observed / Fitted",
        main = "Holt-Winters filtering", ...)
}
\arguments{
  \item{x}{Object of class \code{"HoltWinters"}}
  \item{predicted.values}{Predicted values as returned by \code{predict.HoltWinters}}
  \item{intervals}{If \code{TRUE}, the prediction intervals are plotted (default).}
  \item{separator}{If \code{TRUE}, a separating line between fitted and predicted values is plotted (default).}
  \item{col, lty}{Color/line type of original data (default: black solid).}
  \item{col.predicted, lty.predicted}{Color/line type of
    fitted and predicted values (default: red solid).}
  \item{col.intervals, lty.intervals}{Color/line type of prediction
    intervals (default: blue solid).}
  \item{col.separator, lty.separator}{Color/line type of
    observed/predicted values separator (default: black dashed).}
  \item{ylab}{Label of the y-axis.}
  \item{main}{Main title.}
  \item{\dots}{Other graphics parametes.}
}
\references{
  C.C Holt (1957)
  Forecasting seasonals and trends by exponentially weighted
  moving averages,
  ONR Research Memorandum, Carnigie Institute 52.
  
  P.R Winters (1960)
  Forecasting sales by exponentially weighted moving averages,
  \emph{Management Science} \bold{6}, 324--342.
}
\author{
  David Meyer \email{david.meyer@ci.tuwien.ac.at}
}
\seealso{
  \code{\link{HoltWinters}}, \code{\link{predict.HoltWinters}}
}

\keyword{ts}
\name{plot.acf}
\alias{plot.acf}
\title{Plotting Autocovariance and Autocorrelation Functions}
\description{
  Plotting method for objects of class \code{"acf"}.
}
\usage{
\method{plot}{acf}(x, ci = 0.95, type = "h", xlab = "Lag", ylab = NULL,
              ylim = NULL, main = NULL, ci.col="blue",
              ci.type = c("white", "ma"),
              max.mfrow = 6,
              ask = Npgs > 1 && dev.interactive(),
              mar = if(nser > 2) c(3,2,2,0.8) else par("mar"),
              oma = if(nser > 2) c(1,1.2,1,1) else par("oma"),
              mgp = if(nser > 2) c(1.5,0.6,0) else par("mgp"),
              xpd = par("xpd"),
              cex.main = if(nser > 2) 1 else par("cex.main"),
              verbose = getOption("verbose"),
              \dots)
}
\arguments{
  \item{x}{an object of class \code{"acf"}.}
  \item{ci}{coverage probability for confidence interval.  Plotting of
    the confidence interval is suppressed if \code{ci} is zero or
    negative.}
  \item{type}{the type of plot to be drawn, default to histogram like
    vertical lines.}
  \item{xlab}{the x label of the plot.}
  \item{ylab}{the y label of the plot.}
  \item{ylim}{numeric of length 2 giving the y limits for the plot.}
  \item{main}{overall title for the plot.}
  \item{ci.col}{colour to plot the confidence interval lines.}
  \item{ci.type}{should the confidence limits assume a white noise
    input or for lag \eqn{k} an MA(\eqn{k-1}) input?}
  \item{max.mfrow}{positive integer; for multivariate \code{x}
    indicating how many rows and columns of plots should be put on one
    page, using \code{\link{par}(mfrow = c(m,m))}.}
  \item{ask}{logical; if \code{TRUE}, the user is asked before a new
    page is started.}
  \item{mar, oma, mgp, xpd, cex.main}{graphics parameters as in
    \code{\link{par}(*)}, by default adjusted to use smaller than
    default margins for multivariate \code{x} only.
    % drop the following line after year 2002
    \code{xpd = NA} used to be the default for R version <= 1.4.0.
  }
  \item{verbose}{logical.  Should \R report extra information on
    progress?}
  \item{\dots}{graphics parameters to be passed to the plotting
    routines.}
}
\note{
  The confidence interval plotted in \code{plot.acf} is based on an
  \emph{uncorrelated} series and should be treated with appropriate
  caution.  Using \code{ci.type = "ma"} may be less potentially
  misleading.
}
\seealso{\code{\link{acf}} which calls \code{plot.acf} by default.
}
\examples{
%%-- FIXME: use less trivial data :
z4  <- ts(matrix(rnorm(400), 100, 4), start=c(1961, 1), frequency=12)
z7  <- ts(matrix(rnorm(700), 100, 7), start=c(1961, 1), frequency=12)
acf(z4)
acf(z7, max.mfrow = 7)# squeeze on 1 page
acf(z7) # multi-page
}
\keyword{hplot}
\keyword{ts}
\name{plot.spec}
\alias{plot.spec}
\alias{plot.spec.coherency}
\alias{plot.spec.phase}
\title{Plotting Spectral Densities}
\description{
  Plotting method for objects of class \code{"spec"}.  For multivariate
  time series it plots the marginal spectra of the series or pairs plots
  of the coherency and phase of the cross-spectra.
}
\synopsis{
plot.spec(x, add = FALSE, ci = 0.95, log = c("yes", "dB", "no"), 
    xlab = "frequency", ylab = NULL, type = "l",
    ci.col = "blue", main = NULL, sub = NULL,
    plot.type = c("marginal", "coherency", "phase"), \dots) 
plot.spec.phase(x, ci = 0.95, xlab = "frequency",
    ylab = "phase", ylim = c(-pi, pi), type = "l",
    main = NULL, ci.lty = 3, ci.col = "blue", \dots) 
plot.spec.coherency(x, ci = 0.95, xlab = "frequency",
    ylab = "squared coherency", ylim = c(0, 1), type = "l",
    main = NULL, ci.lty = 3, ci.col = "blue", \dots)
}
\usage{
plot(x, add = FALSE, ci = 0.95, log = c("yes", "dB", "no"),
     xlab = "frequency", ylab = NULL, type = "l", ci.col = "blue",
     main = NULL, sub = NULL,
     plot.type = c("marginal", "coherency", "phase"),
     ci.lty = 3, \dots)
}
\arguments{
  \item{x}{an object of class \code{"spec"}.}
  \item{add}{logical.  If \code{TRUE}, add to already existing plot.}
  \item{ci}{Coverage probability for confidence interval.  Plotting of
    the confidence bar is omitted unless \code{ci} is strictly
    positive.}
  \item{log}{If \code{"dB"}, plot on log10 (decibel) scale (as S-PLUS),
    otherwise use conventional log scale or linear scale.  Logical
    values are also accepted.  The default is \code{"yes"} unless
    \code{options(ts.S.compat = TRUE)} has been set, when it is
    \code{"dB"}.}
  \item{xlab}{the x label of the plot.}  
  \item{ylab}{the y label of the plot.}
  \item{type}{the type of plot to be drawn, defaults to lines.}
  \item{ci.col}{Colour for plotting confidence bar or confidence
    intervals for coherency and phase.}
  \item{main}{overall title for the plot.}
  \item{sub}{a sub title for the plot.}
  \item{plot.type}{For multivariate time series, the type of plot
    required.  Only the first character is needed.}
  \item{ci.lty}{line type for confidence intervals for coherency and
    phase.}
  \item{\dots}{Further graphical parameters.}
}
\seealso{
  \code{\link{spectrum}}
}
\keyword{hplot}
\keyword{ts}
\name{PP.test}
\alias{PP.test}
\title{Phillips-Perron Unit Root Test}
\usage{
PP.test(x, lshort = TRUE)
}
\arguments{
  \item{x}{a numeric vector or univariate time series.}
  \item{lshort}{a logical indicating whether the short or long version
    of the truncation lag parameter is used.}
}
\description{
  Computes the Phillips-Perron test for the null hypothesis that
  \code{x} has a unit root against a stationary alternative.
}
\details{
  The general regression equation which incorporates a constant and a
  linear trend is used and the corrected t-statistic for a first order
  autoregressive coefficient equals one is computed.  To estimate
  \code{sigma^2} the Newey-West estimator is used.  If \code{lshort}
  is \code{TRUE}, then the truncation lag parameter is set to
  \code{trunc(4*(n/100)^0.25)}, otherwise
  \code{trunc(12*(n/100)^0.25)} is used.  The \eqn{p}-values are
  interpolated from Table 4.2, page 103 of Banerjee \emph{et al.}
  (1993).
  
  Missing values are not handled.
}
\value{
  A list with class \code{"htest"} containing the following components:
  \item{statistic}{the value of the test statistic.}
  \item{parameter}{the truncation lag parameter.}
  \item{p.value}{the \eqn{p}-value of the test.}
  \item{method}{a character string indicating what type of test was
    performed.} 
  \item{data.name}{a character string giving the name of the data.}
}
\references{
  A. Banerjee, J. J. Dolado, J. W. Galbraith, and D. F. Hendry (1993)
  \emph{Cointegration, Error Correction, and the Econometric Analysis
    of Non-Stationary Data}, Oxford University Press, Oxford.
  
  P. Perron (1988) Trends and random walks in macroeconomic time
  series. \emph{Journal of Economic Dynamics and Control} \bold{12},
  297--332.
}
\author{A. Trapletti}
\examples{
x <- rnorm(1000)
PP.test(x)
y <- cumsum(x) # has unit root
PP.test(y)
}
\keyword{ts}
\name{predict.HoltWinters}
\alias{predict.HoltWinters}
\title{prediction function for fitted Holt-Winters models}
\description{
  Computes predictions and prediction intervals for models fitted by
  the Holt-Winters method.
}
\usage{
\method{predict}{HoltWinters}(object, n.ahead=1, prediction.interval = FALSE,
                    quantile = qnorm(0.975), ...)
}
\arguments{
  \item{object}{An object of class \code{HoltWinters}}
  \item{n.ahead}{Number of future periods to predict}
  \item{prediction.interval}{logical. If \code{TRUE}, the lower and
    upper bounds of the corresponding prediction intervals are computed}
  \item{quantile}{Quantile used for each one-sided prediction interval
    (default: the 0.975 quantile to give a two-sided 0.95 interval)}
  \item{\dots}{arguments passed to or from other methods.}
}
\value{
  A time series of the predicted values. If prediction intervals are
  requested, a multiple time series is returned with columns \code{fit},
  \code{lwr} and \code{upr} for the predicted values and the lower and
  upper bounds respectively.
}
\references{
  C.C Holt (1957)
  Forecasting seasonals and trends by exponentially weighted
  moving averages,
  ONR Research Memorandum, Carnigie Institute 52.
  
  P.R Winters (1960)
  Forecasting sales by exponentially weighted moving averages,
  \emph{Management Science} \bold{6}, 324--342.
}
\author{
  David Meyer \email{david.meyer@ci.tuwien.ac.at}
}
\seealso{\code{\link{HoltWinters}}}

\examples{
data(co2)
m <- HoltWinters(co2)
p <- predict(m, 50, prediction.interval = TRUE)
plot(m, p)
}
\keyword{ts}


\name{predict.Arima}
\alias{predict.Arima}
\title{Forecast from ARIMA fits}
\description{
  Forecast from models fitted by \code{\link{arima}}.
}
\usage{
\method{predict}{Arima}(object, n.ahead = 1, newxreg = NULL,
     se.fit = TRUE, \dots)
}
\arguments{
  \item{object}{The result of an \code{arima} fit.}
  \item{n.ahead}{The number of steps ahead for which prediction is required.}
  \item{newxreg}{New values of \code{xreg} to be used for
    prediction. Must have at least \code{n.ahead} rows.}
  \item{se.fit}{Logical: should standard errors of prediction be returned?}
  \item{\dots}{arguments passed to or from other methods.}
}
\details{
  Finite-history prediction is used, via \code{\link{KalmanForecast}}.
  This is only statistically efficient if the MA part of the fit is
  invertible, so \code{predict.Arima} will give a warning for
  non-invertible MA models.

  The standard errors of prediction exclude the uncertainty in the
  estimation of the ARMA model and the regression coefficients.
  According to Harvey (1993, pp. 58--9) the effect is small.
}
\value{
  A time series of predictions, or if \code{se.fit = TRUE}, a list
  with components \code{pred}, the predictions, and \code{se},
  the estimated standard errors.  Both components are time series.
}
\references{
  Durbin, J. and Koopman, S. J. (2001) \emph{Time Series Analysis by
    State Space Methods.}  Oxford University Press.
  
  Harvey, A. C. and McKenzie, C. R. (1982) Algorithm AS182.
  An algorithm for finite sample prediction from ARIMA processes.
  \emph{Applied Statistics} \bold{31}, 180--187.

  Harvey, A. C. (1993) \emph{Time Series Models},
  2nd Edition, Harvester Wheatsheaf, sections 3.3 and 4.4.
}
\author{B. D. Ripley}

\seealso{
  \code{\link{arima}}
}

\examples{
data(lh, package="ts")
predict(arima(lh, order = c(3,0,0)), n.ahead = 12)

data(USAccDeaths, package="ts")
(fit <- arima(USAccDeaths, order = c(0,1,1),
              seasonal = list(order=c(0,1,1))))
predict(fit, n.ahead = 6)
\testonly{

## tests of prediction
predict(arima(lh, order=c(1,0,1)), n.ahead=5)
predict(arima(lh, order=c(1,1,0)), n.ahead=5)
predict(arima(lh, order=c(0,2,1)), n.ahead=5)
}}
\keyword{ts}
\name{spec.ar}
\alias{spec.ar}
\title{Estimate Spectral Density of a Time Series from AR Fit}
\usage{
spec.ar(x, n.freq, order = NULL, plot = TRUE, na.action = na.fail,
        method = "yule-walker", ...)
}
\arguments{
  \item{x}{A univariate (not yet:or multivariate) time series or the
    result of a fit by \code{\link{ar}}.}
  \item{n.freq}{The number of points at which to plot.}
  \item{order}{The order of the AR model to be fitted.  If omitted,
    the order is chosen by AIC.}
  \item{plot}{Plot the periodogram?}
  \item{na.action}{\code{NA} action function.}
  \item{method}{\code{method} for \code{ar} fit.}
  \item{\dots}{Graphical arguments passed to \code{\link{plot.spec}}.}
}
\description{
  Fits an AR model to \code{x} (or uses the existing fit) and computes
  (and by default plots) the spectral density of the fitted model.
}
\value{
  An object of class \code{"spec"}.
  The result is returned invisibly if \code{plot} is true.
}
\references{
  Thompson, D.J. (1990) Time series analysis of Holocene climate data.
  \emph{Phil. Trans. Roy. Soc. A} \bold{330}, 601--616.

  Venables, W.N. and Ripley, B.D. (1997) \emph{Modern Applied
    Statistics with S-PLUS.} Second edition. Springer. (Especially
  page 448.)
}
\section{Warning}{
  Some authors, for example Thomson (1990), warn strongly
  that AR spectra can be misleading.
}

\author{B.D. Ripley}

\seealso{\code{\link{ar}}, \code{\link{spectrum}}.}

\note{The multivariate case is not yet implemented.}

\examples{
data(lh)
spec.ar(lh)

data(UKLungDeaths)
spec.ar(ldeaths)
spec.ar(ldeaths, method="burg")
}
\keyword{ts}
\name{spec.pgram}
\alias{spec.pgram}
\title{Estimate Spectral Density of a Time Series from Smoothed
    Periodogram}
\usage{
spec.pgram(x, spans = NULL, kernel, taper = 0.1,
           pad = 0, fast = TRUE, demean = FALSE, detrend =TRUE,
           plot = FALSE, na.action = na.fail, \dots)
}
\arguments{
  \item{x}{univariate or multivariate time series.}
  \item{spans}{vector of odd integers giving the widths of modified
    Daniell smoothers to be used to smooth the periodogram.}
  \item{kernel}{alternatively, a kernel smoother of class
    \code{"tskernel"}.}
  \item{taper}{proportion of data to taper.  A split cosine bell taper
    is applied to this proportion of the data at the beginning and
    end of the series.}
  \item{pad}{proportion of data to pad. Zeros are added to the end of
    the series to increase its length by the proportion \code{pad}.}
  \item{fast}{logical; if \code{TRUE}, pad the series to a highly composite
    length.}
  \item{demean}{logical. If \code{TRUE}, subtract the mean of the
    series.}
  \item{detrend}{logical. If \code{TRUE}, remove a linear trend from
    the series. This will also remove the mean.}
  \item{plot}{plot the periodogram?}
  \item{na.action}{\code{NA} action function.}
  \item{\dots}{graphical arguments passed to \code{plot.spec}.}
}
\description{
  \code{spec.pgram} calculates the periodogram using a fast Fourier
  transform, and optionally smooths the result with a series of
  modified Daniell smoothers (moving averages giving half weight to
  the end values).
}
\details{
  The raw periodogram is not a consistent estimator of the spectral density,
  but adjacent values are asymptotically independent. Hence a consistent
  estimator can be derived by smoothing the raw periodogram, assuming that
  the spectral density is smooth.

  The series will be automatically padded with zeros until the series
  length is a highly composite number in order to help the Fast Fourier
  Transform. This is controlled by the \code{fast} and not the \code{pad}
  argument.

  The periodogram at zero is in theory zero as the mean of the series
  is removed (but this may be affected by tapering): it is replaced by
  an interpolation of adjacent values during smoothing, and no value
  is returned for that frequency.
}
\value{
  A list object of class \code{"spec"} (see \code{\link{spectrum}})
  with the following additional components:
  \item{kernel}{The \code{kernel} argument, or the kernel constructed
    from \code{spans}.}
  \item{df}{The distribution of the spectral density estimate can be
    approximated by a chi square distribution with \code{df} degrees
    of freedom.}
  \item{bandwidth}{The equivalent bandwidth of the kernel smoother as
    defined by Bloomfield (1976, page 201).}
  \item{taper}{The value of the \code{taper} argument.}
  \item{pad}{The value of the \code{pad} argument.}
  \item{detrend}{The value of the \code{detrend} argument.}
  \item{demean}{The value of the \code{demean} argument.}

  The result is returned invisibly if \code{plot} is true.
}

\references{
  Bloomfield, P. (1976) \emph{Fourier Analysis of Time Series: An
    Introduction.} Wiley.

  Brockwell, P.J. and Davis, R.A. (1991) \emph{Time Series: Theory and
    Methods.} Second edition. Springer.

  Venables, W.N. and Ripley, B.D. (1997) \emph{Modern Applied
    Statistics with S-PLUS.} Second edition. Springer. (Especially
  pp. 437--442.)
}
\author{
  Originally Martyn Plummer; kernel smoothing by Adrian Trapletti,
  synthesis by B.D. Ripley
}
\seealso{\code{\link{spectrum}}, \code{\link{spec.taper}},
  \code{\link{plot.spec}}, \code{\link{fft}}}

\examples{
## Examples from Venables & Ripley
data(UKLungDeaths)
spectrum(ldeaths)
spectrum(ldeaths, spans = c(3,5))
spectrum(ldeaths, spans = c(5,7))
spectrum(mdeaths, spans = c(3,3))
spectrum(fdeaths, spans = c(3,3))

## bivariate example
mfdeaths.spc <- spec.pgram(ts.union(mdeaths, fdeaths), spans = c(3,3))
# plots marginal spectra: now plot coherency and phase
plot(mfdeaths.spc, plot.type = "coherency")
plot(mfdeaths.spc, plot.type = "phase")

## now impose a lack of alignment
mfdeaths.spc <- spec.pgram(ts.intersect(mdeaths, lag(fdeaths, 4)),
   spans = c(3,3), plot = FALSE)
plot(mfdeaths.spc, plot.type = "coherency")
plot(mfdeaths.spc, plot.type = "phase")

data(EuStockMarkets)
stocks.spc <- spectrum(EuStockMarkets, kernel("daniell", c(30,50)),
                       plot = FALSE)
plot(stocks.spc, plot.type = "marginal") # the default type
plot(stocks.spc, plot.type = "coherency")
plot(stocks.spc, plot.type = "phase")

data(BJsales)
sales.spc <- spectrum(ts.union(BJsales, BJsales.lead),
                      kernel("modified.daniell", c(5,7)))
plot(sales.spc, plot.type = "coherency")
plot(sales.spc, plot.type = "phase")
}
\keyword{ts}
\name{spec.taper}
\alias{spec.taper}
\title{Taper a Time Series}
\usage{
spec.taper(x, p=0.1)
}
\arguments{
 \item{x}{A univariate or multivariate time series}
 \item{p}{The total proportion to be tapered, either a scalar or a
   vector of the length of the number of series.}
}
\description{
  Apply a cosine-bell taper to a time series.
}
\details{
  The cosine-bell taper is applied to the first and last \code{p[i]/2}
  observations of time series \code{x[, i]}.
}
\value{
  A new time series object.
}
\author{Kurt Hornik, B.D. Ripley}
\note{From package \file{MASS}.}

\seealso{\code{\link{spec.pgram}}, \code{\link{cpgram}}}

\keyword{ts}
\name{spectrum}
\alias{spectrum}
\alias{spec}
\title{Spectral Density Estimation}
\description{
  The \code{spectrum} function estimates the spectral density of a
  time series.
}
\usage{
spectrum(x, method = c("pgram", "ar"), plot = TRUE, na.action = na.fail,
         \dots)
}
%% spectrum() dispatches to spec.pgram() or spec.ar() which have quite
%%            different extra arguments
\synopsis{
spectrum(\dots, method = c("pgram", "ar"))
}
\arguments{
  \item{x}{A univariate or multivariate time series.}
  \item{method}{String specifying the method used to estimate the
    spectral density.  Allowed methods are \code{"pgram"} (the default)
    and \code{"ar"}.} 
  \item{plot}{logical. If \code{TRUE} then the spectral density is
    plotted.}
  \item{na.action}{\code{NA} action function.}
  \item{\dots}{Further arguments to specific spec methods or
    \code{plot.spec}.}
}
\value{
  An object of class \code{"spec"}, which is a list containing at
  least the following components:
  \item{freq}{vector of frequencies at which the spectral
    density is estimated. (Possibly approximate Fourier frequencies.)
    The units are the reciprocal of cycles per unit time (and not per
    observation spacing): see Details below.}

  \item{spec}{Vector (for univariate series) or matrix (for multivariate
    series) of estimates of the spectral density at frequencies
    corresponding to \code{freq}.}

  \item{coh}{\code{NULL} for univariate series. For multivariate time
    series, a matrix containing the \emph{squared} coherency
    between different
    series. Column \eqn{ i + (j - 1) * (j - 2)/2} of \code{coh}
    contains the squared coherency between columns \eqn{i} and \eqn{j}
    of \code{x}, where \eqn{i < j}.}

  \item{phase}{\code{NULL} for univariate series. For multivariate
    time series a matrix containing the cross-spectrum phase between
    different series. The format is the same as \code{coh}.}

  \item{series}{The name of the time series.}

  \item{snames}{For multivariate input, the names of the component series.}

  \item{method}{The method used to calculate the spectrum.}

  The result is returned invisibly if \code{plot} is true.
}
\details{
  \code{spectrum} is a wrapper function which calls the methods
  \code{\link{spec.pgram}} and \code{\link{spec.ar}}.
  
  The spectrum here is defined with scaling \code{1/frequency(x)},
  following S-PLUS.  This makes the spectral density a density over the
  range \code{(-frequency(x)/2, +frequency(x)/2]}, whereas a more common
  scaling is \eqn{2\pi} and range \eqn{(-0.5, 0.5]} (e.g., Bloomfield)
  or 1 and range \eqn{(-\pi, \pi]}.
  
  If available, a confidence interval will be plotted by
  \code{plot.spec}: this is asymmetric, and the width of the centre
  mark indicates the equivalent bandwidth.
}
\note{
  The default plot for objects of class \code{"spec"} is quite complex,
  including an error bar and default title, subtitle and axis
  labels.  The defaults can all be overridden by supplying the
  appropriate graphical parameters.
}
\references{
  Bloomfield, P. (1976) \emph{Fourier Analysis of Time Series: An
    Introduction.} Wiley.

  Brockwell, P. J. and Davis, R. A. (1991) \emph{Time Series: Theory and
    Methods.} Second edition. Springer.

  Venables, W. N. and Ripley, B. D. (1997) \emph{Modern Applied
    Statistics with S-PLUS.} Second edition. Springer. (Especially
  pages 437--442.)
}
\author{Martyn Plummer, B.D. Ripley}
\seealso{
  \code{\link{spec.ar}},
  \code{\link{spec.pgram}};
  \code{\link{plot.spec}}.
}
\examples{
## Examples from Venables & Ripley
## spec.pgram
par(mfrow=c(2,2))
data(lh)
spectrum(lh)
spectrum(lh, spans=3)
spectrum(lh, spans=c(3,3))
spectrum(lh, spans=c(3,5))

data(UKLungDeaths)
spectrum(ldeaths)
spectrum(ldeaths, spans=c(3,3))
spectrum(ldeaths, spans=c(3,5))
spectrum(ldeaths, spans=c(5,7))
spectrum(ldeaths, spans=c(5,7), log="dB", ci=0.8)

# for multivariate examples see the help for spec.pgram

## spec.ar
spectrum(lh, method="ar")
spectrum(ldeaths, method="ar")
}
\keyword{ts}
\name{stl}
\alias{stl}
% all methods -> ./stlmethods.Rd
\title{Seasonal Decomposition of Time Series by Loess}
\description{
  Decompose a time series into seasonal, trend and irregular components
  using \code{loess}, acronym STL.
}
\usage{
stl(x, s.window, s.degree = 0,
    t.window = NULL, t.degree = 1,
    l.window = nextodd(period), l.degree = t.degree, 
    s.jump = ceiling(s.window/10),
    t.jump = ceiling(t.window/10),
    l.jump = ceiling(l.window/10),
    robust = FALSE,
    inner = if(robust)  1 else 2,
    outer = if(robust) 15 else 0,
    na.action = na.fail)
}
\arguments{
  \item{x}{univariate time series to be decomposed.
    This should be an object of class \code{"ts"} with a frequency
    greater than one.}
  \item{s.window}{either the character string \code{"periodic"} or the span (in
    lags) of the loess window for seasonal extraction, which should
    be odd.  This has no default.}
  \item{s.degree}{degree of locally-fitted polynomial in seasonal
    extraction.  Should be zero or one.} 
  \item{t.window}{the span (in lags) of the loess window for trend
    extraction, which should be odd.  If \code{NULL}, the default,
    \code{nextodd(ceiling((1.5*period) / (1-(1.5/s.window))))}, is taken.}
  \item{t.degree}{degree of locally-fitted polynomial in trend
    extraction.  Should be zero or one.}
  \item{l.window}{the span (in lags) of the loess window of the low-pass
    filter used for each subseries.  Defaults to the smallest odd
    integer greater than or equal to \code{frequency(x)} which is
    recommended since it prevents competition between the trend and
    seasonal components.  If not an odd integer its given value is
    increased to the next odd one.}
  \item{l.degree}{degree of locally-fitted polynomial for the subseries
    low-pass filter.  Must be 0 or 1.}
  \item{s.jump, t.jump, l.jump}{integers at least one to increase speed of
    the respective smoother.  Linear interpolation happens between every
  \code{*.jump}th value.}
  \item{robust}{logical indicating if robust fitting be used in the \code{loess}
    procedure.}
  \item{inner}{integer; the number of `inner' (backfitting) iterations;
    usually very few (2) iterations suffice.}
  \item{outer}{integer; the number of `outer' robustness iterations.}
  \item{na.action}{action on missing values.}
}
\details{
  The seasonal component is found by \emph{loess} smoothing the
  seasonal sub-series (the series of all January values, \ldots); if
  \code{s.window = "periodic"} smoothing is effectively replaced by
  taking the mean. The seasonal values are removed, and the remainder
  smoothed to find the trend. The overall level is removed from the
  seasonal component and added to the trend component. This process is
  iterated a few times.  The \code{remainder} component is the
  residuals from the seasonal plus trend fit.

  Several methods for the resulting class \code{"stl"} objects, see,
  \code{\link{plot.stl}}.
}
\value{
  \code{stl} returns an object of class \code{"stl"} with components
  \item{time.series}{a multiple time series with columns
    \code{seasonal}, \code{trend} and \code{remainder}.}
  \item{weights}{the final robust weights (all one if fitting is not
    done robustly).}
  \item{call}{the matched call.}
  \item{win}{integer (length 3 vector) with the spans used for the \code{"s"},
    \code{"t"}, and \code{"l"} smoothers.}
  \item{deg}{integer (length 3) vector with the polynomial degrees for
    these smoothers.}
  \item{jump}{integer (length 3) vector with the ``jumps'' (skips) used
    for these smoothers.}
  \item{ni}{number of \bold{i}nner iterations}
  \item{no}{number of \bold{o}uter robustness iterations}
}
\references{
  R. B. Cleveland, W. S. Cleveland, J.E.  McRae, and I. Terpenning (1990)
  STL:  A  Seasonal-Trend  Decomposition  Procedure Based on Loess.
  \emph{Journal of Official Statistics}, \bold{6}, 3--73.
}
\author{B.D. Ripley; Fortran code by Cleveland \emph{et al.} (1990) from
  \file{netlib}.}

\note{This is similar to but not identical to the \code{stl} function in
  S-PLUS. The \code{remainder} component given by S-PLUS is the sum of
  the \code{trend} and \code{remainder} series from this function.}

\seealso{\code{\link{plot.stl}} for \code{stl} methods;
  \code{\link{loess}} in package \file{modreg} (which is not actually
  used in \code{stl}).
} 
\examples{
data(nottem)
plot(stl(nottem, "per"))
plot(stl(nottem, s.win = 4, t.win = 50, t.jump = 1))
    
data(co2)
plot(stllc <- stl(log(co2), s.window=21))
summary(stllc)
## linear trend, strict period.
plot(stl(log(co2), s.window="per", t.window=1000))

## Two STL plotted side by side :    
data(UKLungDeaths)
        stmd <- stl(mdeaths, s.w = "per") # un-robust
summary(stmR <- stl(mdeaths, s.w = "per", robust = TRUE))
op <- par(mar = c(0, 4, 0, 3), oma = c(5, 0, 4, 0), mfcol = c(4, 2))
plot(stmd, set.pars=NULL, labels = NULL,
     main = "stl(mdeaths, s.w = \"per\",  robust = FALSE / TRUE )")
plot(stmR, set.pars=NULL)
# mark the `outliers' :    
(iO <- which(stmR $ weights  < 1e-8)) # 10 were considered outliers
sts <- stmR$time.series
points(time(sts)[iO], .8* sts[,"remainder"][iO], pch = 4, col = "red")
par(op)# reset    
}
\keyword{ts}
\name{stlmethods}
\alias{print.stl}
\alias{summary.stl}
\alias{plot.stl}
\title{Methods for STL Objects}
\description{
  Methods for objects of class \code{stl}, typically the result of
  \code{\link{stl}}.  The \code{plot} method does a multiple figure plot
  with some flexibility.
}
\usage{
\method{plot}{stl}(x, labels = colnames(X),
         set.pars = list(mar = c(0, 6, 0, 6), oma = c(6, 0, 4, 0),
                         tck = -0.01, mfrow = c(nplot, 1)),
         main = NULL, range.bars = TRUE, \dots)
\method{print}{stl}(x, \dots)
\method{summary}{stl}(object, digits = getOption("digits"), \dots)
}
\arguments{
  \item{x, object}{\code{\link{stl}} object.}
  \item{labels}{character of length 4 giving the names of the component
    time-series.}
  \item{set.pars}{settings for \code{\link{par}(.)} when setting up the plot.}
  \item{main}{plot main title.}
  \item{range.bars}{logical indicating if each plot should have a bar at
    its right side which are of equal heights in user coordinates.}
  \item{digits}{significant figures used in printing.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\seealso{\code{\link{plot.ts}} and \code{\link{stl}}, particularly for
  examples.}
\keyword{ts}
\name{sunspot}
\alias{sunspot}
\alias{sunspot.month}
\alias{sunspot.year}
\title{
  Yearly Sunspot Data, 1700--1988.
  Monthly Sunspot Data, 1749--1997.
}
\usage{
data(sunspot)
}
\format{
  The univariate time series \code{sunspot.year} and
  \code{sunspot.month} contain 289 and 2988 observations, respectively.
  The objects are of class \code{"ts"}.
}
\description{
  Monthly and yearly number of sunspots. 
}
\seealso{
  \code{sunspot.month} is a longer version of \code{\link{sunspots}}
  in base \R, that runs until 1988.
}
\source{
  Monthly data: Sunspot Index Data Center,
  World Data Center-C1 For Sunspot Index
  Royal Observatory of Belgium, Av. Circulaire, 3, B-1180 BRUSSELS
  \url{http://www.oma.be/KSB-ORB/SIDC/sidc_txt.html}

  Yearly data: H. Tong (1996)
  \emph{Non-Linear Time Series}. Clarendon Press, Oxford, p. 471. 
}
\examples{
## Compare the monthly series from 'base' and 'ts':
data(sunspots, package = base)
data(sunspot,  package = ts)
plot (sunspot.month, main = "sunspot.month [ts]", col = 2)
lines(sunspots)# ``very barely'' see something

## Now look at the difference :
all(tsp(sunspots)     [c(1,3)] ==
    tsp(sunspot.month)[c(1,3)]) ## Start & Periodicity are the same
n1 <- length(sunspots)
table(eq <- sunspots == sunspot.month[1:n1]) #>  132  are different !
i <- which(!eq) 
rug(time(eq)[i])
s1 <- sunspots[i] ; s2 <- sunspot.month[i]
cbind(i = i, sunspots = s1, ss.month = s2,
      perc.diff = round(100*2*abs(s1-s2)/(s1+s2), 1))
}
\keyword{datasets}


\name{toeplitz}
\title{Form Symmetric Toeplitz Matrix}
\usage{
toeplitz (x)
}
\alias{toeplitz}
\arguments{
  \item{x}{the first row to form the Toeplitz matrix.}
}
\description{
  Forms a symmetric Toeplitz matrix given its first row.
}
\value{
  The Toeplitz matrix.
}
\author{A. Trapletti}
\examples{
x <- 1:5
toeplitz (x)
}
\keyword{ts}

\name{treering}
\alias{treering}
\title{
  Yearly Treering Data, -6000--1979.
}
\usage{
data(treering)
}
\format{
  A univariate time series with 7981 observations. The object is of
  class \code{"ts"}.
}
\description{
  Contains normalized tree-ring widths in dimensionless units.
  Each tree ring corresponds to one year. Tree: Methuselah Walk, Pilo;
  Location: California, Gt Basin B C pine 2805M, 3726-11810; 
  Author: Donald A. Graybill, 1980.  
}
\source{
  Time Series Data Library:
  \url{http://www-personal.buseco.monash.edu.au/~hyndman/TSDL/}
}
\keyword{datasets}
\name{ts.plot}
\alias{ts.plot}
\title{Plot Multiple Time Series}
\usage{
ts.plot(..., gpars = list())
}
\arguments{
  \item{\dots}{one or more univariate or multivariate time series.}
  \item{gpars}{list of named graphics parameters to be passed to the
    plotting functions.  Those commonly used can be supplied directly in
    \code{\dots}.}
}
\description{
  Plot several time series on a common plot. Unlike
  \code{\link{plot.ts}} the series can have a different time bases,
  but they should have the same frequency.
}
\note{
  Although this can be used for a single time series, \code{plot} is
  easier to use and is preferred.
}
\value{
  None.
}
\author{B.D. Ripley}


\seealso{\code{\link{plot.ts}}}

\examples{
data(UKLungDeaths)
ts.plot(ldeaths, mdeaths, fdeaths,
        gpars=list(xlab="year", ylab="deaths", lty=c(1:3)))
}
\keyword{ts}
\name{ts.union}
\alias{ts.union}
\alias{ts.intersect}
\title{Bind Two or More Time Series}
\usage{
ts.intersect(\dots, dframe = FALSE)
ts.union(\dots, dframe = FALSE)
}
\arguments{
  \item{\dots}{two or more univariate or multivariate time series, or
    objects which can coerced to time series.}
  \item{dframe}{logical; if \code{TRUE} return the result as a data
    frame.}
}
\description{
  Bind time series which have a common frequency. \code{ts.union} pads
  with \code{NA}s to the total time coverage, \code{ts.intersect}
  restricts to the time covered by all the series.
}
\details{
  As a special case, \code{\dots} can contain vectors or matrices of the
  same length as the combined time series of the time series present, as
  well as those of a single row.
}
\value{
  A time series object if \code{dframe} is \code{FALSE}, otherwise a
  data frame.
}
\seealso{\code{\link{cbind}}.}
\author{B. D. Ripley}
\examples{
data(UKLungDeaths)
ts.union(mdeaths, fdeaths)
cbind(mdeaths, fdeaths) # same as the previous line
ts.intersect(window(mdeaths, 1976), window(fdeaths, 1974, 1978))
data(BJsales)
sales1 <- ts.union(BJsales, lead = BJsales.lead)
ts.intersect(sales1, lead3 = lag(BJsales.lead, -3))
}
\keyword{ts}
\name{tsSmooth}
\alias{tsSmooth}
\alias{tsSmooth.StructTS}
\title{Use Fixed-Interval Smoothing on Time Series}
\description{
  Performs fixed-interval smoothing on a univariate time series via a
  state-space model.  Fixed-interval smoothing gives the best estimate
  of the state at each time point based on the whole observed series.
}
\usage{
tsSmooth(object, ...)
}
\arguments{
  \item{object}{a time-series fit.  Currently only class
    \code{"\link{StructTS}"} is supported}
  \item{\dots}{possible arguments for future methods.}
}
\value{
  A time series, with as many dimensions as the state space and results
  at each time point of the original series.  (For seasonal models, only
  the current seasonal component is returned.)
}

\references{
  Durbin, J. and Koopman, S. J. (2001) \emph{Time Series Analysis by
    State Space Methods.}  Oxford University Press.
}

\author{ B. D. Ripley }
 
\seealso{
  \code{\link{KalmanSmooth}}, \code{\link{StructTS}}.

  For examples consult \code{\link{AirPassengers}},
  \code{\link{JohnsonJohnson}} and \code{\link{Nile}}.
}
\keyword{ts}

\name{tsdiag}
\alias{tsdiag}
\alias{tsdiag.arima0}
\alias{tsdiag.Arima}
\alias{tsdiag.StructTS}
\alias{arima0.diag}
\title{Diagnostic Plots for Time-Series Fits}
\description{
  A generic function to plot time-series diagnostics.
}
\usage{
tsdiag(object, gof.lag, ...)
}
\arguments{
  \item{object}{a fitted time-series model}
  \item{gof.lag}{the maximum number of lags for a Portmanteau
    goodness-of-fit test}
  \item{\dots}{further arguments to be passed to particular methods}
}
\details{
  This is a generic function. It will generally plot the residuals,
  often standadized, the autocorrelation function of the residuals, and
  the p-values of a Portmanteau test for all lags up to \code{gof.lag}.

  The methods for \code{\link{arima}} and \code{\link{StructTS}} objects
  plots residuals scaled by the estimate of their (individual) variance,
  and use the Ljung--Box version of the portmanteau test.
}
\value{
  None. Diagnostics are plotted.
}

\author{B. D. Ripley}

\seealso{
  \code{\link{arima}}, \code{\link{StructTS}}, \code{\link{Box.test}}
}
\note{
  \code{\link{arima0.diag}} was an earlier version using the Box--Pierce
  test which is now deprecated.
}

\examples{
\dontrun{data(lh)
fit <- arima(lh, c(1,0,0))
tsdiag(fit)

## see also examples(arima)

data(JohnsonJohnson)
(fit <- StructTS(log10(JohnsonJohnson), type="BSM"))
tsdiag(fit)
}}
\keyword{ts}

