17 |
18 |
19 | [](https://travis-ci.com/DylanB95/statespacer)
20 | [](https://www.tidyverse.org/lifecycle/#stable)
21 | [](https://CRAN.R-project.org/package=statespacer)
22 |
23 |
24 | ## Overview
25 | statespacer is a package for state space modelling and forecasting in R. It provides functions that make estimating models in State Space form a breeze. This package implements state-of-the-art algorithms developed by various time series practitioners such as J. Durbin and S.J. Koopman. Details about the algorithms can be found in their book, "Time Series Analysis by State Space Methods".
26 |
27 | If you are new to statespacer, check out `vignette("intro", "statespacer")` for a quick start to the statespacer package! Also check out the references for the following functions:
28 |
29 | * `statespacer()` for fitting State Space models.
30 | * `predict.statespacer()` for producing forecasts and out-of-sample simulations using fitted State Space models.
31 | * `SimSmoother()` for drawing random samples of the hidden state of a State Space model conditional on the data.
32 |
33 | ## State Space Components
34 | This package supports numerous state space components:
35 |
36 | * The Local Level
37 | * The Local Level + Slope
38 | * Smoothing Splines
39 | * Trigonometric Seasonality, BSM
40 | * (Business) Cycles
41 | * Explanatory Variables
42 | * Explanatory Variables with time-varying coefficients
43 | * Explanatory Variables in the Local Level
44 | * Explanatory Variables in the Local Level + Slope
45 | * ARIMA
46 | * SARIMA
47 | * Moreover, you can specify a component yourself!
48 |
49 | These components can be used for both univariate, and multivariate models. The components can be combined in order to get more extensive models. Moreover, the user can control the format of the variance - covariance matrices of each of the components. This way, one could specify the components to be deterministic instead of stochastic. In the multivariate case, one could impose rank restrictions on the variance - covariance matrices such that commonalities in the components are estimated, like common levels, common slopes, etc.
50 |
51 | ## Fitting Procedure
52 | The package employs a univariate treatment, and an exact initialisation for diffuse elements, to estimate the state parameters and compute the loglikelihood. Collapsing large observation vectors is supported as well. Moreover, missing observations are readily dealt with by putting the models in State Space form!
53 |
54 | ## Installation
55 |
56 | You can install statespacer from CRAN with:
57 |
58 | ```{r, eval = FALSE}
59 | install.packages("statespacer")
60 | ```
61 |
62 | ### Development version
63 |
64 | To get a bug fix or to use a feature from the development version, you can install the development version of statespacer from GitHub.
65 |
66 | ```{r, eval = FALSE}
67 | # install.packages("devtools")
68 | devtools::install_github("DylanB95/statespacer")
69 | ```
70 |
71 | ## Usage
72 | ```{r, message = FALSE, warning = FALSE}
73 | library(statespacer)
74 |
75 | library(datasets)
76 | y <- matrix(Nile)
77 |
78 | fit <- statespacer(y = y,
79 | local_level_ind = TRUE,
80 | initial = 0.5*log(var(y)))
81 |
82 | plot(1871:1970, fit$function_call$y, type = 'p', ylim = c(500, 1400),
83 | xlab = NA, ylab = NA,
84 | sub = "The smoothed level with 90% confidence intervals,
85 | and the observed data points")
86 | lines(1871:1970, fit$smoothed$level, type = 'l')
87 | lines(1871:1970, fit$smoothed$level + qnorm(0.95) * sqrt(fit$smoothed$V[1,1,]),
88 | type = 'l', col = 'gray'
89 | )
90 | lines(1871:1970, fit$smoothed$level - qnorm(0.95) * sqrt(fit$smoothed$V[1,1,]),
91 | type = 'l', col = 'gray'
92 | )
93 | ```
94 |
95 | ## Getting help
96 |
97 | If you encounter a clear bug, please file an issue with a minimal reproducible example on [GitHub](https://github.com/DylanB95/statespacer/issues).
98 |
99 | ---
100 | Please note that the 'statespacer' project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By contributing to this project, you agree to abide by its terms.
101 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | # State Space Modelling in R
5 |
6 |
7 |
8 | [](https://travis-ci.com/DylanB95/statespacer)
10 | [](https://www.tidyverse.org/lifecycle/#stable)
12 | [](https://CRAN.R-project.org/package=statespacer)
14 |
15 |
16 | ## Overview
17 |
18 | statespacer is a package for state space modelling and forecasting in R.
19 | It provides functions that make estimating models in State Space form a
20 | breeze. This package implements state-of-the-art algorithms developed by
21 | various time series practitioners such as J. Durbin and S.J. Koopman.
22 | Details about the algorithms can be found in their book, “Time Series
23 | Analysis by State Space Methods”.
24 |
25 | If you are new to statespacer, check out
26 | `vignette("intro", "statespacer")` for a quick start to the statespacer
27 | package! Also check out the references for the following functions:
28 |
29 | - `statespacer()` for fitting State Space models.
30 | - `predict.statespacer()` for producing forecasts and out-of-sample
31 | simulations using fitted State Space models.
32 | - `SimSmoother()` for drawing random samples of the hidden state of a
33 | State Space model conditional on the data.
34 |
35 | ## State Space Components
36 |
37 | This package supports numerous state space components:
38 |
39 | - The Local Level
40 | - The Local Level + Slope
41 | - Smoothing Splines
42 | - Trigonometric Seasonality, BSM
43 | - (Business) Cycles
44 | - Explanatory Variables
45 | - Explanatory Variables with time-varying coefficients
46 | - Explanatory Variables in the Local Level
47 | - Explanatory Variables in the Local Level + Slope
48 | - ARIMA
49 | - SARIMA
50 | - Moreover, you can specify a component yourself!
51 |
52 | These components can be used for both univariate, and multivariate
53 | models. The components can be combined in order to get more extensive
54 | models. Moreover, the user can control the format of the variance -
55 | covariance matrices of each of the components. This way, one could
56 | specify the components to be deterministic instead of stochastic. In the
57 | multivariate case, one could impose rank restrictions on the variance -
58 | covariance matrices such that commonalities in the components are
59 | estimated, like common levels, common slopes, etc.
60 |
61 | ## Fitting Procedure
62 |
63 | The package employs a univariate treatment, and an exact initialisation
64 | for diffuse elements, to estimate the state parameters and compute the
65 | loglikelihood. Collapsing large observation vectors is supported as
66 | well. Moreover, missing observations are readily dealt with by putting
67 | the models in State Space form!
68 |
69 | ## Installation
70 |
71 | You can install statespacer from CRAN with:
72 |
73 | ``` r
74 | install.packages("statespacer")
75 | ```
76 |
77 | ### Development version
78 |
79 | To get a bug fix or to use a feature from the development version, you
80 | can install the development version of statespacer from GitHub.
81 |
82 | ``` r
83 | # install.packages("devtools")
84 | devtools::install_github("DylanB95/statespacer")
85 | ```
86 |
87 | ## Usage
88 |
89 | ``` r
90 | library(statespacer)
91 |
92 | library(datasets)
93 | y <- matrix(Nile)
94 |
95 | fit <- statespacer(y = y,
96 | local_level_ind = TRUE,
97 | initial = 0.5*log(var(y)))
98 |
99 | plot(1871:1970, fit$function_call$y, type = 'p', ylim = c(500, 1400),
100 | xlab = NA, ylab = NA,
101 | sub = "The smoothed level with 90% confidence intervals,
102 | and the observed data points")
103 | lines(1871:1970, fit$smoothed$level, type = 'l')
104 | lines(1871:1970, fit$smoothed$level + qnorm(0.95) * sqrt(fit$smoothed$V[1,1,]),
105 | type = 'l', col = 'gray'
106 | )
107 | lines(1871:1970, fit$smoothed$level - qnorm(0.95) * sqrt(fit$smoothed$V[1,1,]),
108 | type = 'l', col = 'gray'
109 | )
110 | ```
111 |
112 |
113 |
114 | ## Getting help
115 |
116 | If you encounter a clear bug, please file an issue with a minimal
117 | reproducible example on
118 | [GitHub](https://github.com/DylanB95/statespacer/issues).
119 |
120 | ------------------------------------------------------------------------
121 |
122 | Please note that the ‘statespacer’ project is released with a
123 | [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By contributing to
124 | this project, you agree to abide by its terms.
125 |
--------------------------------------------------------------------------------
/vignettes/intro.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Introduction to statespacer"
3 | description: >
4 | Start here if this is your first time using statespacer. You'll learn how to
5 | use `statespacer()` to fit a simple State Space model, called the Local
6 | Level model, to the Nile dataset.
7 | output: rmarkdown::html_vignette
8 | bibliography: ../inst/REFERENCES.bib
9 | vignette: >
10 | %\VignetteIndexEntry{Introduction to statespacer}
11 | %\VignetteEngine{knitr::rmarkdown}
12 | %\VignetteEncoding{UTF-8}
13 | ---
14 |
15 | ```{r, include = FALSE}
16 | knitr::opts_chunk$set(
17 | collapse = TRUE,
18 | comment = "#>"
19 | )
20 | ```
21 |
22 | This document provides a brief introduction to using the statespacer package. It does so by showcasing the estimation of a Local Level model on the well known Nile data. See `?Nile` for more information about this dataset.
23 |
24 | To start, let's first introduce the Local Level model. Mathematically, this model can be represented as follows:
25 |
26 | $$
27 | \begin{aligned}
28 | y_t ~ &= ~ \mu_t ~ + ~ \varepsilon_t, ~~~~~~ \varepsilon_t ~ \sim ~ N(0, ~ \sigma_\varepsilon^2), \\
29 | \mu_{t+1} ~ &= ~ \mu_t ~ + ~ \eta_t, ~~~~~~ \eta_t ~ \sim ~ N(0, ~ \sigma_\eta^2),
30 | \end{aligned}
31 | $$
32 |
33 | where $y_t$ is the dependent variable at time $t$, $\mu_t$ is the unobserved level at time $t$, and $\varepsilon_t$ and $\eta_t$ are disturbances. This model has two parameters, $\sigma_\varepsilon^2$ and $\sigma_\eta^2$ that will be estimated by maximising the loglikelihood. In addition, the level $\mu_t$ is a state parameter that will be estimated by employing the Kalman Filter. For extensive details about the algorithms employed, see @durbin2012time.
34 |
35 | Estimating this model using the statespacer package is simple. First, we load the data and extract the dependent variable. The dependent variable needs to be specified as a matrix, with each column being one of the dependents. In this case, we just have one column, as the Nile data comprises a univariate series.
36 |
37 | ```{r, setup}
38 | # Load statespacer
39 | library(statespacer)
40 |
41 | # Load the dataset
42 | library(datasets)
43 | y <- matrix(Nile)
44 | ```
45 |
46 | To fit a local level model, we simply call the `statespacer()` function. See `?statespacer` for further details.
47 |
48 | ```{r}
49 | fit <- statespacer(y = y,
50 | local_level_ind = TRUE,
51 | initial = 0.5*log(var(y)),
52 | verbose = TRUE)
53 | ```
54 |
55 | We get a warning message about the number of initial parameters, as we didn't specify enough of them. We needed 2 initial parameters, but specified only 1. This is okay, as the function just replicates the specified parameters the required amount of times. This way, we don't need to worry about how many parameters are needed. We could also specify too many initial parameters, in which case only the first few are used. This is particularly useful when we want random initial parameters. One could just simply specify `initial = rnorm(1000)`, and not have to worry about if enough parameters were supplied.
56 |
57 | Now, let's check the estimated values of $\sigma_\varepsilon^2$ and $\sigma_\eta^2$.
58 |
59 | ```{r}
60 | c(fit$system_matrices$H$H, fit$system_matrices$Q$level)
61 | ```
62 |
63 | Note that we use the notation used in @durbin2012time for the system matrices. $H$ being the system matrix for the variance - covariance matrix of the observation equation, and $Q$ being the system matrix for the variance - covariance matrix of the state equation.
64 |
65 | Checking out the estimated level is easy as well. The filtered level:
66 |
67 | ```{r, fig.height = 4.5, fig.width = 7}
68 | plot(1871:1970, fit$function_call$y, type = 'p', ylim = c(500, 1400),
69 | xlab = NA, ylab = NA,
70 | sub = "The filtered level with 90% confidence intervals,
71 | and the observed data points"
72 | )
73 | lines(1871:1970, fit$filtered$level, type = 'l')
74 | lines(1871:1970, fit$filtered$level + qnorm(0.95) * sqrt(fit$filtered$P[1,1,]),
75 | type = 'l', col = 'gray'
76 | )
77 | lines(1871:1970, fit$filtered$level - qnorm(0.95) * sqrt(fit$filtered$P[1,1,]),
78 | type = 'l', col = 'gray'
79 | )
80 | ```
81 |
82 | And the smoothed level:
83 |
84 | ```{r, fig.height = 4.5, fig.width = 7}
85 | plot(1871:1970, fit$function_call$y, type = 'p', ylim = c(500, 1400),
86 | xlab = NA, ylab = NA,
87 | sub = "The smoothed level with 90% confidence intervals,
88 | and the observed data points")
89 | lines(1871:1970, fit$smoothed$level, type = 'l')
90 | lines(1871:1970, fit$smoothed$level + qnorm(0.95) * sqrt(fit$smoothed$V[1,1,]),
91 | type = 'l', col = 'gray'
92 | )
93 | lines(1871:1970, fit$smoothed$level - qnorm(0.95) * sqrt(fit$smoothed$V[1,1,]),
94 | type = 'l', col = 'gray'
95 | )
96 | ```
97 |
98 | The object returned by `statespacer()` exhibits many other useful items. For more information about these items, please see `vignette("dictionary", "statespacer")`. For more exhibitions of the statespacer package, please see the other tutorials on YEAR: 2020 77 | COPYRIGHT HOLDER: Dylan Beijers 78 |79 | 80 |