--- title: "Forecasting time series with hmix" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Forecasting time series with hmix} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>") ``` `hmix` produces probabilistic forecasts of a univariate numeric series. It transforms the observations into changes, groups windows of changes with k-means, and fits a hidden Markov model (HMM) to the resulting cluster sequence. A future cluster is sampled according to the HMM forecast, and historical windows in that cluster provide simulated future changes. These changes are transformed back to the original scale. By default, strictly positive training data use log changes; other data use differences. The choice is made separately at each backtest origin using only the observations available at that origin. The `transform` argument can also select `"log"`, `"difference"`, or `"return"` explicitly. Log changes require strictly positive observations; percentage returns require nonzero previous values. Missing or non-finite observations are not accepted. ## Fit a forecast This example uses the included historical series. The last five observations are held out; they are not used in fitting or model selection. These data are illustrative, and the example is not an investment recommendation. ```{r forecast} library(hmix) data(dummy_set) y <- tail(dummy_set$AMZN.Close, 255) train <- head(y, -5) holdout <- tail(y, 5) fit <- hmix(train, horizon = 5, centers = 4, n_hidden = 2, n_tests = 0, n_samples = 500, seed = 42) names(fit$model) ``` `n_tests = 0` skips backtesting. Otherwise the default is 20 backtest origins, which means repeated model fits. Each forecast horizon has marginal functions: ```{r marginal} first <- fit$model$pred_funs$t1 first$qfun(c(0.1, 0.5, 0.9)) first$pfun(holdout[1]) first$rfun(5) ``` `pfun`, `qfun` and `rfun` use the empirical distribution of simulated values. `dfun` is a smoothed density estimate for visualization; it is not the derivative of the discrete empirical CDF. All forecasts are conditional on the model and are not guarantees of future outcomes. To keep the dependence between steps, draw complete paths instead of calling the marginal `rfun` independently at each step: ```{r paths} set.seed(123) paths <- fit$model$random_path(3) paths ``` Rows are paths and columns `t1`, ..., `t5` are forecast horizons. The function resamples the `n_samples` simulated paths with replacement; increasing the number requested does not generate additional distinct underlying simulations. Both fitting and sampling use R's random-number generator. Fitting sets the global seed supplied to `hmix`; set a seed before sampling when reproducible draws are needed. ## Validation and tuning Rolling-origin backtesting fits only on observations available at each origin. The returned empirical continuous ranked probability score (CRPS) measures the predictive distribution on the same scale as the series; lower is better. Columns correspond to forecast horizons. Check data length and complexity before choosing early origins, because k-means needs enough distinct windows. ```{r validate} validated <- hmix(train, horizon = 5, centers = 4, n_hidden = 2, n_tests = 3, warmup = 0.6, n_samples = 500, seed = 42) validated$error_sets$crps_set ``` Select complexity on training and validation observations, keeping a separate final holdout. The candidates are compared at the same chronological origins. This example uses a small grid to keep it quick; a larger grid is not a substitute for a representative evaluation. ```{r tune} grid <- data.frame(centers = c(3, 4), n_hidden = c(2, 2)) selection <- tune_hmix(train, horizon = 5, candidates = grid, n_tests = 2, n_samples = 500, seed = 42) selection$results[, c("centers", "n_hidden", "mean_crps", "error")] selection$best ``` Use the chosen settings to fit the training series, and evaluate forecasts against the untouched holdout and simple baselines such as the last observed value. For a meaningful assessment, repeat this on multiple independent or appropriately separated origins and relevant series. A single five-step holdout is too small to establish predictive accuracy or calibration. ## Windows and performance `stride = 1` uses overlapping training windows. A window contains `horizon` changes. The HMM advances `horizon / stride` transitions to reach the window covering the forecast period; `stride` must divide the horizon. Overlapping windows share observations, so the HMM's conditional independence assumption is an approximation. Compare alternative representations on held-out data. The compiled HMM engine is the default; `engine = "reference"` uses the HMM package's reference training algorithm. `training_window`, `n_samples`, `max_iterations`, `tolerance`, and `kmeans_starts` control cost but can change forecasts or convergence. A maximum of two `workers` may be used for backtesting or tuning; worker startup can make small jobs slower. Inspect `fit$model$hmm_model$trained_hmm$difference` to see the training changes and whether the iteration limit was reached. Version 2 changes the defaults and output relative to version 1.0.3. To use the earlier window representation, set `transform = "return"` and `stride = horizon`; forecasts will still differ because the distribution, training and evaluation methods have changed.