| Title: | Generating Time Series with Diverse and Controllable Characteristics |
|---|---|
| Description: | Generates synthetic time series based on various univariate time series models including MAR and ARIMA processes. Kang, Y., Hyndman, R.J., Li, F.(2020) <doi:10.1002/sam.11461>. |
| Authors: | Yanfei Kang [aut] (ORCID: <https://orcid.org/0000-0001-8769-6650>), Feng Li [aut, cre] (ORCID: <https://orcid.org/0000-0002-4248-9778>), Rob Hyndman [aut] (ORCID: <https://orcid.org/0000-0002-2140-5352>), Mitchell O'Hara-Wild [ctb] (ORCID: <https://orcid.org/0000-0001-6729-7695>), Bocong Zhao [ctb] (ORCID: <https://orcid.org/0000-0001-8434-9047>) |
| Maintainer: | Feng Li <[email protected]> |
| License: | GPL-3 |
| Version: | 1.9 |
| Built: | 2026-10-15 17:22:15 UTC |
| Source: | https://github.com/ykang/gratis |
Construct a Gaussian ARIMA model that can be used with
simulate.gratis_arima() or generate.Arima().
Omitted orders and coefficients are inferred where possible or randomly
selected from the supported parameter space. Construction does not simulate
observations or store a seed for later simulations.
arima_model( frequency = 1, p = NULL, d = NULL, q = NULL, P = NULL, D = NULL, Q = NULL, constant = NULL, phi = NULL, theta = NULL, Phi = NULL, Theta = NULL, sigma = NULL )arima_model( frequency = 1, p = NULL, d = NULL, q = NULL, P = NULL, D = NULL, Q = NULL, constant = NULL, phi = NULL, theta = NULL, Phi = NULL, Theta = NULL, sigma = NULL )
frequency |
Positive integer seasonal period, for example 12 for monthly data. A value of 1 denotes a non-seasonal model. |
p, q
|
Non-negative integer non-seasonal AR and MA orders. If omitted,
inferred from supplied |
d |
Non-negative integer ordinary difference order, with |
P, Q
|
Non-negative integer seasonal AR and MA orders. If omitted,
inferred from supplied |
D |
Non-negative integer seasonal difference order. Seasonal arguments
require |
constant |
Mean when |
phi |
Finite numeric vector of length |
theta |
Finite numeric vector of length |
Phi |
Finite numeric vector of length |
Theta |
Finite numeric vector of length |
sigma |
The standard deviation of the noise. Its squared variance must lie in the positive normal floating-point range, in both R and Python. |
When orders are omitted, p and q are sampled from
, P and Q from ,
d from , and D from , with the
restriction . If constant is omitted, it is sampled
from unless , in which case it is set to zero.
AR and MA parameters are sampled so the stationary and invertible parts of
the process are valid, and sigma is sampled from .
Above order two, random AR polynomials allow every possible count of real
roots. This has full support, but is not uniform over coefficient space.
A gratis_arima object inheriting from Arima. Its
simulation method uses scaled innovations and preserves all seasonal
coefficients, including coefficients whose sum is zero. Models fitted
separately with forecast retain their own simulation method.
Rob J Hyndman
simulate.gratis_arima for initialization and controlled
innovations; generate.Arima for batches of paths.
# An AR(2) model with random parameters model1 <- arima_model(p = 2, d = 0, q = 0) # An AR(2) model with specific parameters model2 <- arima_model(p = 2, d = 0, q = 0, phi = c(1.34, -0.64), sigma = 15) # Seasonal ARIMA model with randomly selected parameters model3 <- arima_model(frequency = 4) # Simulate from each model and plot the results plot(simulate(model1, 100)) plot(simulate(model2, 100)) plot(simulate(model3, 100))# An AR(2) model with random parameters model1 <- arima_model(p = 2, d = 0, q = 0) # An AR(2) model with specific parameters model2 <- arima_model(p = 2, d = 0, q = 0, phi = c(1.34, -0.64), sigma = 15) # Seasonal ARIMA model with randomly selected parameters model3 <- arima_model(frequency = 4) # Simulate from each model and plot the results plot(simulate(model1, 100)) plot(simulate(model2, 100)) plot(simulate(model3, 100))
Construct an ETS state space model that can be used with
simulate.ets() or generate.ets().
Any omitted argument is randomly selected from the supported parameter space.
ets_model( frequency = 1, error = NULL, trend = NULL, seasonal = NULL, alpha = NULL, beta = NULL, gamma = NULL, phi = NULL, level = NULL, slope = NULL, season = NULL, damped = NULL, sigma = NULL )ets_model( frequency = 1, error = NULL, trend = NULL, seasonal = NULL, alpha = NULL, beta = NULL, gamma = NULL, phi = NULL, level = NULL, slope = NULL, season = NULL, damped = NULL, sigma = NULL )
frequency |
Positive integer seasonal period, for example 12 for monthly data. Seasonal models require a value greater than 1. |
error |
Character string specifying the error component: |
trend |
Character string specifying the trend component: |
seasonal |
Character string specifying the seasonal component:
|
alpha |
Level smoothing parameter, strictly between 0 and 1. |
beta |
Trend smoothing parameter in |
gamma |
Seasonal smoothing parameter in |
phi |
Damping parameter in |
level |
Finite initial level |
slope |
Finite initial additive trend state |
season |
Finite numeric vector of initial seasonal states
|
damped |
Logical value indicating whether an additive trend is damped. |
sigma |
The standard deviation of the noise. Its squared variance must lie in the positive normal floating-point range, in both R and Python. It is measured on the observation scale for additive errors and is dimensionless for multiplicative errors. |
The error component is sampled from "A" and "M", the trend
component from "N" and "A", and the seasonal component from
"N", "A", and "M" when frequency > 1. Smoothing
parameters are sampled until they satisfy the ETS admissibility conditions.
The innovation variance is sampled from for additive errors and
from for multiplicative errors. Initial states are sampled
from ranges appropriate to the selected components.
Omitted smoothing parameters are resampled after rejection, with a maximum
of 10000 attempts. Fixed parameters must satisfy the usual smoothing bounds:
, ,
, and .
Multiplicative seasonal factors are positive and sampled factors are
normalized to have mean one.
Simulation starts from the supplied initial states without an automatic burn-in. Multiplicative innovations are clipped below at -1 by the forecast simulator, matching Python's convention. Admissibility and positive initial states do not guarantee positive or finite values for every simulated path.
An ets object compatible with the forecast package's
simulation methods.
Rob J Hyndman
# An ETS(A,A,N) model with random parameters model1 <- ets_model(error = "A", trend = "A", seasonal = "N") # An ETS(A,A,N) model with specific parameters model2 <- ets_model( error = "A", trend = "A", seasonal = "N", alpha = 0.3, beta = 0.2, level = 0, slope = 1, sigma = 2 ) # A quarterly seasonal ETS model with random admissible parameters model3 <- ets_model(error = "A", trend = "N", seasonal = "A", frequency = 4) # Simulate from each model and plot the results plot(simulate(model1, 100)) plot(simulate(model2, 100)) plot(simulate(model3, 100))# An ETS(A,A,N) model with random parameters model1 <- ets_model(error = "A", trend = "A", seasonal = "N") # An ETS(A,A,N) model with specific parameters model2 <- ets_model( error = "A", trend = "A", seasonal = "N", alpha = 0.3, beta = 0.2, level = 0, slope = 1, sigma = 2 ) # A quarterly seasonal ETS model with random admissible parameters model3 <- ets_model(error = "A", trend = "N", seasonal = "A", frequency = 4) # Simulate from each model and plot the results plot(simulate(model1, 100)) plot(simulate(model2, 100)) plot(simulate(model3, 100))
This function is deprecated. Use mar_model() with
generate.mar() or simulate.mar() instead.
generate_msts( seasonal.periods = c(7, 365), n = 800, nComp = NULL, output_format = "list" )generate_msts( seasonal.periods = c(7, 365), n = 800, nComp = NULL, output_format = "list" )
seasonal.periods |
Numeric vector of seasonal periods. |
n |
Length of the generated series. |
nComp |
Number of mixture components. If |
output_format |
Output format: |
A multiple-seasonal time series when output_format = "list",
or a tsibble when output_format = "tsibble".
x <- generate_msts(seasonal.periods = c(7, 365), n = 800, nComp = 2, output_format = "list") forecast::autoplot(x)x <- generate_msts(seasonal.periods = c(7, 365), n = 800, nComp = 2, output_format = "list") forecast::autoplot(x)
This function is deprecated. Use mar_model() with
generate.mar() or simulate.mar() instead.
generate_ts(n.ts = 1, freq = 1, nComp = NULL, n = 120, output_format = "list")generate_ts(n.ts = 1, freq = 1, nComp = NULL, n = 120, output_format = "list")
n.ts |
Number of time series to generate. |
freq |
Seasonal period of the generated series. |
nComp |
Number of mixture components. If |
n |
Length of each generated series. |
output_format |
Output format: |
When output_format = "list", a list containing generated time
series and the parameters used for each series. When
output_format = "tsibble", a list of tsibbles.
Yanfei Kang and Feng Li
Wong, CS & WK Li (2000).
x <- generate_ts(n.ts = 2, freq = 12, nComp = 2, n = 120) x$N1$pars forecast::autoplot(x$N1$x)x <- generate_ts(n.ts = 2, freq = 12, nComp = 2, n = 120) x$N1$pars forecast::autoplot(x$N1$x)
This function is deprecated. Use generate_target() instead.
generate_ts_with_target( n, ts.length, freq, seasonal, features, selected.features, target, parallel = TRUE, output_format = "list" )generate_ts_with_target( n, ts.length, freq, seasonal, features, selected.features, target, parallel = TRUE, output_format = "list" )
n |
Number of time series to generate. |
ts.length |
Length of each generated time series. |
freq |
Seasonal frequency, or seasonal periods for multiple-seasonal data. |
seasonal |
Integer seasonality flag: 0 for non-seasonal data, 1 for single-seasonal data, and 2 for multiple-seasonal data. |
features |
Character vector of feature function names passed to
|
selected.features |
Character vector naming the features to match. |
target |
Numeric vector of target feature values in the same order as
|
parallel |
Logical value or parallel backend specification indicating whether the genetic algorithm should evaluate candidates in parallel. |
output_format |
Output format: |
A ts or msts object containing the generated series,
or a tsibble when output_format = "tsibble". The historical
"list" option returns a time-series object, not an R list.
Yanfei Kang
generate_target, simulate_target
## Not run: library(tsfeatures) x <- generate_ts_with_target( n = 1, ts.length = 60, freq = 1, seasonal = 0, features = c("entropy", "stl_features"), selected.features = c("entropy", "trend"), target = c(0.6, 0.9), parallel = FALSE ) forecast::autoplot(x) ## End(Not run)## Not run: library(tsfeatures) x <- generate_ts_with_target( n = 1, ts.length = 60, freq = 1, seasonal = 0, features = c("entropy", "stl_features"), selected.features = c("entropy", "trend"), target = c(0.6, 0.9), parallel = FALSE ) forecast::autoplot(x) ## End(Not run)
Generate one or more synthetic time series from a fitted or specified model.
Methods are provided for mar_model() objects, ETS objects from
ets_model(), and ARIMA objects from arima_model().
Each series is produced by repeatedly calling the corresponding
simulate() method.
Automatic burn-in for models created by arima_model() is
calculated once per batch. This does not change the simulation behavior of
separately fitted forecast models.
## S3 method for class 'mar' generate(x, length = 100, nseries = 10, ..., seed = NULL) ## S3 method for class 'ets' generate(x, length = 100, nseries = 10, ..., seed = NULL) ## S3 method for class 'Arima' generate(x, length = 100, nseries = 10, ..., seed = NULL)## S3 method for class 'mar' generate(x, length = 100, nseries = 10, ..., seed = NULL) ## S3 method for class 'ets' generate(x, length = 100, nseries = 10, ..., seed = NULL) ## S3 method for class 'Arima' generate(x, length = 100, nseries = 10, ..., seed = NULL)
x |
A model object of class |
length |
Positive integer output length of each series, excluding burn-in. |
nseries |
Positive integer number of series to generate. |
... |
Other arguments passed to the relevant |
seed |
Optional seed set once for the whole batch. Successive series
use successive random draws, and the previous RNG state is restored after
generation. The default, |
The generated series are returned as a tsibble. The index is inferred from the model frequency or seasonal periods where possible, with special handling for common weekly, hourly, half-hourly, quarter-hourly, and minute data.
A tsibble containing the generated values. For multiple series the
output has length * nseries rows and includes a key column identifying
each series. Unlike the Python API, the result contains calendar or seasonal
index information rather than being an unlabelled numeric matrix.
Rob J Hyndman
Feng Li, Mattias Villani, and Robert Kohn. (2010). Flexible Modeling of Conditional Distributions using Smooth Mixtures of Asymmetric Student T Densities, Journal of Statistical Planning and Inference, 140(12), pp. 3638-3654.
mar_model, arima_model,
ets_model, simulate.mar
# MAR model with constant variances phi <- cbind(c(0.8, 0), c(0.6, 0.3)) weights <- c(0.8, 0.2) model1 <- mar_model(phi = phi, sigmas = c(1, 2), weights = weights) generate(model1, nseries = 5) # MAR model for hourly data with daily and weekly periods hourly_model <- mar_model(seasonal_periods = c(24, 24*7)) generate(hourly_model, length = 24 * 7, nseries = 2) # ARIMA and ETS models also work generate(arima_model(p = 1, d = 0, q = 0, phi = 0.5), length = 20, nseries = 2) generate(ets_model(error = "A", trend = "N", seasonal = "N"), length = 20, nseries = 2)# MAR model with constant variances phi <- cbind(c(0.8, 0), c(0.6, 0.3)) weights <- c(0.8, 0.2) model1 <- mar_model(phi = phi, sigmas = c(1, 2), weights = weights) generate(model1, nseries = 5) # MAR model for hourly data with daily and weekly periods hourly_model <- mar_model(seasonal_periods = c(24, 24*7)) generate(hourly_model, length = 24 * 7, nseries = 2) # ARIMA and ETS models also work generate(arima_model(p = 1, d = 0, q = 0, phi = 0.5), length = 20, nseries = 2) generate(ets_model(error = "A", trend = "N", seasonal = "N"), length = 20, nseries = 2)
Construct a mixture autoregressive (MAR) model made up of Gaussian
ARIMA components. The resulting mar object can
be passed to simulate.mar() to simulate one series or to
generate.mar() to generate a tsibble of several series.
mar_model( k = NULL, p = NULL, d = NULL, phi = NULL, P = NULL, D = NULL, Phi = NULL, constants = NULL, sigmas = NULL, weights = NULL, seasonal_periods = 1L )mar_model( k = NULL, p = NULL, d = NULL, phi = NULL, P = NULL, D = NULL, Phi = NULL, constants = NULL, sigmas = NULL, weights = NULL, seasonal_periods = 1L )
k |
Positive integer number of mixture components. |
p |
Non-negative integer scalar or vector of length |
d |
Non-negative integer scalar or vector of length |
phi |
Numeric matrix of non-seasonal AR parameters. Column |
P |
Non-negative integer scalar or vector of length |
D |
Non-negative integer scalar or vector of length |
Phi |
Numeric matrix of seasonal AR parameters. Column |
constants |
Numeric vector of length |
sigmas |
Positive innovation variances of length |
weights |
Non-negative finite numeric vector of length |
seasonal_periods |
Positive integer seasonal period applied to every
component, or
a numeric vector of length |
Component has the form
and is selected independently at each time with probability .
Every component conditions on the same generated past; components are not
independently generated paths that are subsequently averaged. Here is the
backshift operator, is the seasonal period, is a
standard normal variate, and and are the
non-seasonal and seasonal AR coefficient sums, with seasonal coefficients
multiplying lags .
Any missing model argument is randomly selected. Randomly selected
non-seasonal AR orders are sampled from ,
non-seasonal differences from , seasonal AR orders from
, and seasonal differences from . AR parameters
are sampled from the stationary region, constants from , sigmas
from , and mixture weights from before normalization.
If k is omitted, the number of components is sampled from
, unless it can be inferred from another argument.
Stationary component AR polynomials do not guarantee a stationary mixture.
Integrated components are also allowed. Simulation uses zero initial states
and a fixed burn-in by default; near-unit-root models may need a substantially
longer n.start in simulate.mar().
An object of class mar. The object stores the component orders,
coefficients, constants, sigmas, normalized weights, seasonal periods, and
the expanded AR recursion coefficients used by simulate.mar().
Rob J Hyndman
simulate.mar, generate.mar,
pi_coefficients
# Quarterly MAR model with randomly selected parameters model1 <- mar_model(seasonal_periods = 4) # Daily MAR model with randomly selected parameters model2 <- mar_model(seasonal_periods = c(7, 365)) # MAR model with constant variances and user-specified coefficients phi <- cbind(c(0.8, 0), c(0.6, 0.3)) weights <- c(0.8, 0.2) model3 <- mar_model(phi = phi, d = 0, sigmas = c(1, 2), weights = weights) # MAR model with heteroskedastic errors if (requireNamespace("fGarch", quietly = TRUE)) { sigmas_spec <- list( fGarch::garchSpec(model = list(alpha = c(0.05, 0.06))), fGarch::garchSpec(model = list(alpha = c(0.05, 0.05))) ) model4 <- mar_model(phi = phi, sigmas = sigmas_spec, weights = weights) }# Quarterly MAR model with randomly selected parameters model1 <- mar_model(seasonal_periods = 4) # Daily MAR model with randomly selected parameters model2 <- mar_model(seasonal_periods = c(7, 365)) # MAR model with constant variances and user-specified coefficients phi <- cbind(c(0.8, 0), c(0.6, 0.3)) weights <- c(0.8, 0.2) model3 <- mar_model(phi = phi, d = 0, sigmas = c(1, 2), weights = weights) # MAR model with heteroskedastic errors if (requireNamespace("fGarch", quietly = TRUE)) { sigmas_spec <- list( fGarch::garchSpec(model = list(alpha = c(0.05, 0.06))), fGarch::garchSpec(model = list(alpha = c(0.05, 0.05))) ) model4 <- mar_model(phi = phi, sigmas = sigmas_spec, weights = weights) }
Convert SARIMA coefficients into the equivalent infinite-order AR recursion
coefficients, truncated after the last coefficient whose absolute value is
greater than tol. These coefficients are used internally by
mar_model() and are also exported for users who need the same
conversion.
pi_coefficients( ar = 0, d = 0L, ma = 0, sar = 0, D = 0L, sma = 0, m = 1L, tol = 1e-07, n_terms = 500L )pi_coefficients( ar = 0, d = 0L, ma = 0, sar = 0, D = 0L, sma = 0, m = 1L, tol = 1e-07, n_terms = 500L )
ar, ma
|
Finite numeric vectors of non-seasonal AR and MA coefficients, excluding the leading 1 of each lag polynomial. |
d, D
|
Non-negative integer ordinary and seasonal difference orders.
Seasonal differencing is ignored when |
sar, sma
|
Finite numeric vectors of seasonal AR and MA coefficients.
Ignored when |
m |
Positive integer seasonal period. A value of 1 is non-seasonal. |
tol |
Non-negative finite truncation tolerance. Coefficients are returned through
the last position whose absolute value exceeds |
n_terms |
Lag limit for an infinite AR approximation with MA terms.
The limit is increased to include the full AR and MA polynomial degrees.
A warning is issued if the tail has not decayed below |
AR lag polynomials use negative coefficient signs, while MA lag polynomials use positive signs. The result expands the ratio of the AR/differencing polynomial to the MA polynomial; no stationarity or invertibility is imposed.
A numeric vector of AR recursion coefficients in increasing lag
order, without an intercept or leading 1. Complete cancellation returns
numeric(0). An unconverged MA approximation issues a warning;
increase n_terms, noting that noninvertible MA terms may not converge.
Rob J Hyndman
pi_coefficients(ar = 0.8) pi_coefficients(ar = c(0.4, -0.2), d = 1) pi_coefficients(ar = 0.3, sar = 0.2, D = 1, m = 12)pi_coefficients(ar = 0.8) pi_coefficients(ar = c(0.4, -0.2), d = 1) pi_coefficients(ar = 0.3, sar = 0.2, D = 1, m = 12)
Draw random values from a finite mixture of multivariate normal
distributions, each with dimension . For univariate mixtures,
means and sigmas may be supplied as vectors.
Covariance matrices must be finite, symmetric and positive definite,
including those of zero-weight components.
rmixnorm(n, means, sigmas, weights)rmixnorm(n, means, sigmas, weights)
n |
Non-negative integer number of observations to generate. |
means |
A |
sigmas |
A |
weights |
Finite, non-negative component weights, with at least one positive value. Weights are normalized to sum to one. |
An matrix of generated data, or a numeric vector
when .
Feng Li, Central University of Finance and Economics.
Villani et al 2009.
rmixnorm_ts for autoregressive conditional means.
out <- rmixnorm( n = 1000, means = c(-5, 0, 5), sigmas = c(1, 1, 3), weights = c(0.3, 0.4, 0.3) ) hist(out, breaks = 100, freq = FALSE)out <- rmixnorm( n = 1000, means = c(-5, 0, 5), sigmas = c(1, 1, 3), weights = c(0.3, 0.4, 0.3) ) hist(out, breaks = 100, freq = FALSE)
Simulate a univariate process whose conditional distribution is a finite
mixture of Gaussian distributions. The conditional mean of each component is
an autoregressive process with its own parameter vector.
All components use the common observed past, rather than independent latent
component paths. No burn-in is removed: the first min(n, max_order)
observations are fixed at yinit, where max_order is the largest
component AR order. A shorter series consists entirely of these initial values.
rmixnorm_ts(n, means.ar.par.list, sigmas.list, weights, yinit = 0)rmixnorm_ts(n, means.ar.par.list, sigmas.list, weights, yinit = 0)
n |
Non-negative integer total path length, including initial observations. |
means.ar.par.list |
List of component AR parameter vectors. The first element of each vector is the intercept, followed by at least one lag coefficient. Orders may differ between components; values must be finite. |
sigmas.list |
List of positive, finite component variance vectors, each of
length |
weights |
Finite, non-negative component weights. At least one must be positive; weights are normalized to sum to one. |
yinit |
Finite scalar assigned to the initial observations. |
A ts object of length n, or
numeric(0) for zero length. Stationarity is not enforced.
Feng Li, Central University of Finance and Economics.
Feng Li, Mattias Villani, and Robert Kohn. (2010). Flexible Modeling of Conditional Distributions using Smooth Mixtures of Asymmetric Student T Densities, Journal of Statistical Planning and Inference, 140(12), pp. 3638-3654.
rmixnorm, mar_model, simulate.mar
if (requireNamespace("fGarch", quietly = TRUE)) { n <- 1000 means.ar.par.list <- list(c(0, 0.8), c(0, 0.6, 0.3)) sigmas.spec <- list( fGarch::garchSpec(model = list(alpha = c(0.05, 0.06)), cond.dist = "norm"), fGarch::garchSpec(model = list(alpha = c(0.05, 0.05)), cond.dist = "norm") ) sigmas.list <- lapply( lapply(sigmas.spec, fGarch::garchSim, extended = TRUE, n = n), function(x) x$sigma^2 ) weights <- c(0.8, 0.2) y <- rmixnorm_ts( n = n, means.ar.par.list = means.ar.par.list, sigmas.list = sigmas.list, weights = weights ) plot(y) }if (requireNamespace("fGarch", quietly = TRUE)) { n <- 1000 means.ar.par.list <- list(c(0, 0.8), c(0, 0.6, 0.3)) sigmas.spec <- list( fGarch::garchSpec(model = list(alpha = c(0.05, 0.06)), cond.dist = "norm"), fGarch::garchSpec(model = list(alpha = c(0.05, 0.05)), cond.dist = "norm") ) sigmas.list <- lapply( lapply(sigmas.spec, fGarch::garchSim, extended = TRUE, n = n), function(x) x$sigma^2 ) weights <- c(0.8, 0.2) y <- rmixnorm_ts( n = n, means.ar.par.list = means.ar.par.list, sigmas.list = sigmas.list, weights = weights ) plot(y) }
Search for MAR model parameters that produce time series with feature values
close to a user-specified target. simulate_target() returns one
generated series, while generate_target() repeats the search to return
several generated series in a tsibble.
simulate_target( length = 100, seasonal_periods = 1, feature_function, target, k = ifelse(length(seasonal_periods) == 1, 3, length(seasonal_periods)), tolerance = 0.05, trace = FALSE, parallel = FALSE ) generate_target( length = 100, nseries = 10, seasonal_periods = 1, feature_function, target, k = ifelse(length(seasonal_periods) == 1, 3, length(seasonal_periods)), tolerance = 0.05, trace = FALSE, parallel = FALSE )simulate_target( length = 100, seasonal_periods = 1, feature_function, target, k = ifelse(length(seasonal_periods) == 1, 3, length(seasonal_periods)), tolerance = 0.05, trace = FALSE, parallel = FALSE ) generate_target( length = 100, nseries = 10, seasonal_periods = 1, feature_function, target, k = ifelse(length(seasonal_periods) == 1, 3, length(seasonal_periods)), tolerance = 0.05, trace = FALSE, parallel = FALSE )
length |
Positive integer output length of each generated series. |
seasonal_periods |
Positive integer seasonal period, applied to every
component, or a vector of length |
feature_function |
Function that accepts a candidate time series and returns one numeric value per target feature. It should be deterministic for reproducible scores. Nonfinite values reject a candidate; errors raised by the function propagate. Callbacks used in parallel must be available to the workers along with their dependencies. |
target |
Numeric vector of target feature values. It must have the same
length and order as the vector returned by |
k |
Number of MAR components to use. The default is 3 for single-seasonal or non-seasonal data, and the number of seasonal periods for multiple-seasonal data. |
tolerance |
Non-negative finite mean absolute feature-error tolerance. Reaching this value stops the search. Success is not guaranteed; a miss returns the best series with a warning reporting its error. |
trace |
Logical value indicating whether to show genetic algorithm progress. |
parallel |
Logical value or parallel backend specification passed to the
genetic algorithm. Use |
nseries |
Positive integer number of separate target searches. Searches
are repeated sequentially, with successive draws from the current RNG
stream; |
A genetic algorithm evaluates candidate MAR parameter vectors by simulating a
series, scaling it, computing feature_function(), and comparing those
features to target. Because each candidate series is scaled before
feature evaluation, the target features should not depend on the absolute
scale of the series.
Finite nonconstant series are centered and sample-standardized using
overflow-safe scaling; exactly constant series are left unchanged.
Mixture weights are the spacings between sorted breakpoints in ,
allowing the full simplex, including zero-weight components. If tolerance
is not reached, the best series is returned with a warning giving its mean
absolute feature error. Callback errors and incompatible feature lengths
are reported as errors; nonfinite candidate paths or features are rejected.
The best final population member is selected using its cached fitness and
series; generation histories are not retained or callbacks reevaluated.
simulate_target() returns a msts
object of length length. generate_target() returns a tsibble
containing nseries generated series. Returned values are on the
standardized scale used for feature evaluation, except that exactly constant
candidates are unchanged. Neither function returns fitted MAR parameters.
A search with no finite valid candidate stops with an error.
Yanfei Kang and Rob J Hyndman
## Not run: set.seed(1) library(tsfeatures) my_features <- function(y) { c(entropy(y), acf = acf(y, plot = FALSE)$acf[2:3, 1, 1]) } # Simulate a ts with specified target features y <- simulate_target( length = 60, feature_function = my_features, target = c(0.5, 0.9, 0.8) ) my_features(y) plot(y) # Generate a tsibble with specified target features df <- generate_target( length = 60, feature_function = my_features, target = c(0.5, 0.9, 0.8) ) df %>% as_tibble() %>% group_by(key) %>% dplyr::reframe( value = my_features(value), feature=c("entropy","acf1", "acf2") ) autoplot(df) # Simulate time series similar to an existing series my_features <- function(y) { c(stl_features(y)[c("trend", "seasonal_strength", "peak", "trough")]) } y <- simulate_target( length = length(USAccDeaths), seasonal_periods = frequency(USAccDeaths), feature_function = my_features, target = my_features(USAccDeaths) ) tsp(y) <- tsp(USAccDeaths) plot(cbind(USAccDeaths, y)) cbind(my_features(USAccDeaths), my_features(y)) ## End(Not run)## Not run: set.seed(1) library(tsfeatures) my_features <- function(y) { c(entropy(y), acf = acf(y, plot = FALSE)$acf[2:3, 1, 1]) } # Simulate a ts with specified target features y <- simulate_target( length = 60, feature_function = my_features, target = c(0.5, 0.9, 0.8) ) my_features(y) plot(y) # Generate a tsibble with specified target features df <- generate_target( length = 60, feature_function = my_features, target = c(0.5, 0.9, 0.8) ) df %>% as_tibble() %>% group_by(key) %>% dplyr::reframe( value = my_features(value), feature=c("entropy","acf1", "acf2") ) autoplot(df) # Simulate time series similar to an existing series my_features <- function(y) { c(stl_features(y)[c("trend", "seasonal_strength", "peak", "trough")]) } y <- simulate_target( length = length(USAccDeaths), seasonal_periods = frequency(USAccDeaths), feature_function = my_features, target = my_features(USAccDeaths) ) tsp(y) <- tsp(USAccDeaths) plot(cbind(USAccDeaths, y)) cbind(my_features(USAccDeaths), my_features(y)) ## End(Not run)
Simulate the stationary ARMA part from zero states, discard burn-in, and
then apply differencing inverses and the model's mean or linear drift.
All random innovations, including burn-in, have standard deviation
sqrt(object$sigma2). This method applies only to models constructed
by arima_model(), not to fitted forecast models.
## S3 method for class 'gratis_arima' simulate( object, nsim = 100, seed = NULL, n.start = NULL, innov = NULL, start.innov = NULL, ... )## S3 method for class 'gratis_arima' simulate( object, nsim = 100, seed = NULL, n.start = NULL, innov = NULL, start.innov = NULL, ... )
object |
A model created by |
nsim |
Non-negative integer output length, excluding burn-in. Supplied
|
seed |
Optional integer random seed. A supplied seed temporarily sets
the RNG state, restoring the previous state or its absence afterwards.
|
n.start |
Non-negative integer burn-in length. |
innov |
Optional finite numeric vector of output-period innovations,
already on the model's noise scale. Values are not multiplied by
|
start.innov |
Optional finite numeric vector of burn-in innovations.
Its length determines |
... |
Other arguments, not supported. |
A ts object with the model's frequency and the
requested output length, or numeric(0) for zero output length.
For an AR model, impulse-response windows double from a power of two covering
at least 64 steps, 2 * (AR order + MA order + 1), and twelve time
constants of the slowest pole. Burn-in is half the first window whose latter
half contains at most 1e-8 of its energy. Repeated and seasonal poles
and near AR-MA cancellation are included. A pure MA model uses its expanded
MA order as burn-in. The same rule is used in Python.
This is a numerical tail estimate, not exact stationary initialization.
Searches exceeding 2^22 steps stop with an error requesting an explicit
n.start. Differencing inverses and the mean or drift are applied only
after the stationary ARMA burn-in has been discarded.
model <- arima_model(p = 1, d = 0, q = 0, phi = 0.99, constant = 0, sigma = 0.01) simulate(model, nsim = 20, seed = 1) # Supplied innovations are already scaled; zero burn-in gives zero prehistory. impulse_model <- arima_model(p = 1, d = 0, q = 0, phi = 0.5, constant = 0, sigma = 1) as.numeric(simulate(impulse_model, innov = c(1, 0, 0), n.start = 0))model <- arima_model(p = 1, d = 0, q = 0, phi = 0.99, constant = 0, sigma = 0.01) simulate(model, nsim = 20, seed = 1) # Supplied innovations are already scaled; zero burn-in gives zero prehistory. impulse_model <- arima_model(p = 1, d = 0, q = 0, phi = 0.5, constant = 0, sigma = 1) as.numeric(simulate(impulse_model, innov = c(1, 0, 0), n.start = 0))
Simulate one random sample path from a mixture of Gaussian autoregressive
components created by mar_model(). At each time point, a
component is sampled according to the model weights, that component's
conditional mean and innovation variance are used, and the resulting series
is returned after discarding a burn-in period.
## S3 method for class 'mar' simulate(object, nsim = 100, seed = NULL, n.start = 100, ...)## S3 method for class 'mar' simulate(object, nsim = 100, seed = NULL, n.start = 100, ...)
object |
A |
nsim |
Non-negative integer output length, excluding burn-in. |
seed |
Optional integer passed to |
n.start |
Non-negative integer burn-in length, discarded before returning the simulated series. The default of 100 does not guarantee convergence to a stationary distribution, particularly for near-unit-root models. Stationary components do not by themselves guarantee mixture stability. |
... |
Other arguments, not currently used. |
A msts object of length nsim. For
single-seasonal or non-seasonal models this also behaves like a base
ts object. Zero output length returns numeric(0).
Values are not centered or standardized.
Rob J Hyndman
Feng Li, Mattias Villani, and Robert Kohn. (2010). Flexible Modeling of Conditional Distributions using Smooth Mixtures of Asymmetric Student T Densities, Journal of Statistical Planning and Inference, 140(12), pp. 3638-3654.
# MAR model with constant variances phi <- cbind(c(0.8, 0), c(0.6, 0.3)) weights <- c(0.8, 0.2) model1 <- mar_model(phi = phi, sigmas = c(1, 2), weights = weights) y <- simulate(model1, 100) plot(y) # MAR model with heteroskedastic errors if (requireNamespace("fGarch", quietly = TRUE)) { sigmas_spec <- list( fGarch::garchSpec(model = list(alpha = c(0.05, 0.06))), fGarch::garchSpec(model = list(alpha = c(0.05, 0.05))) ) model2 <- mar_model(phi = phi, sigmas = sigmas_spec, weights = weights) y <- simulate(model2, 100) plot(y) }# MAR model with constant variances phi <- cbind(c(0.8, 0), c(0.6, 0.3)) weights <- c(0.8, 0.2) model1 <- mar_model(phi = phi, sigmas = c(1, 2), weights = weights) y <- simulate(model1, 100) plot(y) # MAR model with heteroskedastic errors if (requireNamespace("fGarch", quietly = TRUE)) { sigmas_spec <- list( fGarch::garchSpec(model = list(alpha = c(0.05, 0.06))), fGarch::garchSpec(model = list(alpha = c(0.05, 0.05))) ) model2 <- mar_model(phi = phi, sigmas = sigmas_spec, weights = weights) y <- simulate(model2, 100) plot(y) }