# Featured Methods

acf:        Auto-correlation or auto-covariance of univariate series.
ar:         Multivariate Autoregressive Model.
arsim:      Simulated Multivariate Autoregressive Model.
ccf:        Cross-correlation or cros-covariance of two univariate series.
d:          Lagged differences of a given order for Vector and Array
forecast:   Forecast values of fitted time series models.
hma:        Henderson moving average filter.
loess:      Locally estimated scatterplot smoothing.
p:          Reverse lagged differences of a given order for types Vector and Array.
pacf:       Partial Auto-correlation function.
sma:        Simple moving average.
splot:      Plot a seasonal plot for types Vector and TimeArray.
stl:        Seasonal and Trend decomposition using loess.
summarize:  Statistical summary.

## acf

Auto-correlation/covariance function

Forecast.acfFunction

Package: Forecast

acf(x::{AbstractVector,DataFrame},
type = "cor",
lag = Integer(ceil(10*log10(length(x)))),
alpha = (0.95,0.99))

Compute the auto-correlation or auto-covariance for an univariate series.

The results are normalized to preserve homoscedasticity. The distribution used to normalize the data is an approximation of a Fisher Transformation via a Normal Distribution. There is a plot recipe for the returned object, if the type is cor the plot will also show confidence intervals for the given alpha values.

Arguments

• x: Vector or uni-dimensional DataFrame of data.
• type: Valid values are "cor" for correlation (default) and "cov" for convariance.
• lag: Maximum number of lags.
• alpha: A tuple with two thresholds (t1,t2) with t1 <= t2 to plot confidence intervals. The default values are 0.95 and 0.99.

Returns

A CCF object.

Examples

julia> x = rand(100);
res = acf(x; type="cor");
plot(res)

## ar

Autoregressive model

Forecast.arFunction

Package: Forecast

ar(x::DataFrame, or, constant = true;
alpha = 1.0, dΦ0 = nothing, dΦ = nothing)

ar(x::AbstractArray, or, constant = true;
alpha = false, dΦ0 = nothing, dΦ = nothing, varnames = nothing)

Fit a multivariate autoregressive series model.

The fitting is done via Ordinary Least Squared and implements the following model:

$$$Xt = \Phi_0 + \sum_{i=1}^p \Phi_i \cdot X_{t-i} + \mathcal{N}(\vec{0},\Sigma)$$$

Arguments

• x: Multivariate series each column containing a dimension and ordered by time ascending rows.
• or: Number of parameters Φ to be estimated.
• constant: If truear estimates Φ0 otherwise it is assume to be zero.
• alpha: fixes to zero all coefficients which significance is below its value. It defaults to one.
• dΦ0: Tuple containing two Φ0 objects, the first one will act as an original reference to the second one and different values will be fixed in the fitting process to the values in the second Φ0.
• dΦ: Equivalent to dΦ0 but for Φ.
• varnames: Names of the dimensions (by default xi where i is an integer)

Returns

An AR object containing the model coefficients, the error sigma matrix, residuals and a collection of information criteria

Examples

julia-repl julia> ar(rand(100,2),2) AR([...])

## arsim

Autoregressive simulation

Forecast.arsimFunction

Package: Forecast

arsim(Φ,Φ0,x0,n; Σ,E,fix)
arsim(AR,n;fix)

Simulate a multivariate autoregressive series model.

The simulated series follows the model:

$$$Xt = \Phi_0 + \sum_{i=1}^p \Phi_i \cdot X_{t-i} + E$$$

Arguments

• AR: AR struct coming from an ar model.

• Φ: Array with dimensions (m,m,p) for the parameters in the AR model.

• Φ0: Vector size m for the constant in the AR model. Default value is 0.

• x0: Array with dimensions (m,p) for the initial value in the AR model. Default value is a random value from zero to one.

• n: Number of simulations.

• fix: Matrix{Union{Missing,Float64}} containing values to be fixed in th simulation.

• Σ2: Variance Covariance matrix for the AR model with a MvNormal distribution for the noise. Default value is an identity Matrix.

• E: Distribution for the error.

Returns

A multivariate series simulating an AR model each column containing a dimension and ordered by time ascending rows.

Examples

julia-repl julia> arsim(1,1,1,10) 10-element Vector{Float64,1}: [...]

## boxcox

Autoregressive simulation

Forecast.boxcoxFunction

Package: Forecast

boxcox(x::Vector)
boxcox(x::Vector, λ::Float64)
boxcox(x::Vector, λ::Vector)

Compute a Box-Cox power transformation given λ or (λ1,λ2) for data containing negative values, or compute an optimal power transformation if no λ or (λ1,λ2) is provided.

