### Quick Start: Fit LocalLevel and Forecast Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Quick start workflow: install the package, create a LocalLevel model, fit it, print results, forecast 10 steps, and run Kalman filter and smoother to extract innovations and smoothed states. ```julia import Pkg Pkg.add("StateSpaceModels") using StateSpaceModels y = randn(100) model = LocalLevel(y) fit!(model) print_results(model) forec = forecast(model, 10) kf = kalman_filter(model) v = get_innovations(kf) ks = kalman_smoother(model) alpha = get_smoothed_state(ks) ``` -------------------------------- ### LocalLevelExplanatory constructor and example Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructs a local level model with explanatory variables. The example creates a model from 100 random observations and a 100x1 matrix of explanatory variables. ```julia LocalLevelExplanatory(y::Vector{Fl}, X::Matrix{Fl}) where Fl ``` ```julia julia> model = LocalLevelExplanatory(rand(100), rand(100, 1)) LocalLevelExplanatory ``` -------------------------------- ### Install StateSpaceModels.jl with Pkg Source: https://lampspuc.github.io/StateSpaceModels.jl/stable Install the registered StateSpaceModels.jl package using Julia's Pkg manager. ```julia pkg> add StateSpaceModels ``` -------------------------------- ### Example: set_initial_hyperparameters! on LocalLevel Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Example usage of set_initial_hyperparameters! on a LocalLevel model. It shows the hyperparameter names and the resulting constrained_values vector with NaN for unset values. ```julia julia> model = LocalLevel(rand(100)) LocalLevel julia> get_names(model) 2-element Vector{String}: "sigma2_ε" "sigma2_η" julia> set_initial_hyperparameters!(model, Dict("sigma2_η" => 100.0)) LocalLevel julia> model.hyperparameters.constrained_values 2-element Vector{Float64}: NaN 100.0 ``` -------------------------------- ### SARIMA model construction example Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Shows how to create a SARIMA model instance using random data and specified orders. The output displays the model summary. ```julia julia> model = SARIMA(rand(100); order=(1,1,1), seasonal_order=(1,2,3,12)) SARIMA(1, 1, 1)x(1, 2, 3, 12) with zero mean ``` -------------------------------- ### LocalLevel constructor and example Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructs a local level model with the given vector of observations. The example creates a model from 100 random values. ```julia LocalLevel(y::Vector{Fl}) where Fl ``` ```julia julia> model = LocalLevel(rand(100)) LocalLevel ``` -------------------------------- ### BasicStructural model construction example Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Shows how to create a BasicStructural model instance using random data and a seasonal period of 12. The output displays the model name. ```julia julia> model = BasicStructural(rand(100), 12) BasicStructural ``` -------------------------------- ### MultivariateBasicStructural constructor and example Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructs a multivariate basic structural model with trend and seasonal components. The example creates a model from a 100x2 matrix of observations and a seasonal period of 12. ```julia MultivariateBasicStructural(y::Matrix{Fl}, s::Int) where Fl ``` ```julia julia> model = MultivariateBasicStructural(rand(100, 2), 12) MultivariateBasicStructural ``` -------------------------------- ### LocalLevelCycle constructor and example Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructs a local level model with a cycle component. The example creates a model from 100 random values. ```julia LocalLevelCycle(y::Vector{Fl}) where Fl ``` ```julia julia> model = LocalLevelCycle(rand(100)) LocalLevelCycle ``` -------------------------------- ### LinearRegression model construction example Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Shows how to create a LinearRegression model instance using random data. The output displays the model name. ```julia julia> model = LinearRegression(rand(100, 2), rand(100)) LinearRegression ``` -------------------------------- ### Creating an Optimizer with BFGS Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Example of creating an Optimizer with BFGS and showing the trace. The semicolon suppresses the large log output. ```julia julia> using Optim # use a semicolon to avoid displaying the big log julia> opt = Optimizer(Optim.BFGS(), Optim.Options(show_trace = true)); ``` -------------------------------- ### LocalLinearTrend constructor and example Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructs a local linear trend model. The example creates a model from 100 random values. ```julia LocalLinearTrend(y::Vector{Fl}) where Fl ``` ```julia julia> model = LocalLinearTrend(rand(100)) LocalLinearTrend ``` -------------------------------- ### Example: fix_hyperparameters! on LocalLevel Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Example usage of fix_hyperparameters! on a LocalLevel model. It shows the hyperparameter names and the resulting fixed_constrained_values dictionary. ```julia julia> model = LocalLevel(rand(100)) LocalLevel julia> get_names(model) 2-element Vector{String}: "sigma2_ε" "sigma2_η" julia> fix_hyperparameters!(model, Dict("sigma2_ε" => 100.0)) LocalLevel julia> model.hyperparameters.fixed_constrained_values Dict{String, Float64} with 1 entry: "sigma2_ε" => 100.0 ``` -------------------------------- ### BasicStructuralExplanatory model construction example Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Shows how to create a BasicStructuralExplanatory model instance using random data, a seasonal period of 12, and a random matrix of explanatory variables. The output displays the model name. ```julia julia> model = BasicStructuralExplanatory(rand(100), 12, rand(100, 2)) BasicStructuralExplanatory ``` -------------------------------- ### Fitting LocalLevel and LocalLinearTrend models Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Example of fitting a LocalLevel model with default settings and a LocalLinearTrend model with a NelderMead optimizer. The output shows the model type after each call. ```julia julia> model = LocalLevel(rand(100)) LocalLevel julia> fit!(model) LocalLevel julia> model = LocalLinearTrend(LinRange(1, 100, 100) + rand(100)) LocalLinearTrend julia> fit!(model; optimizer = Optimizer(StateSpaceModels.Optim.NelderMead())) LocalLinearTrend ``` -------------------------------- ### Get WHOLESALE_PRICE_INDEX dataset path Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the absolute path to the WHOLESALE_PRICE_INDEX dataset stored inside StateSpaceModels.jl. The dataset is marked as TODO in the documentation. ```julia WHOLESALE_PRICE_INDEX ``` -------------------------------- ### SARIMA type definition Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Defines the SARIMA model constructor with keyword arguments for order, seasonal_order, and include_mean. The example shows creating a SARIMA model with order (1,1,1) and seasonal order (1,2,3,12). ```julia SARIMA( y::Vector{Fl}; order::Tuple{Int,Int,Int} = (1, 0, 0), seasonal_order::Tuple{Int, Int, Int, Int} = (0, 0, 0, 0), include_mean::Bool = false, ) where Fl ``` -------------------------------- ### BasicStructuralExplanatory type definition Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Defines the BasicStructuralExplanatory model constructor that takes a vector of observations, a seasonal period, and a matrix of explanatory variables. The example shows creating a model with 100 observations, seasonal period 12, and two explanatory variables. ```julia BasicStructuralExplanatory(y::Vector{Fl}, s::Int, X::Matrix{Fl}) where Fl ``` -------------------------------- ### Get hyperparameter names with get_names Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the names of the hyperparameters registered on a StateSpaceModel. ```julia get_names(model::StateSpaceModel) ``` -------------------------------- ### BasicStructural type definition Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Defines the BasicStructural model constructor that takes a vector of observations and a seasonal period. The example shows creating a model with 100 observations and a seasonal period of 12. ```julia BasicStructural(y::Vector{Fl}, s::Int) where Fl ``` -------------------------------- ### Get INTERNET dataset path Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the absolute path to the INTERNET dataset stored inside StateSpaceModels.jl. The dataset provides the number of users logged on to an Internet server each minute over 100 minutes. ```julia INTERNET ``` -------------------------------- ### Get smoothed state estimates from Kalman smoother Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Runs the Kalman smoother on the fitted model and retrieves the smoothed state estimates for the level of the annual flow. The output is a vector of Float64 values. ```julia smoother_output = kalman_smoother(model) get_smoothed_state(smoother_output) ``` -------------------------------- ### Get filtered state estimates from Kalman filter Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Runs the Kalman filter on the fitted model and retrieves the filtered state estimates for the level of the annual flow. The output is a 100x1 matrix of Float64 values. ```julia filter_output = kalman_filter(model) get_filtered_state(filter_output) ``` -------------------------------- ### Get SUNSPOTS_YEAR dataset path Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the absolute path to the SUNSPOTS_YEAR dataset stored inside StateSpaceModels.jl. The dataset provides yearly numbers of sunspots from 1700 to 1988 (rounded to one digit). ```julia SUNSPOTS_YEAR ``` -------------------------------- ### Get RJ_TEMPERATURE dataset path Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the absolute path to the RJ_TEMPERATURE dataset stored inside StateSpaceModels.jl. The dataset provides weekly mean temperature in Rio de Janeiro in Kelvin (K). ```julia RJ_TEMPERATURE ``` -------------------------------- ### Get FRONT_REAR_SEAT_KSI dataset path Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the absolute path to the FRONT_REAR_SEAT_KSI dataset stored inside StateSpaceModels.jl. The dataset provides the log of British people killed or seriously injured in road accidents across the UK. ```julia FRONT_REAR_SEAT_KSI ``` -------------------------------- ### Get US_CHANGE dataset path Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the absolute path to the US_CHANGE dataset stored inside StateSpaceModels.jl. The dataset provides percentage changes in quarterly personal consumption expenditure, personal disposable income, production, savings and the unemployment rate for the US, 1960 to 2016. ```julia US_CHANGE ``` -------------------------------- ### Set initial hyperparameters with set_initial_hyperparameters! Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Fill a model with user inputed initial points for hyperparameter optimzation. ```julia set_initial_hyperparameters!(model::StateSpaceModel, initial_hyperparameters::Dict{String, <:Real}) ``` -------------------------------- ### BasicStructuralExplanatory Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor for the BasicStructuralExplanatory model type. ```APIDOC ## BasicStructuralExplanatory ### Description Constructs a basic structural state-space model with explanatory variables. The model includes a trend, seasonal component, and regression effects from the explanatory variables. ### Constructor `BasicStructuralExplanatory(y::Vector{Fl}, s::Int, X::Matrix{Fl}) where Fl` ### Parameters - **y** (Vector{Fl}) - Required - The time series data. - **s** (Int) - Required - The seasonal period. - **X** (Matrix{Fl}) - Required - The matrix of explanatory variables. ### Example ```julia julia> model = BasicStructuralExplanatory(rand(100), 12, rand(100, 2)) BasicStructuralExplanatory ``` ``` -------------------------------- ### Julia: Run cross_validation on BasicStructural model Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Loads the air passengers dataset, applies a log transformation, fits a BasicStructural model with a 12-month seasonal period, and runs cross_validation with a 24-step horizon and 50 rolling windows. ```julia using CSV, DataFrames air_passengers = CSV.File(StateSpaceModels.AIR_PASSENGERS) |> DataFrame log_air_passengers = log.(air_passengers.passengers) model = BasicStructural(log_air_passengers, 12) b = cross_validation(model, 24, 50) ``` -------------------------------- ### LinearRegression type definition Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Defines the LinearRegression model constructor that takes a matrix of predictors and a vector of responses. The example shows creating a model with 100 observations and two predictors. ```julia LinearRegression(X::Matrix{Fl}, y::Vector{Fl}) where Fl ``` -------------------------------- ### ExperimentalSeasonalNaive model constructor Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor for an experimental seasonal naive model that simulates S scenarios and uses the mean as the forecast. The default number of simulations is 10,000. ```julia ExperimentalSeasonalNaive(y::Vector{<:Real}, seasonal::Int; S::Int = 10_000) ``` -------------------------------- ### BasicStructural Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor for the BasicStructural model type. ```APIDOC ## BasicStructural ### Description Constructs a basic structural state-space model consisting of a trend (level + slope) and a seasonal component. The model is defined by the equations for the observation, level, slope, and seasonal components. ### Constructor `BasicStructural(y::Vector{Fl}, s::Int) where Fl` ### Parameters - **y** (Vector{Fl}) - Required - The time series data. - **s** (Int) - Required - The seasonal period. ### Example ```julia julia> model = BasicStructural(rand(100), 12) BasicStructural ``` ``` -------------------------------- ### Get VEHICLE_FATALITIES dataset path Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the absolute path to the VEHICLE_FATALITIES dataset stored inside StateSpaceModels.jl. The dataset provides the number of annual road traffic fatalities in Norway and Finland. ```julia VEHICLE_FATALITIES ``` -------------------------------- ### simulate_scenarios(model::StateSpaceModel, steps_ahead::Int, n_scenarios::Int; filter::KalmanFilter=default_filter(model)) Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Samples future scenarios via Monte Carlo simulation for a given number of steps ahead. ```APIDOC ## simulate_scenarios(model::StateSpaceModel, steps_ahead::Int, n_scenarios::Int; filter::KalmanFilter=default_filter(model)) -> Array{<:AbstractFloat, 3} ### Description Samples `n_scenarios` future scenarios via Monte Carlo simulation for `steps_ahead` using the desired `filter`. ### Method Function call ### Endpoint `simulate_scenarios(model::StateSpaceModel, steps_ahead::Int, n_scenarios::Int; filter::KalmanFilter=default_filter(model))` ### Parameters - **model** (StateSpaceModel) - Required - The state space model to simulate scenarios from. - **steps_ahead** (Int) - Required - Number of steps ahead to simulate. - **n_scenarios** (Int) - Required - Number of scenarios to sample. - **filter** (KalmanFilter) - Optional - The filter to use; defaults to `default_filter(model)`. ### Response Returns an array of shape (steps_ahead, n_scenarios, ...) with simulated scenarios. ``` -------------------------------- ### Get AIR_PASSENGERS dataset path Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the absolute path to the AIR_PASSENGERS dataset stored inside StateSpaceModels.jl. The dataset provides monthly totals of US airline passengers from 1949 to 1960. ```julia AIR_PASSENGERS ``` -------------------------------- ### Naive model constructor Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor for a naive model where the h-step ahead forecast is the last observed value. Use as a benchmark for forecasting. ```julia Naive(y::Vector{<:Real}) ``` -------------------------------- ### set_initial_hyperparameters! Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Sets initial values for hyperparameters to be used in optimization. ```APIDOC ## set_initial_hyperparameters!(model::StateSpaceModel, initial_hyperparameters::Dict{String, <:Real}) ### Description Fill a model with user inputed initial points for hyperparameter optimization. ### Method Function ### Endpoint `StateSpaceModels.set_initial_hyperparameters!(model::StateSpaceModel, initial_hyperparameters::Dict{String, <:Real})` ### Parameters - **model** (`StateSpaceModel`) - Required - The state space model. - **initial_hyperparameters** (`Dict{String, <:Real}`) - Required - Dictionary mapping hyperparameter names to initial values. ### Response Returns the modified model. ### Example ```julia julia> model = LocalLevel(rand(100)) LocalLevel julia> get_names(model) 2-element Vector{String}: "sigma2_ε" "sigma2_η" julia> set_initial_hyperparameters!(model, Dict("sigma2_η" => 100.0)) LocalLevel julia> model.hyperparameters.constrained_values 2-element Vector{Float64}: NaN 100.0 ``` ``` -------------------------------- ### cross_validation(model::StateSpaceModel, steps_ahead::Int, start_idx::Int; n_scenarios::Int = 10_000, filter::KalmanFilter=default_filter(model), optimizer::Optimizer=default_optimizer(model)) Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Performs rolling window cross-validation to benchmark forecasting skill. ```APIDOC ## cross_validation(model::StateSpaceModel, steps_ahead::Int, start_idx::Int; n_scenarios::Int = 10_000, filter::KalmanFilter=default_filter(model), optimizer::Optimizer=default_optimizer(model)) ### Description Makes rolling window estimating and forecasting to benchmark the forecasting skill of the model for different time periods and different lead times. Returns a struct with the MAE and mean CRPS per lead time. ### Method Function call ### Endpoint `cross_validation(model::StateSpaceModel, steps_ahead::Int, start_idx::Int; n_scenarios::Int = 10_000, filter::KalmanFilter=default_filter(model), optimizer::Optimizer=default_optimizer(model))` ### Parameters - **model** (StateSpaceModel) - Required - The state space model to cross-validate. - **steps_ahead** (Int) - Required - Number of steps ahead to forecast. - **start_idx** (Int) - Required - Starting index for the rolling window. - **n_scenarios** (Int) - Optional - Number of scenarios for simulation; default is 10,000. - **filter** (KalmanFilter) - Optional - The filter to use; defaults to `default_filter(model)`. - **optimizer** (Optimizer) - Optional - The optimizer to use; defaults to `default_optimizer(model)`. ### Response Returns a struct with the MAE and mean CRPS per lead time. ``` -------------------------------- ### StateSpaceModels.ExperimentalSeasonalNaive Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor for an experimental seasonal naive model that simulates multiple scenarios to produce a forecast. ```APIDOC ## ExperimentalSeasonalNaive(y::Vector{<:Real}, seasonal::Int; S::Int = 10_000) ### Description A seasonal naive model where the h step ahead forecast is the mean of the simulation of S scenarios: yT+h|T = yT+h−m(k+1) + εt, where m is the seasonal period, k is the integer part of (h-1)/m and εt is a sampled error. ### Method Constructor ### Endpoint `StateSpaceModels.ExperimentalSeasonalNaive(y::Vector{<:Real}, seasonal::Int; S::Int = 10_000)` ### Parameters - **y** (Vector{<:Real}) - Required - The time series data. - **seasonal** (Int) - Required - The seasonal period (m). - **S** (Int) - Optional - Number of simulation scenarios (default: 10,000). ### References - None provided. ``` -------------------------------- ### Get NILE dataset path Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Returns the absolute path to the NILE dataset stored inside StateSpaceModels.jl. The dataset provides measurements of the annual flow of the Nile river at Aswan from 1871 to 1970, in 108m3. ```julia NILE ``` -------------------------------- ### StateSpaceModels.Naive Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor for a naive model that uses the last observed value as the forecast for all future horizons. ```APIDOC ## Naive(y::Vector{<:Real}) ### Description A naive model where the h step ahead forecast is yT+h|T = yT. ### Method Constructor ### Endpoint `StateSpaceModels.Naive(y::Vector{<:Real})` ### Parameters - **y** (Vector{<:Real}) - Required - The time series data. ### References - Hyndman, Rob J., Athanasopoulos, George. "Forecasting: Principles and Practice" ``` -------------------------------- ### SARIMA Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor for the SARIMA model type. ```APIDOC ## SARIMA ### Description Constructs a SARIMA model (Seasonal AutoRegressive Integrated Moving Average) within the state-space framework. The model is specified by (p,d,q)×(P,D,Q,s) and can include a constant term via the `include_mean` keyword. ### Constructor `SARIMA(y::Vector{Fl}; order::Tuple{Int,Int,Int} = (1, 0, 0), seasonal_order::Tuple{Int, Int, Int, Int} = (0, 0, 0, 0), include_mean::Bool = false) where Fl` ### Parameters - **y** (Vector{Fl}) - Required - The time series data. - **order** (Tuple{Int,Int,Int}) - Optional - The non-seasonal (p,d,q) order. Default: (1,0,0). - **seasonal_order** (Tuple{Int,Int,Int,Int}) - Optional - The seasonal (P,D,Q,s) order. Default: (0,0,0,0). - **include_mean** (Bool) - Optional - Whether to include a constant term. Default: false. ### Example ```julia julia> model = SARIMA(rand(100); order=(1,1,1), seasonal_order=(1,2,3,12)) SARIMA(1, 1, 1)x(1, 2, 3, 12) with zero mean ``` ``` -------------------------------- ### kalman_filter Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Runs the Kalman filter on a state space model and returns the filter output. ```APIDOC ## kalman_filter ### Description Filter the data using the desired `filter` and the estimated hyperparameters in `model`. ### Method Function call ### Endpoint `kalman_filter(model::StateSpaceModel; filter::KalmanFilter=default_filter(model)) -> FilterOutput` ### Parameters - **model** (StateSpaceModel) - Required - The state space model with estimated hyperparameters. - **filter** (KalmanFilter) - Optional - The filter to use. Defaults to `default_filter(model)`. ### Returns - **FilterOutput** - Structure with the results of the Kalman filter. ``` -------------------------------- ### Forecast output for 24 steps ahead Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Output of the forecast command, showing the forecasted values and standard errors for the next 24 time points. ```text StateSpaceModels.Forecast{Float64}([[6.1100783269760806], [6.053643535089317], [6.171326207071635], [6.199284566888648], [6.232663436588682], [6.368794427137307], [6.50742299366151], [6.503004703603158], [6.324632038853844], [6.209032320028253] … [6.26744855378555], [6.295406913602562], [6.328785783302597], [6.464916773851222], [6.603545340375425], [6.5991270503170725], [6.420754385567759], [6.305154666742168], [6.159527964824452], [6.263985795085841]], [[0.0013606492643246676;;], [0.0018485279562723811;;], [0.0023364066482185275;;], [0.002824285340164674;;], [0.0033121640321108203;;], [0.0038000427240569667;;], [0.004287921530288826;;], [0.004775800322234974;;], [0.0052636791141811206;;], [0.005751557906128267;;] … [0.010255711840981315;;], [0.0112756523907784;;], [0.012295592969832864;;], [0.013315533581722543;;], [0.01433547439154342;;], [0.015355415366095434;;], [0.01637535614434456;;], [0.017395296922618417;;], [0.01842137626486757;;], [0.019434891531997466;;]]) ``` -------------------------------- ### Forecast 24 steps ahead with SARIMA model Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Creates a forecast of 24 steps ahead from the fitted SARIMA model. The output shows the forecasted values and their standard errors. ```julia forec = forecast(model, 24) ``` -------------------------------- ### SeasonalNaive model constructor Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor for a seasonal naive model where the forecast is the value from the same season in the previous cycle. The seasonal period m is provided as the second argument. ```julia SeasonalNaive(y::Vector{<:Real}, seasoanl::Int) ``` -------------------------------- ### Unconstrain box with unconstrain_box! Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Map an unconstrained hyperparameter ψ∗∈R to a constrained hyperparameter ψ∈[lb,ub]. The mapping is ψ∗=−lnub−lbψ−lb−1 ```julia unconstrain_box!(model::StateSpaceModel, str::String, lb::Fl, ub::Fl) where Fl ``` -------------------------------- ### forecast(model::StateSpaceModel, steps_ahead::Int; kwargs...) Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Forecast the mean and covariance for future observations from a StateSpaceModel. ```APIDOC ## forecast(model::StateSpaceModel, steps_ahead::Int; kwargs...) ### Description Forecast the mean and covariance for future observations from a StateSpaceModel. ### Method Function call ### Endpoint `forecast(model::StateSpaceModel, steps_ahead::Int; kwargs...)` ### Parameters - **model** (StateSpaceModel) - Required - The state space model to forecast from. - **steps_ahead** (Int) - Required - Number of steps ahead to forecast. - **kwargs** - Optional - Additional keyword arguments (not specified). ### Response Returns the forecast mean and covariance for future observations. ``` -------------------------------- ### StateSpaceModels.print_results Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual The `print_results` function prints the optimization results stored in a fitted state-space model. ```APIDOC ## `StateSpaceModels.print_results` — Function ### Description Query the results of the optimization called by `fit!`. ### Signature ```julia print_results(model::StateSpaceModel) ``` ### Parameters - **model** (`StateSpaceModel`) - Required - The fitted state-space model whose optimization results are to be printed. ``` -------------------------------- ### Constrain box with constrain_box! Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Map a constrained hyperparameter ψ∈[lb,ub] to an unconstrained hyperparameter ψ∗∈R. The mapping is ψ=lb+ub−lb1+exp(−ψ∗) ```julia constrain_box!(model::StateSpaceModel, str::String, lb::Fl, ub::Fl) where Fl ``` -------------------------------- ### SARIMA model estimation results Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Output of fitting the SARIMA(0,1,1)x(0,1,1,12) model, showing parameter estimates, standard errors, z-statistics, and p-values. The estimates match the paper 'State Space Methods in Ox/SsfPack' up to the 3rd decimal place. ```text Results =============================================================== Model: SARIMA(0, 1, 1)x(0, 1, 1, 12) with zero mean Number of observations: 144 Number of unknown parameters: 3 Log-likelihood: 244.6323 AIC: -483.2645 AICc: -483.0931 BIC: -474.3551 --------------------------------------------------------------- Parameter Estimate Std.Error z stat p-value ma_L1 -0.4011 0.1291 -3.1079 0.0019 s_ma_L12 -0.5561 0.1462 -3.8029 0.0001 sigma2_η 0.0014 0.0024 0.5646 0.5724 ``` -------------------------------- ### Output of fitting LocalLevel model Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Displays the fitted model object, which is a LocalLevel model. ```text LocalLevel ``` -------------------------------- ### LinearUnivariateTimeInvariant constructor Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Definition of the system matrices y, Z, d, T, c, R, H, Q for linear univariate time invariant state space models. The model equations are yt = Zαt + d + εt with εt ~ N(0, H) and αt+1 = Tαt + c + Rηt with ηt ~ N(0, Q). ```julia LinearUnivariateTimeInvariant{Fl}( y::Vector{Fl}, Z::Vector{Fl}, T::Matrix{Fl}, R::Matrix{Fl}, d::Fl, c::Vector{Fl}, H::Fl, Q::Matrix{Fl}, ) where Fl <: AbstractFloat ``` -------------------------------- ### LinearUnivariateTimeVariant constructor Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Definition of the system matrices y, Z, d, T, c, R, H, Q for linear univariate time variant state space models. The model equations are yt = Ztαt + dt + εt with εt ~ N(0, Ht) and αt+1 = Ttαt + ct + Rtηt with ηt ~ N(0, Qt). ```julia LinearUnivariateTimeVariant{Fl}( y::Vector{Fl}, Z::Vector{Vector{Fl}}, T::Vector{Matrix{Fl}}, R::Vector{Matrix{Fl}}, d::Vector{Fl}, c::Vector{Vector{Fl}}, H::Vector{Fl}, Q::Vector{Matrix{Fl}}, ) where Fl <: AbstractFloat ``` -------------------------------- ### StateSpaceModels.fit! Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual The `fit!` function estimates state-space model parameters via maximum likelihood, allowing customization of the filter and optimizer. ```APIDOC ## `StateSpaceModels.fit!` — Function ### Description Estimate the state-space model parameters via maximum likelihood. The resulting optimal hyperparameters and the corresponding log-likelihood are stored within the model. You can choose the desired filter method (`UnivariateKalmanFilter`, `ScalarKalmanFilter`, etc.) and the Optim.jl optimization algorithm. ### Signature ```julia fit!( model::StateSpaceModel; filter::KalmanFilter=default_filter(model), optimizer::Optimizer=default_optimizer(model), save_hyperparameter_distribution::Bool=true ) ``` ### Parameters - **model** (`StateSpaceModel`) - Required - The state-space model to be fitted. - **filter** (`KalmanFilter`) - Optional - The filter method to use (e.g., `UnivariateKalmanFilter`, `ScalarKalmanFilter`). Defaults to `default_filter(model)`. - **optimizer** (`Optimizer`) - Optional - The Optim.jl optimization algorithm to use. Defaults to `default_optimizer(model)`. - **save_hyperparameter_distribution** (`Bool`) - Optional - Whether to save the hyperparameter distribution. Defaults to `true`. ### Example ```julia julia> model = LocalLevel(rand(100)) LocalLevel julia> fit!(model) LocalLevel julia> model = LocalLinearTrend(LinRange(1, 100, 100) + rand(100)) LocalLinearTrend julia> fit!(model; optimizer = Optimizer(StateSpaceModels.Optim.NelderMead())) LocalLinearTrend ``` ``` -------------------------------- ### Cite StateSpaceModels.jl with BibTeX Source: https://lampspuc.github.io/StateSpaceModels.jl/stable BibTeX entry for citing StateSpaceModels.jl in academic work. ```bibtex @article{SaavedraBodinSouto2019, title={StateSpaceModels.jl: a Julia Package for Time-Series Analysis in a State-Space Framework}, author={Raphael Saavedra and Guilherme Bodin and Mario Souto}, journal={arXiv preprint arXiv:1908.01757}, year={2019} } ``` -------------------------------- ### Unconstrain variance with unconstrain_variance! Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Map an unconstrained hyperparameter ψ∗∈R to a constrained hyperparameter ψ∈R+. The mapping is ψ∗=√ψ. ```julia unconstrain_variance!(model::StateSpaceModel, str::String) ``` -------------------------------- ### get_innovations Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Retrieves the innovations from the Kalman filter output. ```APIDOC ## get_innovations ### Description Returns the innovations `v` obtained with the Kalman filter. ### Method Function call ### Endpoint `get_innovations` ### Returns - **v** - Innovations from the Kalman filter. ``` -------------------------------- ### StateSpaceModels.auto_ets Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Automatically selects the best ExponentialSmoothing model based on AIC. ```APIDOC ## auto_ets(y::Vector{Fl}; seasonal::Int = 0) where Fl ### Description Automatically fits the best `ExponentialSmoothing` model according to the best AIC between the models: ETS(A, N, N), ETS(A, A, N), ETS(A, Ad, N). If the user provides the time series seasonality it will search between the models: ETS(A, N, A), ETS(A, A, A), ETS(A, Ad, A). ### Method Function ### Endpoint `StateSpaceModels.auto_ets(y::Vector{Fl}; seasonal::Int = 0) where Fl` ### Parameters - **y** (Vector{Fl}) - Required - The time series data. - **seasonal** (Int) - Optional - The seasonal period (default: 0). ### References - Rob J. Hyndman, and George Athanasopoulos. Forecasting: Principles and Practice. 2nd ed. OTexts, 2018. ``` -------------------------------- ### Load and prepare Finland road traffic fatalities data Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Loads the vehicle fatalities dataset and computes the natural logarithm of the fatalities column. The result is stored in `log_ff` for subsequent modeling. ```julia using StateSpaceModels, CSV, DataFrames df = CSV.File(StateSpaceModels.VEHICLE_FATALITIES) |> DataFrame log_ff = log.(df.ff) ``` -------------------------------- ### Load Nile river flow data with CSV and DataFrames Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Loads the built-in Nile river annual flow dataset using CSV.File and converts it to a DataFrame. The data contains 100 rows with columns for year (Date) and flow (Float64). ```julia using CSV, DataFrames nile = CSV.File(StateSpaceModels.NILE) |> DataFrame ``` -------------------------------- ### StateSpaceModels.has_fit_methods Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual The `has_fit_methods` function checks whether a given state-space model type supports the `fit!` operation. ```APIDOC ## `StateSpaceModels.has_fit_methods` — Function ### Description Verify if a certain `StateSpaceModel` has the necessary methods to perform `fit!`. ### Signature ```julia has_fit_methods(model_type::Type{<:StateSpaceModel}) -> Bool ``` ### Parameters - **model_type** (`Type{<:StateSpaceModel}`) - Required - The type of the state-space model to check. ### Returns - **Bool** - `true` if the model type has the necessary methods for `fit!`, `false` otherwise. ``` -------------------------------- ### Simulate scenarios function signature Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Samples n_scenarios future scenarios via Monte Carlo simulation for steps_ahead using the desired filter. Returns a 3-dimensional array of floats. ```julia simulate_scenarios( model::StateSpaceModel, steps_ahead::Int, n_scenarios::Int; filter::KalmanFilter=default_filter(model) ) -> Array{<:AbstractFloat, 3} ``` -------------------------------- ### Fit LocalLinearTrend model to log fatalities Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Fits a LocalLinearTrend model to the log-transformed fatalities data. The model is stored in `model` and then fitted using `fit!`. ```julia model = LocalLinearTrend(log_ff) fit!(model) ``` -------------------------------- ### StateSpaceModels.Optimizer Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual The `Optimizer` type wraps Optim.jl optimizers for use in StateSpaceModels.jl, providing a straightforward way to select optimization algorithms. ```APIDOC ## `StateSpaceModels.Optimizer` — Type ### Description An Optim.jl wrapper to make the choice of the optimizer straightforward in StateSpaceModels.jl. Users can choose among all suitable optimizers in Optim.jl using very similar syntax. ### Example ```julia julia> using Optim # use a semicolon to avoid displaying the big log julia> opt = Optimizer(Optim.BFGS(), Optim.Options(show_trace = true)); ``` ``` -------------------------------- ### Filter and smooth Nile flow with missing values Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Runs the Kalman filter and smoother on the fitted model, then extracts the smoothed state. The exact same code works as when there are no missing values. ```julia filter_output = kalman_filter(model) smoother_output = kalman_smoother(model) get_smoothed_state(smoother_output) ``` -------------------------------- ### unconstrain_box! Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Applies inverse box constraint mapping to a hyperparameter. ```APIDOC ## unconstrain_box!(model::StateSpaceModel, str::String, lb::Fl, ub::Fl) where Fl ### Description Map an unconstrained hyperparameter ψ∗∈R to a constrained hyperparameter ψ∈[lb,ub]. The mapping is ψ∗=−lnub−lbψ−lb−1. ### Method Function ### Endpoint `StateSpaceModels.unconstrain_box!(model::StateSpaceModel, str::String, lb::Fl, ub::Fl) where Fl` ### Parameters - **model** (`StateSpaceModel`) - Required - The state space model. - **str** (`String`) - Required - The name of the hyperparameter to unconstrain. - **lb** (`Fl`) - Required - Lower bound of the box constraint. - **ub** (`Fl`) - Required - Upper bound of the box constraint. ### Response Returns the modified model. ``` -------------------------------- ### Extract smoothed slope from LocalLinearTrend model Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/examples Runs the Kalman smoother on the fitted model and extracts the smoothed state for the slope component (second column). The resulting vector indicates the trend direction over time. ```julia smoother_output = kalman_smoother(model) get_smoothed_state(smoother_output)[:, 2] ``` -------------------------------- ### LinearRegression Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor for the LinearRegression model type. ```APIDOC ## LinearRegression ### Description Constructs a linear regression state-space model where the observation is a linear combination of explanatory variables with time-varying coefficients that follow a random walk. ### Constructor `LinearRegression(X::Matrix{Fl}, y::Vector{Fl}) where Fl` ### Parameters - **X** (Matrix{Fl}) - Required - The matrix of explanatory variables. - **y** (Vector{Fl}) - Required - The response variable. ### Example ```julia julia> model = LinearRegression(rand(100, 2), rand(100)) LinearRegression ``` ``` -------------------------------- ### StateSpaceModels.isfitted Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual The `isfitted` function checks whether a state-space model has been successfully fitted by verifying that no hyperparameters are `NaN`. ```APIDOC ## `StateSpaceModels.isfitted` — Function ### Description Verify if `model` is fitted, i.e., returns `false` if there is at least one `NaN` entry in the hyperparameters. ### Signature ```julia isfitted(model::StateSpaceModel) -> Bool ``` ### Parameters - **model** (`StateSpaceModel`) - Required - The state-space model to check. ### Returns - **Bool** - `true` if the model is fitted (no `NaN` hyperparameters), `false` otherwise. ``` -------------------------------- ### Unconstrain identity with unconstrain_identity! Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Map an unconstrained hyperparameter ψ∗∈R to a constrained hyperparameter ψ∈R. This function is necessary to copy values from a location to another inside `HyperParameters`. The mapping is ψ∗=ψ ```julia unconstrain_identity!(model::StateSpaceModel, str::String) ``` -------------------------------- ### ExponentialSmoothing Constructor Signature Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Constructor signature for the ExponentialSmoothing (ETS) type. Accepts a vector y and optional keyword arguments to enable a trend, damped trend, and seasonal component with a given periodicity. ```julia ExponentialSmoothing( y::Vector{Fl}; trend::Bool = false, damped_trend::Bool = false, seasonal::Int = 0 ) where Fl ``` -------------------------------- ### Constrain variance with constrain_variance! Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Map a constrained hyperparameter ψ∈R+ to an unconstrained hyperparameter ψ∗∈R. The mapping is ψ=ψ2∗ ```julia constrain_variance!(model::StateSpaceModel, str::String) ``` -------------------------------- ### StateSpaceModels.auto_arima Source: https://lampspuc.github.io/StateSpaceModels.jl/stable/manual Automatically selects the best SARIMA model based on information criteria. ```APIDOC ## auto_arima(y::Vector{Fl}; seasonal::Int = 0, max_p::Int = 5, max_q::Int = 5, max_P::Int = 2, max_Q::Int = 2, max_d::Int = 2, max_D::Int = 1, max_order::Int = 5, information_criteria::String = "aicc", allow_mean::Bool = true, show_trace::Bool = false, integration_test::String = "kpss", seasonal_integration_test::String = "seas") where Fl ### Description Automatically fits the best `SARIMA` model according to the best information criteria. ### Method Function ### Endpoint `StateSpaceModels.auto_arima(y::Vector{Fl}; seasonal::Int = 0, max_p::Int = 5, max_q::Int = 5, max_P::Int = 2, max_Q::Int = 2, max_d::Int = 2, max_D::Int = 1, max_order::Int = 5, information_criteria::String = "aicc", allow_mean::Bool = true, show_trace::Bool = false, integration_test::String = "kpss", seasonal_integration_test::String = "seas") where Fl` ### Parameters - **y** (Vector{Fl}) - Required - The time series data. - **seasonal** (Int) - Optional - The seasonal period (default: 0). - **max_p** (Int) - Optional - Maximum autoregressive order (default: 5). - **max_q** (Int) - Optional - Maximum moving average order (default: 5). - **max_P** (Int) - Optional - Maximum seasonal autoregressive order (default: 2). - **max_Q** (Int) - Optional - Maximum seasonal moving average order (default: 2). - **max_d** (Int) - Optional - Maximum number of non-seasonal differences (default: 2). - **max_D** (Int) - Optional - Maximum number of seasonal differences (default: 1). - **max_order** (Int) - Optional - Maximum order of the model (default: 5). - **information_criteria** (String) - Optional - Information criterion to use (default: "aicc"). - **allow_mean** (Bool) - Optional - Whether to allow a mean term (default: true). - **show_trace** (Bool) - Optional - Whether to show trace of the search (default: false). - **integration_test** (String) - Optional - Test for non-seasonal integration (default: "kpss"). - **seasonal_integration_test** (String) - Optional - Test for seasonal integration (default: "seas"). ### References - Hyndman, RJ and Khandakar. Automatic time series forecasting: The forecast package for R. Journal of Statistical Software, 26(3), 2008. ```