Type: | Package |
Title: | Fitting Hidden Markov Models to Financial Data |
Version: | 1.4.2 |
Description: | Fitting (hierarchical) hidden Markov models to financial data via maximum likelihood estimation. See Oelschläger, L. and Adam, T. "Detecting Bearish and Bullish Markets in Financial Time Series Using Hierarchical Hidden Markov Models" (2021, Statistical Modelling) <doi:10.1177/1471082X211034048> for a reference on the method. A user guide is provided by the accompanying software paper "fHMM: Hidden Markov Models for Financial Time Series in R", Oelschläger, L., Adam, T., and Michels, R. (2024, Journal of Statistical Software) <doi:10.18637/jss.v109.i09>. |
Language: | en-US |
URL: | https://loelschlaeger.de/fHMM/ |
BugReports: | https://github.com/loelschlaeger/fHMM/issues |
License: | GPL-3 |
Encoding: | UTF-8 |
Depends: | R (≥ 4.0.0) |
Imports: | checkmate, cli, curl, foreach, graphics, grDevices, httr, jsonlite, MASS, oeli (≥ 0.3.0), padr, pracma, progress, Rcpp, stats, utils |
LinkingTo: | Rcpp, RcppArmadillo |
Suggests: | covr, devtools, doSNOW, knitr, parallel, rmarkdown, testthat (≥ 3.0.0), tseries |
RoxygenNote: | 7.3.1 |
VignetteBuilder: | knitr |
Config/testthat/edition: | 3 |
LazyData: | true |
LazyDataCompression: | xz |
NeedsCompilation: | yes |
Packaged: | 2025-03-23 13:16:05 UTC; lennart |
Author: | Lennart Oelschläger
|
Maintainer: | Lennart Oelschläger <oelschlaeger.lennart@gmail.com> |
Repository: | CRAN |
Date/Publication: | 2025-03-24 01:00:01 UTC |
fHMM: Fitting Hidden Markov Models to Financial Data
Description
Fitting (hierarchical) hidden Markov models to financial data via maximum likelihood estimation. See Oelschläger, L. and Adam, T. "Detecting Bearish and Bullish Markets in Financial Time Series Using Hierarchical Hidden Markov Models" (2021, Statistical Modelling) doi:10.1177/1471082X211034048 for a reference on the method. A user guide is provided by the accompanying software paper "fHMM: Hidden Markov Models for Financial Time Series in R", Oelschläger, L., Adam, T., and Michels, R. (2024, Journal of Statistical Software) doi:10.18637/jss.v109.i09.
Author(s)
Maintainer: Lennart Oelschläger oelschlaeger.lennart@gmail.com (ORCID)
Authors:
Timo Adam ta59@st-andrews.ac.uk (ORCID)
Rouven Michels r.michels@uni-bielefeld.de (ORCID)
See Also
Useful links:
Check date format
Description
This function checks if the input date
has the format
"YYYY-MM-DD"
.
Usage
check_date(date)
Arguments
date |
[ |
Value
as.Date(date)
if date
has the format "YYYY-MM-DD"
.
Otherwise, the function throws an error.
Compare multiple models
Description
This function performs model comparison by comparing multiple
fHMM_model
objects with respect to
the number of model parameters,
the log-likelihood value,
the AIC value,
the BIC value.
Usage
compare_models(...)
Arguments
... |
A list of one or more objects of class |
Value
A data.frame
with models in rows and comparison criteria in columns.
Examples
### 3-state HMM with t-distributions is preferred over 2-state HMM with
### normal distributions for the DAX data based on AIC and BIC
compare_models(dax_model_2n, dax_model_3t)
Compute lengths of fine-scale chunks
Description
This helper function computes lengths of fine-scale chunks in the hierarchical case.
Usage
compute_T_star(horizon, period, dates = NULL, seed = NULL)
Arguments
horizon |
The element |
period |
The element |
dates |
A |
seed |
Set a seed for the simulation of flexible chunk lengths.
By default, |
Value
An integer
vector of fine-scale chunk sizes.
Compute confidence intervals
Description
This helper function computes confidence intervals for the estimates of an
fHMM_model
object using the inverse Fisher information.
Usage
compute_ci(x, alpha = 0.05)
Arguments
x |
An object of class |
alpha |
A |
Value
A list
containing the following elements:
-
lb
: lower bound of confidence -
estimate
: point estimate -
ub
: upper bound of confidence
Compute (pseudo-) residuals
Description
This function computes (pseudo-) residuals of an fHMM_model
object.
Usage
compute_residuals(x, verbose = TRUE)
Arguments
x |
An object of class |
verbose |
Set to |
Value
An object of class fHMM_model
with residuals included.
Examples
compute_residuals(dax_model_3t)
summary(residuals(dax_model_3t))
Deutscher Aktienindex (DAX) index data
Description
Deutscher Aktienindex (DAX) index data from 1988 to 2022 from Yahoo Finance.
Usage
dax
Format
A data.frame
with 9012 rows and the following 7 columns:
-
Date
: The date. -
Open
: Opening price. -
High
: Highest price. -
Low
: Lowest price. -
Close
: Close price adjusted for splits. -
Adj.Close
: Close price adjusted for dividends and splits. -
Volume
: Trade volume.
Details
The data was obtained via:
dax <- download_data( symbol = "^GDAXI", # DAX identifier on Yahoo Finance from = "1988-01-01", # first observation to = "2022-12-31" # last observation )
DAX 2-state HMM with normal distributions
Description
A pre-computed HMM on closing prices of the DAX from 2000 to 2022 with two hidden states and normal state-dependent distributions for demonstration purpose.
Usage
data("dax_model_2n")
Format
An object of class fHMM_model
.
Details
The model was estimated via:
controls <- set_controls( states = 2, sdds = "normal", data = list( file = dax, date_column = "Date", data_column = "Close", logreturns = TRUE, from = "2000-01-03", to = "2022-12-31" ), fit = list("runs" = 10, "gradtol" = 1e-6, "steptol" = 1e-6) ) dax_data <- prepare_data(controls) dax_model_2n <- fit_model(dax_data, seed = 1) dax_model_2n <- decode_states(dax_model_2n) dax_model_2n <- compute_residuals(dax_model_2n) summary(dax_model_2n)
DAX 3-state HMM with t-distributions
Description
A pre-computed HMM on closing prices of the DAX from 2000 to 2022 with three hidden states and state-dependent t-distributions for demonstration purpose.
Usage
data("dax_model_3t")
Format
An object of class fHMM_model
.
Details
The model was estimated via:
controls <- set_controls( states = 3, sdds = "t", data = list( file = dax, date_column = "Date", data_column = "Close", logreturns = TRUE, from = "2000-01-03", to = "2022-12-31" ), fit = list( runs = 100, iterlim = 300, gradtol = 1e-6, steptol = 1e-6 ) ) dax_data <- prepare_data(controls) dax_model_3t <- fit_model(dax_data, seed = 1, ncluster = 10) dax_model_3t <- decode_states(dax_model_3t) dax_model_3t <- compute_residuals(dax_model_3t) summary(dax_model_3t)
DAX/VW hierarchical HMM with t-distributions
Description
A pre-computed HHMM with monthly averaged closing prices of the DAX from 2010 to 2022 on the coarse scale, Volkswagen AG stock data on the fine scale, two hidden fine-scale and coarse-scale states, respectively, and state-dependent t-distributions for demonstration purpose.
Usage
data("dax_vw_model")
Format
An object of class fHMM_model
.
Details
The model was estimated via:
controls <- set_controls( hierarchy = TRUE, states = c(2, 2), sdds = c("t", "t"), period = "m", data = list( file = list(dax, vw), from = "2010-01-01", to = "2022-12-31", logreturns = c(TRUE, TRUE) ), fit = list( runs = 200, iterlim = 300, gradtol = 1e-6, steptol = 1e-6 ) ) dax_vw_data <- prepare_data(controls) dax_vw_model <- fit_model(dax_vw_data, seed = 1, ncluster = 10) dax_vw_model <- decode_states(dax_vw_model) dax_vw_model <- compute_residuals(dax_vw_model) summary(dax_vw_model)
Decode the underlying hidden state sequence
Description
This function decodes the (most likely) underlying hidden state sequence by applying the Viterbi algorithm for global decoding.
Usage
decode_states(x, verbose = TRUE)
viterbi(observations, nstates, sdd, Gamma, mu, sigma = NULL, df = NULL)
Arguments
x |
An object of class |
verbose |
Set to |
observations |
A |
nstates |
The number of states. |
sdd |
A
|
Gamma |
A transition probability |
mu |
A For the gamma- or Poisson-distribution, |
sigma |
A positive Not relevant in case of a state-dependent Poisson distribution. |
df |
A positive Only relevant in case of a state-dependent t-distribution. |
Value
An object of class fHMM_model
with decoded state sequence
included.
References
https://en.wikipedia.org/wiki/Viterbi_algorithm
Examples
decode_states(dax_model_3t)
plot(dax_model_3t, type = "ts")
viterbi(
observations = c(1, 1, 1, 10, 10, 10),
nstates = 2,
sdd = "poisson",
Gamma = matrix(0.5, 2, 2),
mu = c(1, 10)
)
Download financial data from Yahoo Finance
Description
This function downloads financial data from https://finance.yahoo.com/
and returns it as a data.frame
.
Usage
download_data(
symbol,
from = "1902-01-01",
to = Sys.Date(),
fill_dates = FALSE,
columns = c("Date", "Open", "High", "Low", "Close", "Adj.Close", "Volume")
)
Arguments
symbol |
A It must match the identifier on https://finance.yahoo.com/. |
from |
A Must not be earlier than |
to |
A Default is the current date |
fill_dates |
Set to By default, |
columns |
A By default, all columns are returned. |
Details
Yahoo Finance provides historical daily data for stocks or indices. The following data columns are available:
-
Date
: The date. -
Open
: Opening price. -
High
: Highest price. -
Low
: Lowest price. -
Close
: Close price adjusted for splits. -
Adj.Close
: Close price adjusted for dividends and splits. -
Volume
: Trade volume.
Value
A data.frame
.
Examples
### 21st century DAX closing prices
data <- download_data(
symbol = "^GDAXI", from = "2000-01-01", columns = c("Date", "Close"),
fill_dates = TRUE
)
head(data)
Set color scheme for visualizations
Description
This helper function defines a color scheme for visualizations in the {fHMM} package.
Usage
fHMM_colors(controls, colors = NULL)
Arguments
controls |
An object of class |
colors |
Either |
Value
An object of class fHMM_colors
, which is:
for
controls$hierarchy == FALSE
acharacter
vector of lengthcontrols$states
of color codes,for
controls$hierarchy == TRUE
alist
ofa
character
vector of lengthcontrols$states[1]
anda
character
matrix of dimensionscontrols$states
with color codes.
Examples
## Not run:
controls <- set_controls()
fHMM_colors(controls, colors = c("red", "blue"))
## End(Not run)
Constructor of an fHMM_data
object
Description
This function constructs an object of class fHMM_data
, which contains
the financial data for modeling.
Usage
fHMM_data(
dates,
time_points,
markov_chain,
data,
time_series,
T_star,
controls,
true_parameters
)
## S3 method for class 'fHMM_data'
print(x, ...)
## S3 method for class 'fHMM_data'
summary(object, ...)
Arguments
dates |
The dates in the empirical case. |
time_points |
The time points in the simulated case. |
markov_chain |
The states in the simulated case. |
data |
The data for modeling. |
time_series |
The data before transformation. |
T_star |
The fine-scale chunk sizes. |
controls |
The |
true_parameters |
The |
x |
An object of class |
... |
Currently not used. |
object |
An object of class |
Value
An object of class fHMM_data
, which is a list
containing
the following elements:
The
matrix
of thedates
ifsimulated = FALSE
andcontrols$data$data_column
is specified,the
matrix
of thetime_points
ifsimulated = TRUE
orcontrols$data$data_column
is not specified,the
matrix
of the simulatedmarkov_chain
ifsimulated = TRUE
,the
matrix
of the simulated or empiricaldata
used for estimation,the
matrix
time_series
of empirical data before the transformation to log-returns ifsimulated = FALSE
,the
vector
of fine-scale chunk sizesT_star
ifcontrols$hierarchy = TRUE
,the input
controls
,the
true_parameters
.
Checking events
Description
This function checks the input events
.
Usage
fHMM_events(events)
## S3 method for class 'fHMM_events'
print(x, ...)
Arguments
events |
A
|
x |
An object of class |
... |
Currently not used. |
Value
An object of class fHMM_events
.
Examples
events <- list(
dates = c("2001-09-11", "2008-09-15", "2020-01-27"),
labels = c(
"9/11 terrorist attack", "Bankruptcy Lehman Brothers",
"First COVID-19 case Germany"
)
)
events <- fHMM_events(events)
Constructor of a model object
Description
This function constructs an object of class fHMM_model
, which
contains details about the fitted (hierarchical) Hidden Markov model.
Usage
fHMM_model(
data,
estimate,
nlm_output,
estimation_time,
ll,
lls,
gradient,
inverse_fisher,
decoding
)
## S3 method for class 'fHMM_model'
print(x, ...)
## S3 method for class 'fHMM_model'
residuals(object, ...)
## S3 method for class 'fHMM_model'
summary(object, alpha = 0.05, ...)
## S3 method for class 'fHMM_model'
coef(object, alpha = 0.05, digits = 2, ...)
## S3 method for class 'fHMM_model'
AIC(object, ..., k = 2)
## S3 method for class 'fHMM_model'
BIC(object, ...)
## S3 method for class 'fHMM_model'
nobs(object, ...)
## S3 method for class 'fHMM_model'
logLik(object, ...)
npar(object, ...)
## S3 method for class 'fHMM_model'
npar(object, ...)
## S3 method for class 'fHMM_model'
predict(object, ahead = 5, alpha = 0.05, ...)
Arguments
data |
An object of class |
estimate |
A |
nlm_output |
The output of |
estimation_time |
A |
ll |
A |
lls |
A |
gradient |
A |
inverse_fisher |
A |
decoding |
A |
x , object |
An object of class |
... |
Currently not used. |
alpha |
A |
digits |
The number of decimal places. |
k |
Passed on to |
ahead |
The number of time points to predict ahead. |
Value
An object of class fHMM_model
.
Set and check model parameters
Description
This function sets and checks model parameters. Unspecified parameters are sampled.
Usage
fHMM_parameters(
controls = list(),
hierarchy = FALSE,
states = if (!hierarchy) 2 else c(2, 2),
sdds = if (!hierarchy) "normal" else c("normal", "normal"),
Gamma = NULL,
mu = NULL,
sigma = NULL,
df = NULL,
Gamma_star = NULL,
mu_star = NULL,
sigma_star = NULL,
df_star = NULL,
scale_par = c(1, 1),
seed = NULL,
check_controls = TRUE
)
## S3 method for class 'fHMM_parameters'
print(x, ...)
Arguments
controls |
Either a The
Either none, all, or selected elements can be specified. Unspecified parameters are set to their default values. Important: Specifications in |
hierarchy |
A If By default, |
states |
An If By default, |
sdds |
A
The distribution parameters, i.e. the
can be fixed via, e.g., If By default, |
Gamma , Gamma_star |
A transition probability It should have dimension
|
mu , mu_star |
A For the gamma- or Poisson-distribution, It should have length
|
sigma , sigma_star |
A positive It should have length
|
df , df_star |
A positive It should have length Only relevant in case of a state-dependent t-distribution.
|
scale_par |
A positive The first entry is the scale for
|
seed |
Sets a seed for the sampling of parameters. |
check_controls |
Either |
x |
An object of class |
... |
Currently not used. |
Details
See the vignette on the model definition for more details.
Value
An object of class fHMM_parameters
.
Examples
parameters <- fHMM_parameters(states = 2, sdds = "normal")
parameters$Gamma
Define state-dependent distributions
Description
This helper function defines state-dependent distributions.
Usage
fHMM_sdds(sdds, states)
## S3 method for class 'fHMM_sdds'
print(x, ...)
Arguments
sdds |
A
The distribution parameters, i.e. the
can be fixed via, e.g., If By default, |
states |
An If By default, |
... |
Currently not used. |
Value
A list
of length 1
(or 2
in the hierarchical case).
Each element again is a list
, containing
the
"name"
of the distributionand a list
"pars"
of its parameters, where unknown parameters are set toNULL
.
Find closest year
Description
This function takes a date
as input and returns the closest year.
Usage
find_closest_year(date)
Arguments
date |
[ |
Value
An integer
, the closest year to the input date.
Model fitting
Description
This function fits a hidden Markov model via numerical likelihood maximization.
Usage
fit_model(
data,
controls = data[["controls"]],
fit = list(),
runs = 10,
origin = FALSE,
accept = 1:3,
gradtol = 0.01,
iterlim = 100,
print.level = 0,
steptol = 0.01,
ncluster = 1,
seed = NULL,
verbose = TRUE,
initial_estimate = NULL
)
Arguments
data |
An object of class |
controls |
Either a The
Either none, all, or selected elements can be specified. Unspecified parameters are set to their default values. Important: Specifications in |
fit |
A The
Either none, all, or selected elements can be specified. Unspecified parameters are set to their default values, see below. Specifications in |
runs |
An By default, |
origin |
Only relevant for simulated data, i.e., if the In this case, a By default, |
accept |
An By default, |
gradtol |
A positive By default, |
iterlim |
A positive By default, |
print.level |
One of By default, |
steptol |
A positive By default, |
ncluster |
Set the number of clusters for parallel optimization runs to reduce
optimization time.
By default, |
seed |
Set a seed for the generation of initial values. No seed by default. |
verbose |
Set to |
initial_estimate |
Optionally defines an initial estimate for the numerical likelihood optimization. Good initial estimates can improve the optimization process. Can be:
|
Details
Multiple optimization runs starting from different initial values are
computed in parallel if ncluster > 1
.
Value
An object of class fHMM_model
.
Examples
### 2-state HMM with normal distributions
# set specifications
controls <- set_controls(
states = 2, sdds = "normal", horizon = 100, runs = 10
)
# define parameters
parameters <- fHMM_parameters(controls, mu = c(-1, 1), seed = 1)
# sample data
data <- prepare_data(controls, true_parameter = parameters, seed = 1)
# fit model
model <- fit_model(data, seed = 1)
# inspect fit
summary(model)
plot(model, "sdds")
# decode states
model <- decode_states(model)
plot(model, "ts")
# predict
predict(model, ahead = 5)
Initialization of numerical likelihood optimization
Description
This helper function generates a set of initial values for the numerical optimization of the model likelihood function.
Usage
get_initial_values(
data,
ncluster = 1,
seed = NULL,
verbose = TRUE,
initial_estimate = NULL
)
Arguments
data |
An object of class |
ncluster |
Set the number of clusters for parallel optimization runs to reduce
optimization time.
By default, |
seed |
Set a seed for the generation of initial values. No seed by default. |
verbose |
Set to |
initial_estimate |
Optionally defines an initial estimate for the numerical likelihood optimization. Good initial estimates can improve the optimization process. Can be:
|
Value
A list
, where each element is an object of class parUncon
.
List to vector
Description
This function produces a vector
from a list
structure and
replaces NULL
elements by NA
.
Usage
list_to_vector(x)
Arguments
x |
[ |
Value
A numeric
.
Log-likelihood function of an (H)HMM
Description
This function computes the log-likelihood value of a (hierarchical) hidden Markov model for given observations and parameter values.
Usage
ll_hmm(
parUncon,
observations,
controls = list(),
hierarchy = FALSE,
states = if (!hierarchy) 2 else c(2, 2),
sdds = if (!hierarchy) "normal" else c("normal", "normal"),
negative = FALSE,
check_controls = TRUE
)
Arguments
parUncon |
An object of class
|
observations |
A In the hierarchical case ( |
controls |
Either a The
Either none, all, or selected elements can be specified. Unspecified parameters are set to their default values. Important: Specifications in |
hierarchy |
A If By default, |
states |
An If By default, |
sdds |
A
The distribution parameters, i.e. the
can be fixed via, e.g., If By default, |
negative |
Either |
check_controls |
Either |
Value
The (negative) log-likelihood value.
Examples
### HMM log-likelihood
controls <- set_controls(states = 2, sdds = "normal")
parameters <- fHMM_parameters(controls)
parUncon <- par2parUncon(parameters, controls)
observations <- 1:10
ll_hmm(parUncon, observations, controls)
### HHMM log-likelihood
controls <- set_controls(
hierarchy = TRUE, states = c(2, 2), sdds = c("normal", "normal")
)
parameters <- fHMM_parameters(controls)
parUncon <- par2parUncon(parameters, controls)
observations <- matrix(dnorm(110), ncol = 11, nrow = 10)
ll_hmm(parUncon, observations, controls)
Negative log-likelihood function of an HHMM
Description
This function computes the negative log-likelihood of an HHMM.
Usage
nLL_hhmm(parUncon, observations, controls)
Arguments
parUncon |
An object of class |
observations |
The matrix of the simulated or empirical data used for estimation. |
controls |
An object of class |
Value
The negative log-likelihood value.
Negative log-likelihood function of an HMM
Description
This function computes the negative log-likelihood of an HMM.
Usage
nLL_hmm(parUncon, observations, controls)
Arguments
parUncon |
An object of class |
observations |
The vector of the simulated or empirical data used for estimation. |
controls |
An object of class |
Value
The negative log-likelihood value.
Create labels for estimated parameters
Description
This helper function creates labels for the estimated HMM parameters.
Usage
parameter_labels(controls, expected_length = NULL)
Arguments
controls |
An object of class |
expected_length |
The expected output length. If |
Value
A character
vector of parameter labels.
Parameter transformations
Description
These helper functions transform model parameters between
constrained spaces (suffix
*Con
)and unconstrained spaces (suffix
*Uncon
).
The former is useful for interpretation, the latter for unconstrained optimization.
Usage
par2parUncon(par, controls, use_parameter_labels = TRUE)
parUncon2parCon(
parUncon,
controls,
use_parameter_labels = TRUE,
numerical_safeguard = FALSE
)
parCon2par(parCon, controls, use_parameter_labels = TRUE)
par2parCon(par, controls, use_parameter_labels = TRUE)
parCon2parUncon(parCon, controls, use_parameter_labels = TRUE)
parUncon2par(
parUncon,
controls,
use_parameter_labels = TRUE,
numerical_safeguard = FALSE
)
muCon2muUncon(muCon, link, prefix = "muUncon_", use_parameter_labels = TRUE)
muUncon2muCon(muUncon, link, prefix = "muCon_", use_parameter_labels = TRUE)
sigmaCon2sigmaUncon(
sigmaCon,
prefix = "sigmaUncon_",
use_parameter_labels = TRUE
)
sigmaUncon2sigmaCon(
sigmaUncon,
prefix = "sigmaCon_",
use_parameter_labels = TRUE,
numerical_safeguard = FALSE
)
dfCon2dfUncon(dfCon, prefix = "dfUncon_", use_parameter_labels = TRUE)
dfUncon2dfCon(
dfUncon,
prefix = "dfCon_",
use_parameter_labels = TRUE,
numerical_safeguard = FALSE
)
Gamma2gammasCon(
Gamma,
prefix = "gammasCon_",
use_parameter_labels = TRUE,
numerical_safeguard = FALSE
)
Gamma2gammasUncon(Gamma, prefix = "gammasUncon_", use_parameter_labels = TRUE)
gammasCon2Gamma(gammasCon, dim, prefix = "state_", use_parameter_labels = TRUE)
gammasCon2gammasUncon(
gammasCon,
dim,
prefix = "gammasUncon_",
use_parameter_labels = TRUE
)
gammasUncon2Gamma(
gammasUncon,
dim,
prefix = "state_",
use_parameter_labels = TRUE,
numerical_safeguard = FALSE
)
gammasUncon2gammasCon(
gammasUncon,
dim,
prefix = "gammasCon_",
use_parameter_labels = TRUE,
numerical_safeguard = FALSE
)
Arguments
par |
An object of class |
controls |
Either a The
Either none, all, or selected elements can be specified. Unspecified parameters are set to their default values. Important: Specifications in |
use_parameter_labels |
Either |
parUncon |
An object of class
|
numerical_safeguard |
Either
|
parCon |
An object of class
|
muCon , muUncon |
A vector of (un-) constrained expected values. |
link |
Either |
prefix |
A |
sigmaCon , sigmaUncon |
A vector of (un-) constrained standard deviations. |
dfCon , dfUncon |
A vector of (un-) constrained degrees of freedom. |
gammasCon , gammasUncon |
A vector of (un-) constrained non-diagonal transition probabilities. |
dim |
An |
Value
For par2parUncon
: a vector of unconstrained model parameters.
For parUncon2parCon
: a vector of constrained model parameters.
For parCon2par
: an object of class fHMM_parameters
.
For par2parCon
: a vector of constrained model parameters.
For parCon2parUncon
: a vector of unconstrained model parameters.
For parUncon2par
: an object of class fHMM_parameters
.
For muCon2muUncon
: a vector of unconstrained expected values.
For muUncon2muCon
: a vector of constrained expected values.
For sigmaCon2sigmaUncon
: a vector of unconstrained standard
deviations.
For sigmaUncon2sigmaCon
: a vector of constrained standard deviations.
For dfCon2dfUncon
: a vector of unconstrained degrees of freedom.
For dfUncon2dfCon
: a vector of constrained degrees of freedom.
For Gamma2gammasCon
: a vector of constrained non-diagonal matrix
elements (column-wise).
For Gamma2gammasUncon
: a vector of unconstrained non-diagonal matrix
elements (column-wise).
For gammasCon2Gamma
: a transition probability matrix.
For gammasCon2gammasUncon
: a vector of unconstrained non-diagonal
elements of the transition probability matrix.
For gammasUncon2Gamma
: a transition probability matrix.
For gammasUncon2gammasCon
: a vector of constrained non-diagonal
elements of a transition probability matrix.
Plot method for an object of class fHMM_data
Description
This function is the plot method for an object of class fHMM_data
.
Usage
## S3 method for class 'fHMM_data'
plot(x, events = NULL, title = NULL, from = NULL, to = NULL, ...)
Arguments
x |
An object of class |
events |
An object of class |
title |
Optionally a |
from |
Optionally a |
to |
Optionally a |
... |
Currently not used. |
Value
No return value. Draws a plot to the current device.
Examples
plot(dax_model_3t$data, title = "DAX time series")
Plot method for an object of class fHMM_model
Description
This function is the plot method for an object of class
fHMM_model
.
Usage
## S3 method for class 'fHMM_model'
plot(
x,
plot_type = "ts",
events = NULL,
colors = NULL,
ll_relative = TRUE,
title = NULL,
from = NULL,
to = NULL,
...
)
Arguments
x |
An object of class |
plot_type |
A character (vector), specifying the type of plot and can be one (or more) of
|
events |
An object of class |
colors |
Either |
ll_relative |
A |
title |
Optionally a |
from |
Optionally a |
to |
Optionally a |
... |
Currently not used. |
Value
No return value. Draws a plot to the current device.
Visualization of log-likelihood values
Description
This function plots the log-likelihood values of the different optimization runs.
Usage
plot_ll(lls, ll_relative = TRUE)
Arguments
lls |
A |
ll_relative |
A |
Value
No return value. Draws a plot to the current device.
Visualize pseudo residuals
Description
This function visualizes the pseudo residuals.
Usage
plot_pr(residuals, hierarchy)
Arguments
residuals |
An object of class |
hierarchy |
The element |
Value
No return value. Draws a plot to the current device.
Visualization of estimated state-dependent distributions
Description
This function plots the estimated state-dependent distributions.
Usage
plot_sdds(est, true = NULL, controls, colors)
Arguments
est |
An object of class |
true |
Either |
controls |
An object of class |
colors |
Either |
Value
No return value. Draws a plot to the current device.
Visualize time series
Description
This function visualizes the data time series.
Usage
plot_ts(
data,
decoding,
colors,
events = NULL,
title = NULL,
from = NULL,
to = NULL
)
Arguments
data |
An object of class |
decoding |
Either |
colors |
Either |
events |
An object of class |
title |
Optionally a |
from |
Optionally a |
to |
Optionally a |
Value
No return value. Draws a plot to the current device.
Prepare data
Description
This function simulates or reads financial data for the {fHMM} package.
Usage
prepare_data(controls, true_parameters = NULL, seed = NULL)
Arguments
controls |
An object of class |
true_parameters |
An object of class |
seed |
Set a seed for the data simulation. No seed per default. |
Value
An object of class fHMM_data
.
Examples
controls <- set_controls()
data <- prepare_data(controls)
class(data)
summary(data)
Read data
Description
This helper function reads financial data for the {fHMM} package.
Usage
read_data(controls)
Arguments
controls |
An object of class |
Value
A list
containing the following elements:
the
matrix
of thedates
ifcontrols$simulated = FALSE
andcontrols$data$data_column
is specified,the
matrix
of thetime_points
ifcontrols$simulated = TRUE
orcontrols$data$data_column
is not specified,the
matrix
of the empiricaldata
used for estimation,the
matrix
namedtime_series
of empirical data before the transformation to log-returns,the
vector
of fine-scale chunk sizesT_star
ifcontrols$hierarchy = TRUE
.
Reorder estimated states
Description
This function reorders the estimated states, which can be useful for a comparison to true parameters or the interpretation of states.
Usage
reorder_states(x, state_order = "mean")
Arguments
x |
An object of class |
state_order |
Either
|
Value
An object of class fHMM_model
, in which states are reordered.
Examples
dax_model_3t_reordered <- reorder_states(dax_model_3t, state_order = 3:1)
Define and validate model specifications
Description
This function defines and validates specifications for model estimation.
Usage
set_controls(
controls = list(),
hierarchy = FALSE,
states = if (!hierarchy) 2 else c(2, 2),
sdds = if (!hierarchy) "normal" else c("normal", "normal"),
horizon = if (!hierarchy) 100 else c(100, 30),
period = NA,
data = NA,
file = NA,
date_column = if (!hierarchy) "Date" else c("Date", "Date"),
data_column = if (!hierarchy) "Close" else c("Close", "Close"),
from = NA,
to = NA,
logreturns = if (!hierarchy) FALSE else c(FALSE, FALSE),
merge = function(x) mean(x),
fit = list(),
runs = 10,
origin = FALSE,
accept = 1:3,
gradtol = 0.01,
iterlim = 100,
print.level = 0,
steptol = 0.01
)
validate_controls(controls)
## S3 method for class 'fHMM_controls'
print(x, ...)
## S3 method for class 'fHMM_controls'
summary(object, ...)
Arguments
controls |
Either a The
Either none, all, or selected elements can be specified. Unspecified parameters are set to their default values. Important: Specifications in |
hierarchy |
A If By default, |
states |
An If By default, |
sdds |
A
The distribution parameters, i.e. the
can be fixed via, e.g., If By default, |
horizon |
A If By default, If |
period |
Only relevant if In this case, a
By default, |
data |
Either The
Either none, all, or selected elements can be specified. Unspecified parameters are set to their default values, see below. Specifications in |
file |
A If Alternatively, it can be a |
date_column |
A If By default, |
data_column |
A If By default, |
from |
A |
to |
A |
logreturns |
A If By default, |
merge |
Only relevant if In this case, a
|
fit |
A The
Either none, all, or selected elements can be specified. Unspecified parameters are set to their default values, see below. Specifications in |
runs |
An By default, |
origin |
Only relevant for simulated data, i.e., if the In this case, a By default, |
accept |
An By default, |
gradtol |
A positive By default, |
iterlim |
A positive By default, |
print.level |
One of By default, |
steptol |
A positive By default, |
x , object |
An object of class |
... |
Currently not used. |
Details
See the vignette on controls for more details.
Value
An object of class fHMM_controls
, which is a list
that contains
model and estimation specifications.
Examples
# 2-state HMM with t-distributions for simulated data
set_controls(
states = 2, # the number of states
sdds = "t", # the state-dependent distribution
runs = 50 # the number of optimization runs
)
# 3-state HMM with normal distributions for the DAX closing prices
set_controls(
states = 3,
sdds = "normal",
file = download_data("^GDAXI"), # the data set
date_column = "Date", # the column with the dates
data_column = "Close" # the column with the data
)
# hierarchical HMM with Gamma and Poisson state distributions
set_controls(
hierarchy = TRUE, # defines a hierarchy
states = c(3, 2), # coarse scale and fine scale states
sdds = c("gamma", "poisson"), # distributions for both layers
horizon = c(100, NA), # 100 simulated coarse-scale data points
period = "m" # monthly simulated fine-scale data
)
# hierarchical HMM with data from .csv-file
set_controls(
hierarchy = TRUE,
states = c(3, 2),
sdds = c("t", "t"),
file = c(
system.file("extdata", "dax.csv", package = "fHMM"),
system.file("extdata", "dax.csv", package = "fHMM")
),
date_column = c("Date", "Date"),
data_column = c("Close", "Close"),
logreturns = c(TRUE, TRUE)
)
Simulated 2-state HMM with gamma distributions
Description
A pre-computed 2-state HMM with state-dependent gamma distributions with
means fixed to 0.5
and 2
on 500
simulated observations.
Usage
data("sim_model_2gamma")
Format
An object of class fHMM_model
.
Details
The model was estimated via:
controls <- set_controls( states = 2, sdds = "gamma(mu = 1|2)", horizon = 200, runs = 10 ) pars <- fHMM_parameters( controls = controls, Gamma = matrix(c(0.9, 0.2, 0.1, 0.8), nrow = 2), sigma = c(0.5, 1), seed = 1 ) data_sim <- prepare_data(controls, true_parameters = pars, seed = 1) sim_model_2gamma <- fit_model(data_sim, seed = 1) sim_model_2gamma <- decode_states(sim_model_2gamma) sim_model_2gamma <- compute_residuals(sim_model_2gamma) summary(sim_model_2gamma)
Simulate data
Description
This helper function simulates HMM data.
Usage
simulate_hmm(
controls = list(),
hierarchy = FALSE,
states = if (!hierarchy) 2 else c(2, 2),
sdds = if (!hierarchy) "normal" else c("normal", "normal"),
horizon = if (!hierarchy) 100 else c(100, 30),
period = NA,
true_parameters = fHMM_parameters(controls = controls, hierarchy = hierarchy, states =
states, sdds = sdds),
seed = NULL
)
Arguments
controls |
Either a The
Either none, all, or selected elements can be specified. Unspecified parameters are set to their default values. Important: Specifications in |
hierarchy |
A If By default, |
states |
An If By default, |
sdds |
A
The distribution parameters, i.e. the
can be fixed via, e.g., If By default, |
horizon |
A If By default, If |
period |
Only relevant if In this case, a
By default, |
true_parameters |
An object of class |
seed |
Set a seed for the data simulation. No seed per default. |
Value
A list
containing the following elements:
-
time_points
, thevector
(ormatrix
in the hierarchical case) of time points, -
markov_chain
, thevector
(ormatrix
in the hierarchical case) of the simulated states, -
data
, thevector
(ormatrix
in the hierarchical case) of the simulated state-dependent observations, -
T_star
, thenumeric
vector of fine-scale chunk sizes in the hierarchical case
Examples
simulate_hmm(states = 2, sdds = "normal", horizon = 10)
Simulate state-dependent observations
Description
This function simulates state-dependent observations.
Usage
simulate_observations(
markov_chain,
sdd,
mu,
sigma = NULL,
df = NULL,
seed = NULL,
total_length = length(markov_chain)
)
Arguments
markov_chain |
A |
sdd |
A |
mu |
A |
sigma |
A |
df |
A |
seed |
Sets a seed for the observation sampling. |
total_length |
An |
Value
A numeric
vector of length total_length
, where the first
length(markov_chain)
elements are numeric values and the last
total_length - length(markov_chain)
elements are NA_real_
.
Standard & Poor’s 500 (S&P 500) index data
Description
Standard & Poor’s 500 (S&P 500) index data from 1928 to 2022 from Yahoo Finance.
Usage
spx
Format
A data.frame
with 23864 rows and the following 7 columns:
-
Date
: The date. -
Open
: Opening price. -
High
: Highest price. -
Low
: Lowest price. -
Close
: Close price adjusted for splits. -
Adj.Close
: Close price adjusted for dividends and splits. -
Volume
: Trade volume.
Details
The data was obtained via:
spx <- download_data( symbol = "^GSPC", # S&P 500 identifier on Yahoo Finance from = "1928-01-01", # first observation to = "2022-12-31" # last observation )
Unemployment rate data USA
Description
The monthly unemployment rate in the USA from 1955 to 2022 on a daily observation basis.
Usage
unemp
Format
A data.frame
with 24806 rows and the following 3 columns:
-
date
: The date. -
rate
: The unemployment rate. -
rate_diff
: The difference rate to previous month.
Source
OECD (2023), Unemployment rate (indicator). doi: 10.1787/52570002-en (Accessed on 18 January 2023) https://www.oecd.org/en/data/indicators/unemployment-rate.html
Unemployment rate and S&P 500 hierarchical HMM
Description
A pre-computed HHMM with monthly unemployment rate in the US on the coarse scale using 3 states and S&P 500 index data on the fine scale using 2 states from 1970 to 2020 for demonstration purpose.
Usage
data("unemp_spx_model_3_2")
Format
An object of class fHMM_model
.
Details
The model was estimated via:
controls <- list( hierarchy = TRUE, states = c(3, 2), sdds = c("t", "t"), period = "m", data = list( file = list(unemp, spx), data_column = c("rate_diff", "Close"), date_column = c("date", "Date"), from = "1970-01-01", to = "2020-01-01", logreturns = c(FALSE, TRUE) ), fit = list(runs = 50, iterlim = 1000, gradtol = 1e-6, steptol = 1e-6) ) controls <- set_controls(controls) unemp_spx_data <- prepare_data(controls) unemp_spx_model_3_2 <- fit_model(unemp_spx_data, seed = 1, ncluster = 10) unemp_spx_model_3_2 <- decode_states(unemp_spx_model_3_2) unemp_spx_model_3_2 <- compute_residuals(unemp_spx_model_3_2) summary(unemp_spx_model_3_2) state_order <- matrix(c(3, 2, 1, 2, 2, 2, 1, 1, 1), 3, 3) unemp_spx_model_3_2 <- reorder_states(unemp_spx_model_3_2, state_order)
Volkswagen AG (VW) stock data
Description
Volkswagen AG (VW) stock data from 1998 to 2022 from Yahoo Finance.
Usage
vw
Format
A data.frame
with 6260 rows and the following 7 columns:
-
Date
: The date. -
Open
: Opening price. -
High
: Highest price. -
Low
: Lowest price. -
Close
: Close price adjusted for splits. -
Adj.Close
: Close price adjusted for dividends and splits. -
Volume
: Trade volume.
Details
The data was obtained via:
vw <- download_data( symbol = "VOW3.DE", # Volkswagen AG identifier on Yahoo Finance from = "1988-07-22", # first observation to = "2022-12-31" # last observation )