$$$x(\lambda) = \begin{cases} \dfrac{x_i^\lambda - 1}{\lambda} & \text{if } \lambda \neq 0 \\ \ln x_i & \text{if } \lambda = 0 \end{cases}$$$

for negative values

$$$x(\boldsymbol{\lambda}) = \begin{cases} \dfrac{(x_i + \lambda_2)^{\lambda_1} - 1}{\lambda_1} & \text{if } \lambda_1 \neq 0 \\ \ln (x_i + \lambda_2) & \text{if } \lambda_1 = 0 \end{cases}$$$

Arguments

• x: Vector to be transformed.
• λ: Exponent/s for the tranformation

Returns

A vector with a boxcox tarnsformation for x or a Dict with :x boxcox tranformed and the optimal :λ

Reference

Box, G. E. P. and Cox, D. R. (1964). An analysis of transformations, Journal of the Royal Statistical Society, Series B, 26, 211-252. A

Examples

julia> x = rand(100)
julia> bc = boxcox(x)
julia> iboxcox(bc[:x],bc[:λ]) ≈ x

julia> x = rand(100) .- 0.5
julia> bc = boxcox(x)
julia> iboxcox(bc[:x],bc[:λ]) ≈ x

## ccf

Cros-correlation/covariance function

Forecast.ccfFunction

Package: Forecast

ccf(x1::{AbstractVector,DataFrame},
x2::{AbstractVector,DataFrame};
type = "cor",
lag = Integer(ceil(10*log10(length(x1)))),
alpha = (0.95,0.99))

Compute the cross-correlation or cros-covariance of two univariate series.

The results are normalized to preserve homoscedasticity. The distribution used to normalize the data is an approximation of a Fisher Transformation via a Normal Distribution. There is a plot recipe for the returned object, if the type is cor the plot will also show confidence intervals for the given alpha values.

If, for a given integer k, x2 repeats x1 values such that x1[t] = x2[t+k] for all i then high correlation value will be placed at the right from the center in the results. That is, this convention will be represented in the plots as x1_t = x2_{t+k} -> _____0__k__ meaning x2 behavior can be predicted by x1 in k units.

Arguments

• x1: Vector or uni-dimensional DataFrame of data.
• x2: Vector or uni-dimensional DataFrame of data.
• type: Valid values are "cor" for correlation (default) and "cov" for convariance.
• lag: Maximum number of lags.
• alpha: A tuple with two thresholds (t1,t2) with t1 <= t2 to plot confidence intervals. The default values are 0.95 and 0.99.

Returns

A CCF object.

Examples

julia> x1 = rand(100);
x2 = circshift(x1,6);
res = ccf(x1, x2; type="cor");
plot(res)

## d

Lagged differences of a given order

Forecast.dFunction

Package: Forecast

function d(x::{AbstractVector,AbstractArray,DataFrame},
or::Int=1,
la::Int=1;
center::Bool=false)

Return Laged differences of a given or for Vector, Array and TimeSeries.

Arguments

• x: Vector or Array of data.
• or: Order of the differences; number of recursive iterations on the same vector/array.
• la: Lag for the difference.
• center: Center the result in the response using Missing values.

Returns

Laged differences Vector or Array of a given order.

Examples

julia> x = [1,2,3,4,5];
julia> d(x)
d(x)
4-element Vector{Int64}:
1
1
1
1

julia> d(x,2)
3-element Vector{Int64}:
0
0
0

julia> d(x,1,2)
3-element Vector{Int64}:
2
2
2

julia> x = reshape(collect(1:20),10,2);

julia> d(x,2,2)
6×2 Matrix{Int64}:
0  0
0  0
0  0
0  0
0  0
0  0

julia> d(d(x,1,2),1,2) == d(x,2,2)

## forecast

Forecast for models

Forecast.forecastFunction

Package: Forecast

forecast(xar, n; levels = (0.8,.95))

Forecast a univariate or multivariate autoregressive model.

The forecasting follows the model:

$$$Xt = \Phi_0 + \sum_{i=1}^p \Phi_i \cdot X_{t-i} + E$$$

Arguments

xar AR struct coming from the ar function. n Number of time periods to be forecasted. alpha Prediction intervals levels; its default value is (0.8, 0.95) fixMean Fixes the mean in the forecast with a DataFrame which first column is a timestamp type and missing values indicate values to be estimated. Default value is nothing. fixΣ2 fixes Σ2 values in the forecast

Returns

A FORECAST struct

## iboxcox

Autoregressive simulation

Forecast.iboxcoxFunction

Package: Forecast

iboxcox(x::Vector, λ::Float64)
iboxcox(x::Vector, λ::Vector)

