\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{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}
% file UKDriverDeaths.Rd
% copyright (C) 1994-9 W. N. Venables and B. D. Ripley
%
\name{UKDriverDeaths}
\alias{UKDriverDeaths}
\title{
  Deaths of Car Drivers in Great Britain 1969--84
}
\description{
  A regular 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.
}
\usage{data(UKDriverDeaths)}
\source{
  Harvey, A.C. (1989)
  \emph{Forecasting, Structural Time Series Models and the Kalman Filter.}
  Cambridge University Press, pp. 519--523.
}
\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}
% 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{acf}
\alias{acf}
\alias{ccf}
\alias{pacf}
\alias{pacf.default}
\alias{pacf.ts}
\alias{pacf.mts}
\title{Autocovariance and Autocorrelation 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.}
  \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.

  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.
}
\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(LakeHuron)
ar(LakeHuron)
ar(LakeHuron, method="burg")
ar(LakeHuron, method="ols")


data(sunspot)
sunspot.ar <- ar(sunspot.year)
sunspot.ar
ar(x = sunspot.year, method = "burg")
ar(x = sunspot.year, method = "ols")
\dontrun{## next is slow and may have convergence problems,
## as it cares about invertibility
ar(x = sunspot.year, method = "mle")
}
predict(sunspot.ar, n.ahead=25)

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{arima0}
\alias{arima0}
\alias{arima0.diag}
\alias{print.arima0}
\alias{predict.arima0}
\title{ARIMA Modelling of Time Series -- Preliminary Version}
\usage{
arima0(x, order = c(0, 0, 0),
       seasonal = list(order = c(0, 0, 0), period = NA),
       xreg = NULL, include.mean = TRUE, na.action = na.fail,
       delta = 0.01, transform.pars = 2)

\method{predict}{arima0}(object, n.ahead = 1, newxreg, se.fit = TRUE, ...)

arima0.diag(fit, gof.lag = 10) 
}
\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)}).}

  \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{na.action}{Function to be applied to remove missing values.}

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

  \item{transform.pars}{If greater than 0, the ARMA parameters are
    transformed to ensure that they remain in the region of
    invertibility. If equal to 2, the optimization is rerun on
    the original scale to find the Hessian.}

  \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.}
}
\description{
  Fit an ARIMA model to a univariate time series by exact maximum
  likelihood, and forecast from the fitted model.
}
\details{
  Different definitions of ARIMA 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}.
    
  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 using the Fortran code of Gardener \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.

  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.

  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.
}
\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}. If \code{transform.pars = 1}, only the portion
    corresponding to the untransformed parameters is returned.}

  \item{loglik}{the maximized log-likelihood (of the differenced data).}

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

  \item{resid}{the residuals.}

  \item{call}{the matched call.}

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

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

  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.

    Gardener, 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, section 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.
}

\author{B.D. Ripley}
\note{
  This is a preliminary version, and will be replaced in due course.

  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{ar}}}

\examples{
data(lh)
arima0(lh, order=c(1,0,0))
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)

data(USAccDeaths)
fit <- arima0(USAccDeaths, order=c(0,1,1), seasonal=list(order=c(0,1,1)))
fit
predict(fit, n.ahead=6)

data(LakeHuron)
arima0(LakeHuron, order=c(2,0,0), xreg=1:98)
}
\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{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}}}

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

## A simple simulation function for ARMA processes
arma.sim <- function(n, ar = NULL, ma = NULL, sigma = 1.0)
{
    x <- ts(rnorm(n+100, 0, sigma), start = -99)
    if(length(ma)) x <- filter(x, c(1, ma), sides=1)
    if(length(ar)) x <- filter(x, ar, method = "recursive")
    as.ts(x[-(1:100)])
}
arma.sim(63, c(0.8897,-0.4858), c(-0.2279, 0.2488), sigma=sqrt(0.1796))
}
\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")

data(sunspots) # no lines for larges series :
lag.plot(sqrt(sunspots), set = c(1:4, 9:12), pch = ".", col = "gold")

## Multivariate (but non-stationary! ...)
data(freeny)
lag.plot(freeny.x, lag = 3)
}
\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{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}
% file nottem.Rd
% copyright (C) 1994-9 W. N. Venables and B. D. Ripley
%
\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.
}
\keyword{datasets}
\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{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-internal}
\alias{arma0f}
\title{Internal ts functions}
\description{
  Internal ts functions.
}
\usage{
arma0f(p)
}
\details{
  These are not to be called by the user.
}
\keyword{internal}
\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}
}
\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)))

data(nottem)
nott <- window(nottem, end=c(1936,12))
fit <- arima0(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{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}
