R: 时间序列分析之forecast
Posted 复杂决策系统建模与仿真
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了R: 时间序列分析之forecast相关的知识,希望对你有一定的参考价值。
R时间序列分析之forecast
forecast
Ref: https://cran.r-project.org/web/packages/forecast/forecast.pdf
Methods and tools for displaying and analysing univariate time series forecasts including exponential smoothing via state space models and automatic ARIMA modelling.
++++++++++
library(forecast)
library(fracdiff)
library(ggplot2)
----------
[Topic 1] Datasets
[taylor]
taylor is the data set of Half-hourly electricity demand in England and Wales from Monday 5 June 2000 to Sunday 27 August 2000. Discussed in Taylor (2003), and kindly provided by James W Taylor. Units: Megawatts
Examples
++++++++++
plot(taylor)
----------
[gas]
gas is the data of Australian monthly gas production.
Examples
++++++++++
plot(gas)
seasonplot(gas)
tsdisplay(gas)
----------
[gold]
Daily morning gold prices in US dollars. 1 January 1985 – 31 March 1989.
Examples
++++++++++
tsdisplay(gold)
----------
[wineind]
wineind: Australian total wine sales by wine makers in bottles <= 1 litre. Jan 1980 – Aug 1994.
Examples
++++++++++
tsdisplay(wineind)
----------
[woolyrnq]
woolyrnq: Quarterly production of woollen yarn in Australia: tonnes. Mar 1965 – Sep 1994.
Examples
++++++++++
tsdisplay(woolyrnq)
----------
[Topic 2] Test and accuracy
[ocsb.test]
ocsb.test() doese Osborn, Chui, Smith, and Birchenhall Test for Seasonal Unit Roots. It is An implementation of the Osborn, Chui, Smith, and Birchenhall (OCSB) test.
Examples
++++++++++
ocsb.test(AirPassengers)
----------
[dm.test]
dm.test() does Diebold-Mariano test for predictive accuracy.
Examples
++++++++++
# Test on in-sample one-step forecasts
f1 <- ets(WWWusage)
f2 <- auto.arima(WWWusage)
accuracy(f1)
accuracy(f2)
dm.test(residuals(f1),residuals(f2),h=1)
# Test on out-of-sample one-step forecasts
f1 <- ets(WWWusage[1:80])
f2 <- auto.arima(WWWusage[1:80])
f1.out <- ets(WWWusage[81:100],model=f1)
f2.out <- Arima(WWWusage[81:100],model=f2)
accuracy(f1.out)
accuracy(f2.out)
dm.test(residuals(f1.out),residuals(f2.out),h=1)
----------
[accuracy]
Accuracy measures for a forecast model. It Returns range of summary measures of the forecast accuracy. If x is provided, the function measures test set forecast accuracy based on x-f. If x is not provided, the function only produces training set accuracy measures of the forecasts based on f["x"]-fitted(f). accuracy() returns a Matrix giving forecast accuracy measures.
The measures calculated are:
1) ME: Mean Error
2) RMSE: Root Mean Squared Error
3) MAE: Mean Absolute Error
4) MPE: Mean Percentage Error
5) MAPE: Mean Absolute Percentage Error
6) MASE: Mean Absolute Scaled Error
7) ACF1: Autocorrelation of errors at lag 1.
Examples
++++++++++
fit1 <- rwf(EuStockMarkets[1:200,1],h=100)
fit2 <- meanf(EuStockMarkets[1:200,1],h=100)
print('rwf')
accuracy(fit1)
accuracy(fit1,EuStockMarkets[201:300,1])
print('meanf')
accuracy(fit2)
accuracy(fit2,EuStockMarkets[201:300,1])
plot(fit1)
lines(EuStockMarkets[1:300,1])
plot(fit2)
lines(EuStockMarkets[1:300,1])
----------
[Topic 3] Tools
[tsclean]
tsclean() Identify and replace outliers and missing values in a time series. It Uses supsmu for non-seasonal series and a robust STL decomposition for seasonal series. To estimate missing values and outlier replacements, linear interpolation is used on the (possibly seasonally adjusted) series
Examples
++++++++++
cleangold <- tsclean(gold)
----------
[is.acf]
is.acf(): Is an object a particular model type? It returns true if the model object is of a particular type.
Usage
is.acf(x)
is.Arima(x)
is.baggedModel(x)
is.bats(x)
is.ets(x)
is.modelAR(x)
is.stlm(x)
is.nnetar(x)
is.nnetarmodels(x)
[is.constant]
is.constant(): Is an object constant?. It Returns true if the object’s numerical values do not vary.
[is.forecast]
is.forecast(): Is an object a particular forecast type? It returns true if the forecast object is of a particular type.
Usage
is.forecast(x)
is.mforecast(x)
is.splineforecast(x)
[na.interp]
na.interp() Interpolates missing values in a time series. It Uses linear interpolation for non-seasonal series. For seasonal series, a robust STL decomposition is used. A linear interpolation is applied to the seasonally adjusted data, and then the seasonal component is added back.
Examples
++++++++++
data(gold)
plot(gold)
plot(na.interp(gold))
----------
[simulate.ets]
simulate.ets() does Simulation from a time series model, and Returns a time series based on the model object object.
Examples
++++++++++
fit <- ets(USAccDeaths)
plot(USAccDeaths, xlim=c(1973,1982))
lines(simulate(fit, 36), col="red")
----------
[tsoutliers]
tsoutliers() Identifies and replaces outliers in a time series. It Uses supsmu() for non-seasonal series and a periodic stl decomposition with seasonal series to identify outliers and estimate their replacements.
Examples
++++++++++
data(gold)
tsoutliers(gold)
----------
[Topic 3] Fit, Estimation and Forecast
[Acf]
acf() does Autocorrelation and Cross-Correlation Function Estimation. acf() computes (and by default plots) an estimate of the autocorrelation function of a (possibly multivariate) time series. pacf() computes (and by default plots) an estimate of the partial autocorrelation function of a (possibly multivariate) time series. ccf() computes the cross-correlation or cross-covariance of two univariate series.
Examples
++++++++++
acf(wineind)
pacf(wineind)
taperedacf(wineind, nsim=50)
taperedpacf(wineind, nsim=50)
----------
[arfima]
arfima() fits a fractionally differenced ARFIMA model. arfima() combines fracdiff() and auto.arima() to automatically select and estimate an ARFIMA model. The fractional differencing parameter is chosen first assuming an ARFIMA(2,d,0) model. Then the data are fractionally differenced using the estimated d and an ARMA model is selected for the resulting time series using auto.arima(). Finally, the full ARFIMA(p,d,q) model is re-estimated using fracdiff(). If estim=="mle", the ARMA coefficients are refined using arima.
Examples
++++++++++
x <- fracdiff.sim( 100, ma=-.4, d=.3)$series
fit <- arfima(x)
tsdisplay(residuals(fit))
----------
[Arima]
Arima() is the Fit ARIMA model to univariate time series. Arima() is largely a wrapper for the arima function in the stats package. The main difference is that this function allows a drift term. It is also possible to take an ARIMA model from a previous call to Arima and re-apply it to the data y.
Examples
++++++++++
WWWusage %>%
Arima(order=c(3,1,0)) %>%
forecast(h=20) %>%
autoplot
# Fit model to first few years of AirPassengers data
air.model <- Arima(window(AirPassengers,end=1956+11/12),order=c(0,1,1),
seasonal=list(order=c(0,1,1),period=12),lambda=0)
plot(forecast(air.model,h=48))
lines(AirPassengers)
# Apply fitted model to later data
air.model2 <- Arima(window(AirPassengers,start=1957),model=air.model)
# Forecast accuracy measures on the log scale.
# in-sample one-step forecasts.
accuracy(air.model)
# out-of-sample one-step forecasts.
accuracy(air.model2)
# out-of-sample multi-step forecasts
accuracy(forecast(air.model,h=48,lambda=NULL),
log(window(AirPassengers,start=1957)))
----------
[arimaorder]
arimaorder() Return the order of an ARIMA or ARFIMA model. For a seasonal ARIMA model, the returned vector contains the values p, d, q, P, D, Q and m, where m is the period of seasonality.
Examples
++++++++++
WWWusage %>% auto.arima %>% arimaorder
----------
[auto.arima]
auto.arima() Fit best ARIMA model to univariate time series. auto.arima() returns best ARIMA model according to either AIC, AICc or BIC value. The function conducts a search over possible model within the order constraints provided.
Examples
++++++++++
fit <- auto.arima(WWWusage)
plot(forecast(fit,h=20))
----------
[baggedModel]
baggedModel() does Forecasting using a bagged model. It implements the bagged model forecasting method described in Bergmeir et al. By default, ets() is applied to all bootstrapped series. Base models other than ets() can be given by the parameter fn. Using the default parameters, the function bld.mbb.bootstrap is used to calculate the bootstrapped series with the Box-Cox and Loess-based decomposition (BLD) bootstrap. The function forecast.baggedModel can then be used to calculate forecasts. baggedETS is a wrapper for baggedModel, setting fn to "ets". baggedModel() is included for backwards compatibility only, and may be deprecated in the future.
Examples
++++++++++
fit <- baggedModel(WWWusage)
fcast <- forecast(fit)
plot(fcast)
----------
[bats]
bats() is the BATS model (Exponential smoothing state space model with Box-Cox transformation, ARMA errors, Trend and Seasonal components).
Examples
## Not run:
fit <- bats(USAccDeaths)
plot(forecast(fit))
taylor.fit <- bats(taylor)
plot(forecast(taylor.fit))
## End(Not run)
[bizdays]
bizdays retuns the number of trading days in each season, namely the number of trading days in each month or quarter of the observed time period in a major financial center.
Examples
++++++++++
x <- ts(rnorm(30), start = c(2013, 2), frequency = 12)
bizdays(x, FinCenter = "New York")
----------
[bld.mbb.bootstrap]
bld.mbb.bootstrap() is the Box-Cox and Loess-based decomposition bootstrap. It returns a list with bootstrapped versions of the series. The first series in the list is the original series.
Examples
++++++++++
bootstrapped_series <- bld.mbb.bootstrap(WWWusage, 100)
----------
[BoxCox]
BoxCox conducts Box Cox Transformation. BoxCox() returns a transformation of the input variable using a Box-Cox transformation. InvBoxCox() reverses the transformation.
Examples
++++++++++
lambda <- BoxCox.lambda(lynx)
lynx.fit <- ar(BoxCox(lynx,lambda))
plot(forecast(lynx.fit,h=20,lambda=lambda))
----------
[BoxCox.lambda]
BoxCox.lambda() does Automatic selection of Box Cox transformation parameter
Examples
++++++++++
lambda <- BoxCox.lambda(AirPassengers,lower=0)
air.fit <- Arima(AirPassengers, order=c(0,1,1),
seasonal=list(order=c(0,1,1),period=12), lambda=lambda)
plot(forecast(air.fit))
----------
[checkresiduals]
checkresiduals() Checks that residuals from a time series model look like white noise.
Examples
++++++++++
fit <- ets(WWWusage)
checkresiduals(fit)
----------
[croston]
croston() does Forecasts for intermittent demand using Croston’s method
Examples
++++++++++
y <- rpois(20,lambda=.3)
fcast <- croston(y)
plot(fcast)
----------
[CV]
CV() does Cross-validation statistic. It Computes the leave-one-out cross-validation statistic (also known as PRESS – prediction residual sum of squares), AIC, corrected AIC, BIC and adjusted R^2 values for a linear model.
Examples
++++++++++
y <- ts(rnorm(120,0,3) + 20*sin(2*pi*(1:120)/12), frequency=12)
fit1 <- tslm(y ~ trend + season)
fit2 <- tslm(y ~ season)
CV(fit1)
CV(fit2)
----------
[CVar]
CVar() does k-fold Cross-Validation applied to an autoregressive model. It returns a list containing information about the model and accuracy for each fold, plus other summary information computed across folds.
Examples
++++++++++
modelcv <- CVar(lynx, k=5, lambda=0.15)
print(modelcv)
print(modelcv$fold1)
library(ggplot2)
autoplot(lynx, series="Data") +
autolayer(modelcv$testfit, series="Fits") +
autolayer(modelcv$residuals, series="Residuals")
ggAcf(modelcv$residuals)
----------
[dshw]
dshw() conducts Double-Seasonal Holt-Winters Forecasting. It returns An object of class "forecast".
Examples
## Not run:
fcast <- dshw(taylor)
plot(fcast)
t <- seq(0,5,by=1/20)
x <- exp(sin(2*pi*t) + cos(2*pi*t*4) + rnorm(length(t),0,.1))
fit <- dshw(x,20,5)
plot(fit)
## End(Not run)
[easter]
easter() returns the Easter holidays in each season.
Examples
++++++++++
easter(wineind, easter.mon = TRUE)
----------
[ets]
ets() is the Exponential smoothing state space model. The methodology is fully automatic. The only required argument for ets is the time series. The model is chosen automatically if not specified. This methodology performed extremely well on the M3-competition data.
Examples
++++++++++
fit <- ets(USAccDeaths)
plot(forecast(fit))
----------
[findfrequency]
findfrequency() Finds dominant frequency of a time series. findfrequency() returns the period of the dominant frequency of a time series. For seasonal data, it will return the seasonal period. For cyclic data, it will return the average cycle length. The dominant frequency is determined from a spectral analysis of the time series. First, a linear trend is removed, then the spectral density function is estimated from the best fitting autoregressive model (based on the AIC). If there is a large (possibly local) maximum in the spectral density function at frequency f, then the function will return the period 1/f (rounded to the nearest integer). If no such dominant frequency can be found, the function will return 1.
Examples
++++++++++
findfrequency(USAccDeaths) # Monthly data
findfrequency(taylor) # Half-hourly data
findfrequency(lynx) # Annual data
----------
[fitted.fracdiff]
fitted.fracdiff() conducts h-step in-sample forecasts for time series models.
Examples
++++++++++
fit <- ets(WWWusage)
plot(WWWusage)
lines(fitted(fit), col='red')
lines(fitted(fit, h=2), col='green')
lines(fitted(fit, h=3), col='blue')
legend("topleft", legend=paste("h =",1:3), col=2:4, lty=1)
----------
[forecast]
forecast() is a generic function for forecasting from time series or time series models. The function invokes particular methods which depend on the class of the first argument. It returns An object of class "forecast". The function summary is used to obtain and print a summary of the results, while the function plot produces a plot of the forecasts and prediction intervals. The generic accessors functions fitted.values and residuals extract various useful features of the value returned by forecast$model.
Examples
++++++++++
WWWusage %>% forecast %>% plot
fit <- ets(window(WWWusage, end=60))
fc <- forecast(WWWusage, model=fit)
----------
[forecast.baggedModel]
forecast.baggedModel() conducts Forecasting using a bagged model.
Examples
++++++++++
fit <- baggedModel(WWWusage)
fcast <- forecast(fit)
plot(fcast)
----------
## Not run:
fit2 <- baggedModel(WWWusage, fn="auto.arima")
fcast2 <- forecast(fit2)
plot(fcast2)
accuracy(fcast2)
## End(Not run)
[forecast.bats]
forecast.bats() conducts Forecasting using BATS and TBATS models.
Examples
## Not run:
fit <- bats(USAccDeaths)
plot(forecast(fit))
taylor.fit <- bats(taylor)
plot(forecast(taylor.fit))
## End(Not run)
[forecast.ets]
forecast.ets() does Forecasting using ETS models.
Examples
++++++++++
fit <- ets(USAccDeaths)
plot(forecast(fit,h=48))
----------
[forecast.fracdiff]
forecast.fracdiff() does Forecasting using ARIMA or ARFIMA models.
Examples
++++++++++
fit <- Arima(WWWusage,c(3,1,0))
plot(forecast(fit))
x <- fracdiff.sim( 100, ma=-.4, d=.3)$series
fit <- arfima(x)
plot(forecast(fit,h=30))
----------
[forecast.HoltWinters]
forecast.HoltWinters() does Forecasting using Holt-Winters objects.
Examples
++++++++++
fit <- HoltWinters(WWWusage,gamma=FALSE)
plot(forecast(fit))
----------
[forecast.lm]
forecast.lm() Forecasts a linear model with possible time series components. forecast.lm() is used to predict linear models, especially those involving trend and seasonality components. forecast.lm is largely a wrapper for predict.lm() except that it allows variables "trend" and "season" which are created on the fly from the time series characteristics of the data. Also, the output is reformatted into a forecast object.
Examples
++++++++++
y <- ts(rnorm(120,0,3) + 1:120 + 20*sin(2*pi*(1:120)/12), frequency=12)
fit <- tslm(y ~ trend + season)
plot(forecast(fit, h=20))
----------
[forecast.mlm]
forecast.mlm() Forecasts a multiple linear model with possible time series components. forecast.mlm is used to predict multiple linear models, especially those involving trend and seasonality components.
Examples
++++++++++
lungDeaths <- cbind(mdeaths, fdeaths)
fit <- tslm(lungDeaths ~ trend + season)
fcast <- forecast(fit, h=10)
plot(fcast)
carPower <- as.matrix(mtcars[,c("qsec","hp")])
carmpg <- mtcars[,"mpg"]
fit <- lm(carPower ~ carmpg)
fcast <- forecast(fit, newdata=data.frame(carmpg=30))
plot(fcast)
----------
[forecast.nnetar]
forecast.nnetar() Forecasts using neural network models. Prediction intervals are calculated through simulations and can be slow. Note that if the network is too complex and overfits the data, the residuals can be arbitrarily small; if used for prediction interval calculations, they could lead to misleadingly small values. It is possible to use out-of sample residuals to ameliorate this, see examples.
Examples
++++++++++
## Fit & forecast model
fit <- nnetar(USAccDeaths, size=2)
fcast <- forecast(fit, h=20)
plot(fcast)
----------
## Not run:
## Include prediction intervals in forecast
fcast2 <- forecast(fit, h=20, PI=TRUE, npaths=100)
plot(fcast2)
## Set up out-of-sample innovations using cross-validation
fit_cv <- CVar(USAccDeaths, size=2)
res_sd <- sd(fit_cv$residuals, na.rm=TRUE)
myinnovs <- rnorm(20*100, mean=0, sd=res_sd)
## Forecast using new innovations
fcast3 <- forecast(fit, h=20, PI=TRUE, npaths=100, innov=myinnovs)
plot(fcast3)
## End(Not run)
[forecast.stl]
forecast.stl() does Forecasting using stl objects. Forecasts of STL objects are obtained by applying a non-seasonal forecasting method to the seasonally adjusted data and re-seasonalizing using the last year of the seasonal component.
[stlm]
stlm() takes a time series y, applies an STL decomposition, and models the seasonally adjusted data using the model passed as modelfunction or specified using method. It returns an object that includes the original STL decomposition and a time series model fitted to the seasonally adjusted data. This object can be passed to the forecast.stlm() for forecasting.
forecast.stlm() forecasts the seasonally adjusted data, then re-seasonalizes the results by adding back the last year of the estimated seasonal component.
stlf() combines stlm() and forecast.stlm(). It takes a ts argument, applies an STL decomposition, models the seasonally adjusted data, reseasonalizes, and returns the forecasts. However, it allows more general forecasting methods to be specified via forecast function.
forecast.stl() is similar to stlf() except that it takes the STL decomposition as the first argument, instead of the time series.
Examples
++++++++++
tsmod <- stlm(USAccDeaths, modelfunction=ar)
plot(forecast(tsmod, h=36))
decomp <- stl(USAccDeaths,s.window="periodic")
plot(forecast(decomp))
plot(stlf(AirPassengers, lambda=0))
----------
[forecast.StructTS]
forecast.StructTS() Forecasts using Structural Time Series models.
Examples
++++++++++
fit <- StructTS(WWWusage,"level")
plot(forecast(fit))
----------
[fourier]
Fourier terms for modelling seasonality. fourier() returns a matrix containing terms from a Fourier series, up to order K, suitable for use in Arima(), auto.arima(), or tslm().
Examples
++++++++++
# Using Fourier series for a "ts" object
# K is chosen to minimize the AICc
deaths.model <- auto.arima(USAccDeaths, xreg=fourier(USAccDeaths,K=5), seasonal=FALSE)
deaths.fcast <- forecast(deaths.model, xreg=fourier(USAccDeaths, K=5, h=36))
autoplot(deaths.fcast) + xlab("Year")
# Using Fourier series for a "msts" object
taylor.lm <- tslm(taylor ~ fourier(taylor, K = c(3, 3)))
taylor.fcast <- forecast(taylor.lm,
data.frame(fourier(taylor, K = c(3, 3), h = 270)))
autoplot(taylor.fcast)
----------
[autoplot.acf]
autoplot.acf() conducts Autocorrelation and Cross-Correlation Function Estimation and Plotting. It produces a ggplot object of their equivalent Acf, Pacf, Ccf, taperedacf and taperedpacf functions.
Examples
++++++++++
ggAcf(wineind)
wineind %>% Acf(plot=FALSE) %>% autoplot
wineind %>% taperedacf(plot=FALSE) %>% autoplot
ggtaperedacf(wineind)
ggtaperedpacf(wineind)
ggCcf(mdeaths, fdeaths)
----------
[autoplot.decomposed.ts]
autoplot.decomposed.ts() Plots time series decomposition components using ggplot, and Produces a ggplot object of seasonally decomposed time series for objects of class “stl” (created with stl), class “seas” (created with seas), or class “decomposed.ts” (created with decompose).
Examples
++++++++++
co2 %>% decompose %>% autoplot
nottem %>% stl(s.window='periodic') %>% autoplot
----------
[autoplot.mforecast]
autoplot.mforecast() conducts Multivariate forecast plot, and Plots historical data with multivariate forecasts and prediction intervals.
Examples
++++++++++
lungDeaths <- cbind(mdeaths, fdeaths)
fit <- tslm(lungDeaths ~ trend + season)
fcast <- forecast(fit, h=10)
plot(fcast)
autoplot(fcast)
carPower <- as.matrix(mtcars[,c("qsec","hp")])
carmpg <- mtcars[,"mpg"]
fit <- lm(carPower ~ carmpg)
fcast <- forecast(fit, newdata=data.frame(carmpg=30))
plot(fcast, xlab="Year")
autoplot(fcast, xlab=rep("Year",2))
----------
[getResponse]
getResponse() Gets response variable from time series model. getResponse() is a generic function for extracting the historical data from a time series model (including Arima, ets, ar, fracdiff), a linear model of class lm, or a forecast object. The function invokes particular methods which depend on the class of the first argument
ma() is Moving-average smoothing. ma() computes a simple moving average smoother of a given time series.
Examples
++++++++++
plot(wineind)
sm <- ma(wineind,order=12)
lines(sm,col="red")
----------
[
meanf]
meanf is Mean Forecast. meanf Returns forecasts and prediction intervals for an iid model applied to y.
Examples
++++++++++
nile.fcast <- meanf(Nile, h=10)
plot(nile.fcast)
----------
[
monthdays]
monthdays() returns the Number of days in each season.
Examples
++++++++++
par(mfrow=c(2,1))
plot(ldeaths,xlab="Year",ylab="pounds",
main="Monthly deaths from lung disease (UK)")
ldeaths.adj <- ldeaths/monthdays(ldeaths)*365.25/12
plot(ldeaths.adj,xlab="Year",ylab="pounds",
main="Adjusted monthly deaths from lung disease (UK)")
----------
[
mstl]
mstl() doese Multiple seasonal decomposition. It Decompose a time series into seasonal, trend and remainder components. Seasonal components are estimated iteratively using STL. Multiple seasonal periods are allowed. Unlike stl, mstl is completely automated.
Examples
++++++++++
mstl(taylor) %>% autoplot(facet=TRUE)
mstl(AirPassengers, lambda='auto') %>% autoplot(facet=TRUE)
----------
[
msts]
msts() analyzes Multi-Seasonal Time Series. msts() is an S3 class for multi seasonal time series objects, intended to be used for models that support multiple seasonal periods. The msts class inherits from the ts class and has an additional "msts" attribute which contains the vector of seasonal periods. All methods that work on a ts class, should also work on a msts class.
Examples
++++++++++
x <- msts(taylor, seasonal.periods=c(48,336), start=2000+22/52)
y <- msts(USAccDeaths, seasonal.periods=12, start=1949)
----------
[
ndiffs]
ndiffs() returns the Number of differences required for a stationary series.
Examples
++++++++++
ndiffs(WWWusage)
ndiffs(diff(log(AirPassengers),12))
----------
[
nnetar]
nnetar() does Neural Network Time Series Forecasts by using Feed-forward neural networks with a single hidden layer and lagged inputs for forecasting univariate time series.
Examples
++++++++++
fit <- nnetar(lynx)
fcast <- forecast(fit)
plot(fcast)
## Arguments can be passed to nnet()
fit <- nnetar(lynx, decay=0.5, maxit=150)
plot(forecast(fit))
lines(lynx)
## Fit model to first 100 years of lynx data
fit <- nnetar(window(lynx,end=1920), decay=0.5, maxit=150)
plot(forecast(fit,h=14))
lines(lynx)
## Apply fitted model to later data, including all optional arguments
fit2 <- nnetar(window(lynx,start=1921), model=fit)
----------
[
nsdiffs]
nsdiffs() returns the Number of differences required for a seasonally stationary series.
Examples
++++++++++
nsdiffs(AirPassengers)
----------
[
sindexf]
sindexf() Forecasts seasonal index, Returns vector containing the seasonal index for h future periods. If the seasonal index is nonperiodic, it uses the last values of the index.
Examples
++++++++++
uk.stl <- stl(UKDriverDeaths,"periodic")
uk.sa <- seasadj(uk.stl)
uk.fcast <- holt(uk.sa,36)
seasf <- sindexf(uk.stl,36)
uk.fcast$mean <- uk.fcast$mean + seasf
uk.fcast$lower <- uk.fcast$lower + cbind(seasf,seasf)
uk.fcast$upper <- uk.fcast$upper + cbind(seasf,seasf)
uk.fcast$x <- UKDriverDeaths
plot(uk.fcast,main="Forecasts from Holt's method with seasonal adjustment")
----------
[
splinef]
splinef() does Cubic Spline Forecast, and Returns local linear forecasts and prediction intervals using cubic smoothing splines.
Examples
++++++++++
fcast <- splinef(uspop,h=5)
plot(fcast)
summary(fcast)
----------
[
StatForecast]
StatForecast() Generates forecasts from forecast.ts and adds them to the plot. Forecasts can be modified via sending forecast specific arguments above.
Examples
## Not run:
library(ggplot2)
autoplot(USAccDeaths) + geom_forecast()
lungDeaths <- cbind(mdeaths, fdeaths)
autoplot(lungDeaths) + geom_forecast()
# Using fortify.ts
p <- ggplot(aes(x=x, y=y), data=USAccDeaths)
p <- p + geom_line()
p + geom_forecast()
# Without fortify.ts
data <- data.frame(USAccDeaths=as.numeric(USAccDeaths), time=as.numeric(time(USAccDeaths)))
p <- ggplot(aes(x=time, y=USAccDeaths), data=data)
p <- p + geom_line()
p + geom_forecast()
p + geom_forecast(h=60)
p <- ggplot(aes(x=time, y=USAccDeaths), data=data)
p + geom_forecast(level=c(70,98))
p + geom_forecast(level=c(70,98),colour="lightblue")
#Add forecasts to multivariate series with colour groups
lungDeaths <- cbind(mdeaths, fdeaths)
autoplot(lungDeaths) + geom_forecast(forecast(mdeaths), series="mdeaths")
## End(Not run)
[
subset.ts]
subset.ts() does Subsetting a time series by various types of subsetting.
Examples
++++++++++
plot(subset(gas,month="November"))
subset(woolyrnq,quarter=3)
subset(USAccDeaths, start=49)
----------
[
tbats]
tbats() is the TBATS model (Exponential smoothing state space model with Box-Cox transformation, ARMA errors, Trend and Seasonal components).
Examples
## Not run:
fit <- tbats(USAccDeaths)
plot(forecast(fit))
taylor.fit <- tbats(taylor)
plot(forecast(taylor.fit))
## End(Not run)
[
tbats.components]
tbats.components() Extracts components of a TBATS model, Extracts the level, slope and seasonal components of a TBATS model. The extracted components are Box-Cox transformed using the estimated transformation parameter.
Examples
## Not run:
fit <- tbats(USAccDeaths, use.parallel=FALSE)
components <- tbats.components(fit)
plot(components)
## End(Not run)
[
thetaf]
thetaf() is Theta method forecast, Returns forecasts and prediction intervals for a theta method forecast.
Examples
++++++++++
nile.fcast <- thetaf(Nile)
plot(nile.fcast)
----------
[
tsCV]
tsCV() does Time series cross-validation. tsCV computes the forecast errors obtained by applying forecastfunction to subsets of the time series y using a rolling forecast origin.
Examples
++++++++++
#Fit an AR(2) model to each rolling origin subset
far2 <- function(x, h){forecast(Arima(x, order=c(2,0,0)), h=h)}
e <- tsCV(lynx, far2, h=1)
#Fit the same model with a rolling window of length 30
e <- tsCV(lynx, far2, h=1, window=30)
----------
[
tslm]
tslm() Fits a linear model with time series components. tslm() is used to fit linear models to time series including trend and seasonality components. tslm is largely a wrapper for lm() except that it allows variables "trend" and "season" which are created on the fly from the time series characteristics of the data. The variable "trend" is a simple time trend and "season" is a factor indicating the season (e.g., the month or the quarter depending on the frequency of the data).
Examples
++++++++++
y <- ts(rnorm(120,0,3) + 1:120 + 20*sin(2*pi*(1:120)/12), frequency=12)
fit <- tslm(y ~ trend + season)
plot(forecast(fit, h=20))
----------
[
residuals.forecast]
residuals.forecast() returns Residuals for various time series models
Examples
++++++++++
fit <- Arima(lynx,order=c(4,0,0), lambda=0.5)
plot(residuals(fit))
plot(residuals(fit, type='response'))
----------
[
rwf]
rwf() does Naive and Random Walk Forecasts. rwf() returns forecasts and prediction intervals for a random walk with drift model applied to y. This is equivalent to an ARIMA(0,1,0) model with an optional drift coefficient. naive() is simply a wrapper to rwf() for simplicity. snaive() returns forecasts and prediction intervals from an ARIMA(0,0,0)(0,1,0)m model where m is the seasonal period.
Examples
++++++++++
gold.fcast <- rwf(gold[1:60], h=50)
plot(gold.fcast)
plot(naive(gold,h=50),include=200)
plot(snaive(wineind))
----------
[
seasadj]
seasadj() does Seasonal adjustment, Returns seasonally adjusted data constructed by removing the seasonal component.
Examples
++++++++++
plot(AirPassengers)
lines(seasadj(decompose(AirPassengers,"multiplicative")),col=4)
----------
[
seasonal]
seasonal() Extracts components from a time series decomposition, and Returns a univariate time series equal to either a seasonal component, trend-cycle component or remainder component from a time series decomposition.
Examples
++++++++++
plot(USAccDeaths)
fit <- stl(USAccDeaths, s.window="periodic")
lines(trendcycle(fit),col="red")
autoplot(cbind(Data=USAccDeaths, Seasonal=seasonal(fit),
Trend=trendcycle(fit), Remainder=remainder(fit)),
facets=TRUE) + ylab("") + xlab("Year")
----------
[
seasonaldummy]
seasonaldummy() returns a matrix of dummy variables suitable for use in Arima, auto.arima or tslm. The last season is omitted and used as the control.
Examples
++++++++++
plot(ldeaths)
# Using seasonal dummy variables
month <- seasonaldummy(ldeaths)
deaths.lm <- tslm(ldeaths ~ month)
tsdisplay(residuals(deaths.lm))
ldeaths.fcast <- forecast(deaths.lm,
data.frame(month=I(seasonaldummy(ldeaths,36))))
plot(ldeaths.fcast)
# A simpler approach to seasonal dummy variables
deaths.lm <- tslm(ldeaths ~ season)
ldeaths.fcast <- forecast(deaths.lm, h=36)
plot(ldeaths.fcast)
----------
[
ses]
ses() does Exponential smoothing forecasts, Returns forecasts and other information for exponential smoothing forecasts applied to y.
Examples
++++++++++
fcast <- holt(airmiles)
plot(fcast)
deaths.fcast <- hw(USAccDeaths,h=48)
plot(deaths.fcast)
----------
[
Topic 4] Plot
[
autolayer]
autolayer() Creates a ggplot layer appropriate to a particular data type
[
autolayer.mts]
autolayer.mts() automatically create a ggplot for time series objects
Examples
++++++++++
library(ggplot2)
autoplot(USAccDeaths)
lungDeaths <- cbind(mdeaths, fdeaths)
autoplot(lungDeaths)
autoplot(lungDeaths, facets=TRUE)
----------
[
gghistogram]
Histogram with optional normal and kernel density functions Plots a histogram and density estimates using ggplot.
Examples
++++++++++
gghistogram(lynx, add.kde=TRUE)
----------
[
gglagplot]
gglagplot() does Time series lag ggplots
Examples
++++++++++
gglagplot(woolyrnq)
gglagplot(woolyrnq,seasonal=FALSE)
lungDeaths <- cbind(mdeaths, fdeaths)
gglagplot(lungDeaths, lags=2)
gglagchull(lungDeaths, lags=6)
gglagchull(woolyrnq)
----------
[
ggmonthplot]
ggmonthplot() Creates a seasonal subseries ggplot. It Plots a subseries plot using ggplot. Each season is plotted as a separate mini time series. The blue lines represent the mean of the observations within each season.
Examples
++++++++++
ggsubseriesplot(AirPassengers)
ggsubseriesplot(woolyrnq)
----------
[
ggseasonplot]
ggseasonplot() does Seasonal plot.
Examples
++++++++++
ggseasonplot(AirPassengers, col=rainbow(12), year.labels=TRUE)
ggseasonplot(AirPassengers, year.labels=TRUE, continuous=TRUE)
seasonplot(AirPassengers, col=rainbow(12), year.labels=TRUE)
----------
[
ggtsdisplay]
ggtsdisplay() displays Time series, Plots a time series along with its acf and either its pacf, lagged scatterplot or spectrum.
Examples
++++++++++
ggtsdisplay(USAccDeaths, plot.type="scatter", theme=theme_bw())
tsdisplay(diff(WWWusage))
ggtsdisplay(USAccDeaths, plot.type="scatter")
----------
[
plot.Arima]
plot.Arima() Plots characteristic roots from ARIMA model. It Produces a plot of the inverse AR and MA roots of an ARIMA model. Inverse roots outside the unit circle are shown in red.
Examples
++++++++++
fit <- Arima(WWWusage, order=c(3,1,0))
plot(fit)
autoplot(fit)
fit <- Arima(woolyrnq,order=c(2,0,0),seasonal=c(2,1,1))
plot(fit)
autoplot(fit)
plot(ar.ols(gold[1:61]))
autoplot(ar.ols(gold[1:61]))
----------
[
plot.bats]
plot.bats() Plots components from BATS model, and Produces a plot of the level, slope and seasonal components from a BATS or TBATS model. The plotted components are Box-Cox transformed using the estimated transformation parameter
Examples
## Not run:
fit <- tbats(USAccDeaths)
plot(fit)
autoplot(fit, range.bars = TRUE)
## End(Not run)
[
plot.ets]
plot.ets() Plots components from ETS model, Produces a plot of the level, slope and seasonal components from an ETS model.
Examples
++++++++++
fit <- ets(USAccDeaths)
plot(fit)
plot(fit,plot.type="single",ylab="",col=1:3)
library(ggplot2)
autoplot(fit)
----------
[
plot.forecast]
plot.forecast() Plots historical data with forecasts and prediction intervals.
Examples
++++++++++
wine.fit <- hw(wineind,h=48)
plot(wine.fit)
autoplot(wine.fit)
fit <- tslm(wineind ~ fourier(wineind,4))
fcast <- forecast(fit, newdata=data.frame(fourier(wineind,4,20)))
autoplot(fcast)
fcast <- splinef(airmiles,h=5)
plot(fcast)
autoplot(fcast)
----------
[
Keywords]
ARFIMA
ARMA
ARMA errors
Autocorrelation and Cross-Correlation
automatic ARIMA modelling
autoregressive model
backwards compatibility
bagged model
bootstrapped series
bootstrapped versions of the series
Box-Cox and Loess-based decomposition (BLD) bootstrap
Box-Cox transformation
confidence value
cross-correlation or cross-covariance
Cross-validation statistic
cubic smoothing spline
Cubic Spline Forecast
CVar
cyclic data
Diebold-Mariano test
dominant frequency of a time series
Double-Seasonal Holt-Winters Forecasting
drift model
drift term
exponential smoothing
Exponential smoothing forecasts
Exponential smoothing state space model
Feed-forward neural network
Fourier series
h-step in-sample forecast
intermittent demand
k-fold Cross-Validation
leave-one-out cross-validation statistic
linear interpolation
Loess-based decomposition bootstrap
M3-competition data
Mean Forecast
Moving-average smoothing
multiple linear model
Multiple seasonal decomposition
Multi-Seasonal Time Series
multivariate time series
Naive and Random Walk Forecasts
neural network model
non-seasonal forecasting
one-step forecasts
Osborn, Chui, Smith, and Birchenhall (OCSB) test
partial autocorrelation
PRESS – prediction residual sum of squares
re-seasonalizing
residual
response variable
robust
S3 class
Seasonal adjustment
seasonal, trend and remainder components
seasonally stationary series
spectral analysis
spectral density function
state space model
stationary series
Structural Time Series model
TBATS model: Exponential smoothing state space model with Box-Cox transformation, ARMA errors, Trend and Seasonal components
Theta method forecast
time series decomposition components
trading days
Trend and Seasonal components
univariate time series
forecast accuracy
1) ME: Mean Error
2) RMSE: Root Mean Squared Error
3) MAE: Mean Absolute Error
4) MPE: Mean Percentage Error
5) MAPE: Mean Absolute Percentage Error
6) MASE: Mean Absolute Scaled Error
7) ACF1: Autocorrelation of errors at lag 1.
以上是关于R: 时间序列分析之forecast的主要内容,如果未能解决你的问题,请参考以下文章
时间序列分析:趋势时间序列分析之异常点检测和FORECAST过程建立趋势模式
未找到预测包中的 R forecast.holtwinters