Compute the inverse transformation of a Box-Cox power transformation given λ.

Arguments

• x: Vector with a boxcox tranformation to be inverted.
• λ: Exponent for the inverse tranformation.

Returns

A vector with witht the inverse transformation of x given λ.

Reference

Box, G. E. P. and Cox, D. R. (1964). An analysis of transformations, Journal of the Royal Statistical Society, Series B, 26, 211-252. A

Examples

julia> x = rand(100)
julia> bc = boxcox(x)
julia> iboxcox(bc[:x],bc[:λ]) ≈ x

julia> x = rand(100) .- 0.5
julia> bc = boxcox(x)
julia> iboxcox(bc[:x],bc[:λ]) ≈ x

## loess

Locally Estimated Scatterplot Smoothing (LOESS)

Forecast.loessFunction

Package: Forecast

loess(xv, yv;
d = 2,
q = Int64(round(3/4*length(xv))),
rho = repeat([1.0],inner=length(xv)),
predict = xv)

Smooth a vector of observations using locally weighted regressions.

Although loess can be used to smooth observations for any given number of independent variables, this implementation is univariate. The speed of loess can be greatly increased by using fast aproximations for the linear fitting calculations, however this implementation calculates only exact results.

The loess functionality and nomenclature follows the descriptions in:

"STL: A Seasonal, Trend Decomposition Procedure Based on Loess" Robert B. Cleveland, William S. Cleveland, Jean E. McRae, and Irma Terpenning. Journal of Official Statistics Vol. 6. No. 1, 1990, pp. 3-73 (c) Statistics Sweden.

Arguments

• xv: Observations' support.
• yv: Observation values.
• d: Degree of the linear fit, it accepts values 1 or 2.
• q: As q increases loess becomes smoother, when q tends to infinity loess tends to an ordinary least square poynomial fit of degree d. It defaults to the rounding of 3/4 of xv's length.
• rho: Weights expressing the reliability of the observations (e.g. if yi had variances σ^2*ki where ki where known, the rhoi could be 1/ki). It defaults to 1.0.
• predict: Vector containing the real values to be predicted, by default predicts xv.

Returns

The loess values for the values contained in predict.

Examples

julia> loess(rand(5), rand(5); predict=rand(10))
10-element Array{Float64,1}:
[...]

## p

Inverse lagged differences of a given order

Forecast.pFunction

Package: Forecast

function p(dx, x0)

Return reverse lagged differences of a given order for Vector, Array and DataFrame.

Arguments

• dx: Array or DataFrame of data.
• x0: Initial constants the reverse difference. The default value represents an integration of order one and lag one with initial values at zero. The format for the initial values is Array{Real,3}(order, variable, lag)"

Returns

Lagged differences Vector or Array of a given order.

Examples


# Order two with Lag two
julia> x = repeat(1:2,30);
julia> dx = d(x,2,2);
julia> x0 = zeros(2,1,2); # lag 2, 1 variable, order 1
julia> x0[1,:,:] = collect(1:2);
julia> p(dx,x0) ≈ x
true

# Calculation of π
julia> x = 0:0.001:1;
julia> y = sqrt.(1 .- x.^2);
julia> isapprox(4*p(y)[end]/1000 , π, atol = 0.01)
true

## splot

Forecast.splotFunction

Package: Forecast

splot(x, labels)

Plot a seasonal plot of x considering the parameter labels

Arguments

• x: regular timed observations
• labels: This parameter accepts Integer, String and Vector values. When an Integer the labels are 1:labels, when a Vector the labels are specified within and when a String it accepts values "month", "day" and "quarter" expecting the first value of x to fall in "Jan", "Mon" or "Q1" unless x is a DataFrame in which case it is treated as a Time Series where the first Date typed column and value columns ares considered, observations are then automatically ordered either by "month", "day" or "quarter" and labels may be use to rename the default values.

Returns

Sesonal plot

Examples

julia> splot(rand(120),"month")
julia> splot(rand(120),"quarter")
julia> splot(rand(120),"day")

## stl

Seasonal and Trend decomposition based on Loess

Forecast.stlFunction

Package: Forecast

stl(Yv, np; robust=false,
nl=nextodd(np),
ns=10*length(Yv)+1,
nt=nextodd(1.5*np/(1-1.5/ns)),
ni=robust ? 1 : 2,
no=0,
spm=false,
qsmp=max(div(np,7),2),
cth = 0.01,
timestamp = nothing,
verbose=false)

Decompose a time series into trend, seasonal, and remainder components.

"STL has a simple design that consists of a sequence of applications of the loess smoother; the simplicity allows analysis of the properties of the procedure and allows fast computation, even for very long time series and large amounts of trend and seasonal smoothing. Other features of STL are specification of amounts of seasonal and trend smoothing that range, in a nearly continous way, from very small amount of smoothing to a very large amount; robust estimates of the trend and seasonal components that are not distorted by aberrant behavior in the data; specification of the period of the seasonal component to any intenger multiple of the time sampling interval greater than one; and the ability to decompose time series with missing values."*

All default values are chosen following the recommendations of the original paper when those were recommended. ns is recommended to be chosen of the basis of knowledge of the time series and on the basis of diagnostic methods; it must nonethelessbe always odd and at least 7. A default value is not advised on the original paper, instead the same default value used in the stl implementation in R in usere here.

for no the authors advise 5 ("safe value") or 10 ("near certainty of convergence") cycles or a convergence criterion when robustness is required, in this case when robust is true computations stop when convergence is achieved in trend and seasonality.

for qsmp the authors do not adivise a default but they use a value close to div(np,7).

Arguments

• np: Seasonality.
• robust: Robust stl.
• nl: Smoothing parameter of the low-pass filter.
• ns: Smoothing parameter for the seasonal component.
• nt: Smoothing parameter for the trend decomposition.
• ni: Number of inner loop cycles.
• no: Number of outer loop cycles.
• spm: Seasonal post-smoothing.
• qsmp: Loess q window for Seasonal post-smoothing.
• cth: Corvengence threshold for Seasonal and Trend.
• timestamp: Timestamp to be used other than the default.
• verbose: If true shows updates for the Seasonal and Trend convergence.

Returns

An STL object with the seasonal, trend and remainder components.

• STL: A Seasonal, Trend Decomposition Procedure Based on Loess" Robert B. Cleveland, William S. Cleveland, Jean E. McRae, and Irma Terpenning. Journal of Official Statistics Vol. 6. No. 1, 1990, pp. 3-73 (c) Statistics Sweden.

Examples

julia> stl_co2 = stl(co2(),365; robust=true, spm=true)
[ Info: Dataset used in Cleveland et al. paper
[ Info: Corvengence achieved (< 0.01); Stopping computation...
STL Object: stl(Yn, np=365; nl=365, ns=46091, nt=549, ni=1, no=0, spm=true, qsmp=52)

julia> plot(stl_co2)

## summarize

Statistical summary

Forecast.summarizeFunction

Package: Forecast

summarize(x; varnames = nothing)

Return statistical summary for x

The values returned are dividen in three sections, the first one shows Minimum, 1st Quantile, Median, Mean, 3rd Quantile, Maxixum and the p-value for the Jarque-Bera Normality Test. The second one show the first four moment; Mean, Variance, Skewness and Kurtosis, an finally a summary with the different types contained in the Array.

Arguments

• x: Array or DataFrame of data.
• varnames: Names for the columns to be summarized, it defaults to automatic naming or the existing names in when a DataFrame.

Returns

A SUMMARIZE struct

Examples

julia> summarize(rand(100,3); varnames = ["a","b","c"])
┌──────────┬────────────┬──────────┬──────────┬──────────┬──────────┬──────────┬───────────┐
│ Variable │        Min │       1Q │   Median │     Mean │       3Q │      Max │ H0 Normal │
├──────────┼────────────┼──────────┼──────────┼──────────┼──────────┼──────────┼───────────┤
│        a │ 0.00520465 │ 0.205712 │ 0.462199 │ 0.465784 │   0.6913 │  0.97946 │ 0.0593599 │
│        b │ 0.00218787 │ 0.247344 │ 0.485465 │ 0.498587 │ 0.723371 │ 0.985226 │ 0.0562301 │
│        c │  0.0244256 │ 0.247598 │ 0.530821 │ 0.498689 │ 0.722731 │ 0.967952 │ 0.0356495 │
└──────────┴────────────┴──────────┴──────────┴──────────┴──────────┴──────────┴───────────┘
┌──────────┬──────────┬───────────┬───────────┬───────────┐
│ Variable │     Mean │  Variance │  Skewness │  Kurtosis │
├──────────┼──────────┼───────────┼───────────┼───────────┤
│        a │ 0.465784 │ 0.0823949 │ 0.0823949 │ 0.0823949 │
│        b │ 0.498587 │ 0.0854883 │ 0.0854883 │ 0.0854883 │
│        c │ 0.498689 │ 0.0790597 │ 0.0790597 │ 0.0790597 │
└──────────┴──────────┴───────────┴───────────┴───────────┘
┌──────────┬─────────┐
│ Variable │ Float64 │
├──────────┼─────────┤
│        a │     100 │
│        b │     100 │
│        c │     100 │
└──────────┴─────────┘