Title: | Bayesian Estimation of (Sparse) Latent Factor Stochastic Volatility Models |
---|---|
Description: | Markov chain Monte Carlo (MCMC) sampler for fully Bayesian estimation of latent factor stochastic volatility models with interweaving <doi:10.1080/10618600.2017.1322091>. Sparsity can be achieved through the usage of Normal-Gamma priors on the factor loading matrix <doi:10.1016/j.jeconom.2018.11.007>. |
Authors: | Gregor Kastner [aut, cre] , Darjus Hosszejni [ctb] , Luis Gruber [ctb] |
Maintainer: | Gregor Kastner <[email protected]> |
License: | GPL (>= 2) |
Version: | 1.1.0 |
Built: | 2024-10-31 22:09:46 UTC |
Source: | CRAN |
This packages provides a Markov chain Monte Carlo (MCMC) sampler for fully Bayesian estimation of latent factor stochastic volatility models. Sparsity can be achieved through the usage of Normal-Gamma priors on the factor loadings matrix.
In recent years, multivariate factor stochastic volatility (SV) models have been increasingly used to analyze financial and economic time series because they can capture joint (co-)volatility dynamics by a small number of latent time-varying factors. The main advantage of such a model is its parsimony, as all variances and covariances of a time series vector are governed by a low-dimensional common factor with the components following independent SV models. For problems of this kind, MCMC is a very efficient estimation method, it is however associated with a considerable computational burden when the number of assets is moderate to large. To overcome this, the latent volatility states are drawn "all without a loop" (AWOL), ancillarity-sufficiency interweaving strategies (ASIS) are applied to sample the univariate components as well as the factor loadings. Thus, this package can be applied directly estimate time-varying covariance and correlation matrices for medium-and high-dimensional time series. To guarantee sparsity, a hierarchical Normal-Gamma prior can be used for the factor loadings matrix which shrinks the unnecessary factor loadings towards zero.
This package is currently in active development; the interface of some of the functions might change. Moreover, even though I tried to carefully check everything, factorstochvol may still contain typos, inconsistencies, or even bugs. Your comments and suggestions are warmly welcome!
Gregor Kastner [email protected]
Kastner, G., Frühwirth-Schnatter, S., and Lopes, H.F. (2017). Efficient Bayesian Inference for Multivariate Factor Stochastic Volatility Models. Journal of Computational and Graphical Statistics, 26(4), 905–917, doi:10.1080/10618600.2017.1322091.
Kastner, G. (2019). Sparse Bayesian Time-Varying Covariance Estimation in Many Dimensions. Journal of Econometrics, 210(1), 98–115. doi:10.1016/j.jeconom.2018.11.007.
Kastner, G. and Frühwirth-Schnatter, S. (2014). Ancillarity-Sufficiency Interweaving Strategy (ASIS) for Boosting MCMC Estimation of Stochastic Volatility Models. Computational Statistics and Data Analysis, doi:10.1016/j.csda.2013.01.002.
set.seed(1) # simulate data from a (small) factor SV model: sim <- fsvsim(series = 5, factors = 2) # estimate the model (CAVEAT: only few draws!) res <- fsvsample(sim$y, factors = 2, draws = 2000, burnin = 500) # plot implied volas overtime: voltimeplot(res) # plot correlation matrix at some points in time: par(mfrow = c(2,2)) corimageplot(res, seq(1, nrow(sim$y), length.out = 4), fsvsimobj = sim, plotCI = 'circle', plotdatedist = -2) # plot (certain) covariances and correlations over time par(mfrow = c(2,1)) covtimeplot(res, 1) cortimeplot(res, 1) # plot (all) correlations over time corplot(res, fsvsimobj = sim, these = 1:10) # plot factor loadings par(mfrow = c(1,1)) facloadpointplot(res, fsvsimobj = sim) facloadpairplot(res) facloadcredplot(res) facloaddensplot(res, fsvsimobj = sim) # plot latent log variances logvartimeplot(res, fsvsimobj = sim, show = "fac") logvartimeplot(res, fsvsimobj = sim, show = "idi") # plot communalities over time comtimeplot(res, fsvsimobj = sim, show = 'joint') comtimeplot(res, fsvsimobj = sim, show = 'series')
set.seed(1) # simulate data from a (small) factor SV model: sim <- fsvsim(series = 5, factors = 2) # estimate the model (CAVEAT: only few draws!) res <- fsvsample(sim$y, factors = 2, draws = 2000, burnin = 500) # plot implied volas overtime: voltimeplot(res) # plot correlation matrix at some points in time: par(mfrow = c(2,2)) corimageplot(res, seq(1, nrow(sim$y), length.out = 4), fsvsimobj = sim, plotCI = 'circle', plotdatedist = -2) # plot (certain) covariances and correlations over time par(mfrow = c(2,1)) covtimeplot(res, 1) cortimeplot(res, 1) # plot (all) correlations over time corplot(res, fsvsimobj = sim, these = 1:10) # plot factor loadings par(mfrow = c(1,1)) facloadpointplot(res, fsvsimobj = sim) facloadpairplot(res) facloadcredplot(res) facloaddensplot(res, fsvsimobj = sim) # plot latent log variances logvartimeplot(res, fsvsimobj = sim, show = "fac") logvartimeplot(res, fsvsimobj = sim, show = "idi") # plot communalities over time comtimeplot(res, fsvsimobj = sim, show = 'joint') comtimeplot(res, fsvsimobj = sim, show = 'series')
comtimeplot
plots the communalities over time, i.e. the
series-specific percentage of variance explained through the common factors.
comtimeplot( x, fsvsimobj = NULL, show = "series", maxrows = 5, ylim = c(0, 100) )
comtimeplot( x, fsvsimobj = NULL, show = "series", maxrows = 5, ylim = c(0, 100) )
x |
Object of class |
fsvsimobj |
Object of class |
show |
Indicator whether to show joint ( |
maxrows |
Single positive integer denoting the maximum number of series in each plot. Defaults to 5. |
ylim |
Vector of length two denoting the range of the horizontal axis. Defaults to 1. |
This function displays the joint (average) communalities over time and all
series-specific communalities. If communalities haven't been stored during
sampling, comtimeplot
produces an error.
Returns x
invisibly.
Other plotting:
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
corelement
extracts the model-implied (time-varying) correlations between
(exactly) two component series.
corelement(x, i, j, these = seq_len(nrow(x$y)))
corelement(x, i, j, these = seq_len(nrow(x$y)))
x |
Object of class |
i |
Index of component series 1. |
j |
Index of component series 2. |
these |
Vector indicating which points in time should be extracted. |
Vector with the requested correlations.
Other simulation:
cormat.fsvsim()
,
covelement()
,
covmat.fsvsim()
corimageplot
plots the model-implied correlation matrices
for one or several points in time.
corimageplot( x, these = seq_len(nrow(x$y)), order = "original", these4order = these, plotdatedist = 0, plotCI = "n", date.cex = 1.5, col = NULL, fsvsimobj = NULL, plottype = "corrplot", ... )
corimageplot( x, these = seq_len(nrow(x$y)), order = "original", these4order = these, plotdatedist = 0, plotCI = "n", date.cex = 1.5, col = NULL, fsvsimobj = NULL, plottype = "corrplot", ... )
x |
Object of class |
these |
Index vector containing the time points to plot. Defaults
to |
order |
String, where |
these4order |
Index vector containing the time points used for
ordering. Probably, the default ( |
plotdatedist |
Numerical value indicating where the dates should be plotted. |
plotCI |
String. If not equal to 'n', posterior credible regions are
added (posterior mean +/- 2 posterior sd). Ignored if |
date.cex |
Size multiplier for the dates. |
col |
Color palette or NULL (the default). |
fsvsimobj |
To indicate data generating values in case of simulated
data, pass an object of type |
plottype |
Indicates which type of plot should be drawn. Can be
"corrplot" for |
... |
Additional parameters will be passed on to
|
Returns x
invisibly.
If correlations haven't been stored during sampling,
corimageplot
produces an error.
Other plotting:
comtimeplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
Generic function for extracting model-implied correlation matrices, either
from the MCMC output, or from the simulated model. Details about the
function's behavior can be found in cormat.fsvdraws
(the function invoked when applied to MCMC output) or
cormat.fsvsim
(the function invoked when applied to a
simulated model.
cormat(x, ...)
cormat(x, ...)
x |
An object of class |
... |
Arguments to be passed to methods. |
Structure containing the model-implied covariance matrix.
Other generics:
covmat()
cormat
extracts draws from the model-implied correlation matrix
from an fsvdraws
object for all points in time which have been
stored.
## S3 method for class 'fsvdraws' cormat(x, timepoints = "all", ...)
## S3 method for class 'fsvdraws' cormat(x, timepoints = "all", ...)
x |
Object of class |
timepoints |
Vector indicating at which point(s) in time (of those that have been stored during sampling) the correlation matrices should be extracted. Can also be "all" or "last". |
... |
Ignored. |
Array of dimension m
times m
times draws
times timepoints
containing the posterior draws for the
model-implied covariance matrix.
Currently crudely implemented as a double loop in pure R, may be slow.
Other extractors:
covmat.fsvdraws()
,
runningcormat()
,
runningcovmat()
set.seed(1) sim <- fsvsim(n = 500, series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1, keeptime = "all") # estimate cors <- cormat(res, "last") # extract # Trace plot of determinant of posterior correlation matrix # at time t = n = 500: detdraws <- apply(cors[,,,1], 3, det) ts.plot(detdraws) abline(h = mean(detdraws), col = 2) # posterior mean abline(h = median(detdraws), col = 4) # posterior median abline(h = det(cormat(sim, "last")[,,1]), col = 3) # implied by DGP # Trace plot of draws from posterior correlation of Sim1 and Sim2 at # time t = n = 500: ts.plot(cors[1,2,,1]) abline(h = cormat(sim, "last")[1,2,1], col = 3) # "true" value # Smoothed kernel density estimate: plot(density(cors[1,2,,1], adjust = 2)) # Summary statistics: summary(cors[1,2,,1])
set.seed(1) sim <- fsvsim(n = 500, series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1, keeptime = "all") # estimate cors <- cormat(res, "last") # extract # Trace plot of determinant of posterior correlation matrix # at time t = n = 500: detdraws <- apply(cors[,,,1], 3, det) ts.plot(detdraws) abline(h = mean(detdraws), col = 2) # posterior mean abline(h = median(detdraws), col = 4) # posterior median abline(h = det(cormat(sim, "last")[,,1]), col = 3) # implied by DGP # Trace plot of draws from posterior correlation of Sim1 and Sim2 at # time t = n = 500: ts.plot(cors[1,2,,1]) abline(h = cormat(sim, "last")[1,2,1], col = 3) # "true" value # Smoothed kernel density estimate: plot(density(cors[1,2,,1], adjust = 2)) # Summary statistics: summary(cors[1,2,,1])
cormat
extracts the model-implied (time-varying) covariance matrix
from an fsvsim
object.
## S3 method for class 'fsvsim' cormat(x, timepoints = "all", ...)
## S3 method for class 'fsvsim' cormat(x, timepoints = "all", ...)
x |
Object of class |
timepoints |
Vector indicating at which point(s) in time the correlation matrices should be extracted. Can also be "all" or "last". |
... |
Ignored. |
Array of dimension m
times m
times
length(timepoints)
, containing the model-implied correlation matrix.
Currently crudely implemented as an R loop over all time points, may be slow.
Other simulation:
corelement()
,
covelement()
,
covmat.fsvsim()
corplot
gives an overview of (certain) pairwise correlations.
Throws a warning if these haven't been stored during sampling.
corplot( x, fsvsimobj = NULL, these = 1:(ncol(x$y) * (ncol(x$y) - 1)/2), start = 1, end = nrow(x$y), maxrows = 10, ... )
corplot( x, fsvsimobj = NULL, these = 1:(ncol(x$y) * (ncol(x$y) - 1)/2), start = 1, end = nrow(x$y), maxrows = 10, ... )
x |
Object of class |
fsvsimobj |
To indicate data generating values in case of simulated
data, pass an object of type |
these |
Indicator which correlations should be plotted. Default is all. |
start |
First point in time to plot. |
end |
Last point in time to plot. |
maxrows |
The maximum number of rows per page. |
... |
Other arguments will be passed on to |
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
cortimeplot
draws correlations over time.
cortimeplot( x, series, these = seq_len(nrow(x$y)), type = "cor", statistic = "mean" ) covtimeplot( x, series, these = seq_len(nrow(x$y)), type = "cov", statistic = "mean" )
cortimeplot( x, series, these = seq_len(nrow(x$y)), type = "cor", statistic = "mean" ) covtimeplot( x, series, these = seq_len(nrow(x$y)), type = "cov", statistic = "mean" )
x |
Object of class |
series |
Single number, coercible to integer. Indicates the series relative to which correlations are drawn. |
these |
Index vector containing the time points to plot. Defaults
to |
type |
What to plot, usually "cor" or "cov". |
statistic |
Which posterior summary should be plotted, usually "mean". |
This function displays one component series' time-varying correlations with the other components series. Throws an error if correlations haven't been stored during sampling.
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
covelement
extracts the model-implied (time-varying) covariances between
(exactly) two component series.
covelement(x, i, j, these = seq_len(nrow(x$y)))
covelement(x, i, j, these = seq_len(nrow(x$y)))
x |
Object of class |
i |
Index of component series 1. |
j |
Index of component series 2. |
these |
Vector indicating which points in time should be extracted, defaults to all. |
Vector with the requested covariances.
Other simulation:
corelement()
,
cormat.fsvsim()
,
covmat.fsvsim()
Generic function for extracting model-implied covariance matrices, either
from the MCMC output, or from the simulated model. Details about the
function's behavior can be found in covmat.fsvdraws
(the function invoked when applied to MCMC output) or
covmat.fsvsim
(the function invoked when applied to a
simulated model.
covmat(x, ...)
covmat(x, ...)
x |
An object of class |
... |
Arguments to be passed to methods. |
Structure containing the model-implied covariance matrix.
Other generics:
cormat()
covmat
extracts draws from the model-implied covariance matrix
from an fsvdraws
object for all points in time which have been
stored.
## S3 method for class 'fsvdraws' covmat(x, timepoints = "all", ...)
## S3 method for class 'fsvdraws' covmat(x, timepoints = "all", ...)
x |
Object of class |
timepoints |
Vector indicating at which point(s) in time (of those that have been stored during sampling) the correlation matrices should be extracted. Can also be "all" or "last". |
... |
Ignored. |
Array of dimension m
times m
times draws
times timepoints
containing the posterior draws for the
model-implied covariance matrix.
Currently crudely implemented as a double loop in pure R, may be slow.
Other extractors:
cormat.fsvdraws()
,
runningcormat()
,
runningcovmat()
set.seed(1) sim <- fsvsim(n = 500, series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1, keeptime = "all") # estimate covs <- covmat(res, "last") # extract # Trace plot of determinant of posterior covariance matrix # at time t = n = 500: detdraws <- apply(covs[,,,1], 3, det) ts.plot(detdraws) abline(h = mean(detdraws), col = 2) # posterior mean abline(h = median(detdraws), col = 4) # posterior median abline(h = det(covmat(sim, "last")[,,1]), col = 3) # implied by DGP # Trace plot of draws from posterior covariance of Sim1 and Sim2 at # time t = n = 500: ts.plot(covs[1,2,,1]) abline(h = covmat(sim, "last")[1,2,1], col = 3) # "true" value # Smoothed kernel density estimate: plot(density(covs[1,2,,1], adjust = 2)) # Summary statistics: summary(covs[1,2,,1])
set.seed(1) sim <- fsvsim(n = 500, series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1, keeptime = "all") # estimate covs <- covmat(res, "last") # extract # Trace plot of determinant of posterior covariance matrix # at time t = n = 500: detdraws <- apply(covs[,,,1], 3, det) ts.plot(detdraws) abline(h = mean(detdraws), col = 2) # posterior mean abline(h = median(detdraws), col = 4) # posterior median abline(h = det(covmat(sim, "last")[,,1]), col = 3) # implied by DGP # Trace plot of draws from posterior covariance of Sim1 and Sim2 at # time t = n = 500: ts.plot(covs[1,2,,1]) abline(h = covmat(sim, "last")[1,2,1], col = 3) # "true" value # Smoothed kernel density estimate: plot(density(covs[1,2,,1], adjust = 2)) # Summary statistics: summary(covs[1,2,,1])
covmat
extracts the model-implied (time-varying) covariance matrix
from an fsvsim
object.
## S3 method for class 'fsvsim' covmat(x, timepoints = "all", ...)
## S3 method for class 'fsvsim' covmat(x, timepoints = "all", ...)
x |
Object of class |
timepoints |
Vector indicating at which point(s) in time the correlation matrices should be extracted. Can also be "all" or "last". |
... |
Ignored. |
Array of dimension m
times m
times
length(timepoints)
, containing the model-implied covariance matrix.
Currently crudely implemented as an R loop over all time points, may be slow.
Other simulation:
corelement()
,
cormat.fsvsim()
,
covelement()
evdiag
computes, returns, and visualizes the eigenvalues of crossprod(facload).
This can be used as a rough guide to choose the numbers of factors in a model.
evdiag(x)
evdiag(x)
x |
Object of class |
Invisibly returns a matrix with posterior samples of the eigenvalues of crossprod(facload)
Experimental feature. Please be aware that - for the sake of simplicity and interpretability - both the time-varying idiosyncratic as well as the time-varying factor volatilities are simply ignored.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
A common way to get estimates for time-varying covariance matrices is the compute the exponentially weighted empirical covariance matrix.
expweightcov(dat, alpha = 4/126, hist = 180)
expweightcov(dat, alpha = 4/126, hist = 180)
dat |
Matrix containing the data, with |
alpha |
Speed of decay. |
hist |
How far to go back in time? |
A m
times m
covariance matrix estimate.
facloadcredplot
illustrates the bivariate marginals of the
factor loadings distribution. It is a monochrome variant of
facloadpairplot
.
facloadcredplot(x, quants = c(0.01, 0.99))
facloadcredplot(x, quants = c(0.01, 0.99))
x |
Object of class |
quants |
Posterior quantiles to be plotted. |
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
facloaddensplot
draws kernel smoothed density plots of the marginal
factor loadings posterior.
facloaddensplot(x, fsvsimobj = NULL, rows = 5, thesecols = NULL, xlim = NULL)
facloaddensplot(x, fsvsimobj = NULL, rows = 5, thesecols = NULL, xlim = NULL)
x |
Object of class |
fsvsimobj |
To indicate data generating values in case of simulated
data, pass an object of type |
rows |
Number of rows per page. |
thesecols |
Which factor loadings columns should be plotted? Defaults to 1:r. |
xlim |
Vector of length two containing lower and upper bounds of the
horizontal axis. If |
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
facloadpairplot
illustrates the bivariate marginals of the
factor loadings distribution. For a monochrome variant, see
facloadcredplot
.
facloadpairplot(x, maxpoints = 500, alpha = 20/maxpoints, cex = 3)
facloadpairplot(x, maxpoints = 500, alpha = 20/maxpoints, cex = 3)
x |
Object of class |
maxpoints |
The maximum amount of posterior draws to plot. If
the number of draws stored in |
alpha |
Level of transparency. |
cex |
Controls the size of the dots. |
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
facloadpointplot
illustrates point estimates (mean, median, ...)
of the estimated factor loadings matrix.
facloadpointplot( x, fsvsimobj = NULL, statistic = "median", cex = 6.5, alpha = 0.2, allpairs = FALSE, col = NULL )
facloadpointplot( x, fsvsimobj = NULL, statistic = "median", cex = 6.5, alpha = 0.2, allpairs = FALSE, col = NULL )
x |
Object of class |
fsvsimobj |
To indicate data generating values in case of simulated
data, pass an object of type |
statistic |
Character string indicating which posterior statistic should be displayed. |
cex |
Controls the size of the dots. |
alpha |
Controls the level of transparency. |
allpairs |
Logical value; if set to TRUE, all possible pairwise combinations will be plotted. |
col |
Vector of length |
Returns x
invisibly, throws a warning if there aren't any
factors to plot.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
facloadtraceplot
draws trace plots of the factor loadings. Can be
an important tool to check MCMC convergence if inference about (certain)
factor loadings sought.
facloadtraceplot( x, fsvsimobj = NULL, thinning = NULL, maxrows = 10, ylim = NULL )
facloadtraceplot( x, fsvsimobj = NULL, thinning = NULL, maxrows = 10, ylim = NULL )
x |
Object of class |
fsvsimobj |
To indicate data generating values in case of simulated
data, pass an object of type |
thinning |
Plot every |
maxrows |
Indicates the maximum number of rows to be drawn per page. |
ylim |
Vector of length two containing lower and upper bounds of the
vertical axis. If |
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
In factor SV models, the identification of the factor loadings matrix is often chosen through a preliminary static factor analysis. After a maximum likelihood factor model is fit to the data, variables are ordered as follows: The variable with the lowest loadings on all factors except the first (relative to it) is determined to lead the first factor, the variable with the lowest loadings on all factors except the first two (relative to these) is determined to lead the second factor, etc.
findrestrict(dat, factors, transload = abs, relto = "all")
findrestrict(dat, factors, transload = abs, relto = "all")
dat |
Matrix containing the data, with |
factors |
Number of factors to be used. |
transload |
Function for transforming the estimated factor loadings before ordering. Defaults to the absolute value function. |
relto |
Can be 'none', 'current' or 'all'. If 'none', the series with the highest loadings is placed first, the series with the second highest is placed second, and so on. If 'current', the current factor loading is used as a reference, if 'all', all previous loadings are summed up to be the reference. |
A m
times factors
matrix indicating
the restrictions.
This function is automatically invoked by fsvsample if restrict is set to 'auto'.
ledermann
fsvsample
simulates from the joint posterior distribution and returns
the MCMC draws. It is the main workhorse to conduct inference for factor
stochastic volatility models in this package.
fsvsample( y, factors = 1, draws = 1000, thin = 1, burnin = 1000, restrict = "none", zeromean = TRUE, priorfacloadtype = "rowwiseng", priorfacload = 0.1, facloadtol = 1e-18, priorng = c(1, 1), priormu = c(0, 10), priorphiidi = c(10, 3), priorphifac = c(10, 3), priorsigmaidi = 1, priorsigmafac = 1, priorh0idi = "stationary", priorh0fac = "stationary", priorbeta = c(0, 10000), keeptime = "last", heteroskedastic = TRUE, priorhomoskedastic = NA, runningstore = 6, runningstorethin = 10, runningstoremoments = 2, signident = TRUE, signswitch = FALSE, interweaving = 4, quiet = FALSE, samplefac = TRUE, startfac, startpara, startlogvar, startlatent, startlogvar0, startlatent0, startfacload, startfacloadvar, expert )
fsvsample( y, factors = 1, draws = 1000, thin = 1, burnin = 1000, restrict = "none", zeromean = TRUE, priorfacloadtype = "rowwiseng", priorfacload = 0.1, facloadtol = 1e-18, priorng = c(1, 1), priormu = c(0, 10), priorphiidi = c(10, 3), priorphifac = c(10, 3), priorsigmaidi = 1, priorsigmafac = 1, priorh0idi = "stationary", priorh0fac = "stationary", priorbeta = c(0, 10000), keeptime = "last", heteroskedastic = TRUE, priorhomoskedastic = NA, runningstore = 6, runningstorethin = 10, runningstoremoments = 2, signident = TRUE, signswitch = FALSE, interweaving = 4, quiet = FALSE, samplefac = TRUE, startfac, startpara, startlogvar, startlatent, startlogvar0, startlatent0, startfacload, startfacloadvar, expert )
y |
Data matrix. Each of |
factors |
Number of latent factors to be estimated. |
draws |
Number of MCMC draws kept after burn-in. |
thin |
Single number greater or equal to 1, coercible to integer.
Every |
burnin |
Number of initial MCMC draws to be discarded. |
restrict |
Either "upper", "none", or "auto", indicating whether
the factor loadings
matrix should be restricted to have zeros above the diagonal ("upper"),
whether all elements should be estimated from the data ("none"), or
whether the function |
zeromean |
Logical. If |
priorfacloadtype |
Can be
For details please see Kastner (2019). |
priorfacload |
Either a matrix of dimensions |
facloadtol |
Minimum number that the absolute value of a factor loadings draw can take. Prevents numerical issues that can appear when strong shrinkage is enforced if chosen to be greater than zero. |
priorng |
Two-element vector with positive entries indicating the Normal-Gamma
prior's hyperhyperparameters |
priormu |
Vector of length 2 denoting prior mean and standard deviation for unconditional levels of the idiosyncratic log variance processes. |
priorphiidi |
Vector of length 2, indicating the shape parameters for the
Beta prior distributions of the transformed parameters |
priorphifac |
Vector of length 2, indicating the shape parameters for the
Beta prior distributions of the transformed parameters |
priorsigmaidi |
Vector of length |
priorsigmafac |
Vector of length |
priorh0idi |
Vector of length 1 or |
priorh0fac |
Vector of length 1 or |
priorbeta |
numeric vector of length 2, indicating the mean and
standard deviation of the Gaussian prior for the regression parameters. The
default value is |
keeptime |
Either a number coercible to a positive integer, or a string
equal to "all" or "last". If a number different from 1 is provided, only every
|
heteroskedastic |
Vector of length 1, 2, or |
priorhomoskedastic |
Only used if at least one element of
|
runningstore |
Because most machines these days do not have enough memory
to store all draws for all points in time, setting
|
runningstorethin |
How often should the calculation of running moments be conducted? Set to a value > 1 if you want to avoid time consuming calculations at every MCMC iteration. |
runningstoremoments |
Selects how many running moments (up to 4) should be calculated. |
signident |
If set to |
signswitch |
Set to |
interweaving |
The following values for interweaving the factor loadings are accepted:
For details please see Kastner et al. (2017). A value of 4 is the highly recommended default. |
quiet |
Logical value indicating whether the progress bar and other
informative output during sampling should be omitted. The default
value is |
samplefac |
If set to |
startfac |
optional numeric matrix of dimension
|
startpara |
optional numeric matrix of dimension
|
startlogvar |
optional numeric matrix of dimension
|
startlatent |
Deprecated. Please use |
startlogvar0 |
optional numeric vector of length
|
startlatent0 |
Deprecated. Please use |
startfacload |
optional numeric matrix of dimension
|
startfacloadvar |
optional numeric matrix of dimension
|
expert |
optional named list of expert parameters for the
univariate SV models (will be transformed and passed to the
|
For details concerning the factor SV algorithm please see Kastner et al. (2017), details about the univariate SV estimation can be found in Kastner and Frühwirth-Schnatter (2014).
The value returned is a list object of class fsvdraws
holding
facload
: Array containing draws from the posterior distribution of the factor loadings matrix.
fac
: Array containing factor draws from the posterior distribution.
logvar
: Array containing idiosyncratic and factor initial log variance draws.
logvar0
: Array containing idiosyncratic and factor log variance draws.
para
: Array containing parameter draws form the posterior distribution.
y
: Matrix containing the data supplied.
latestauxiliary
: List containing the latest draws of auxiliary quantities used for sampling the factor loadings matrix.
runningstore
: List whose elements contain ergodic moments of certain
variables of interest. See argument
runningstore
for details about what
is being stored here.
config
: List containing information on configuration parameters.
priors
: List containing prior hyperparameter values.
identifier
: Matrix containing the indices of the series used for
ex-post sign-identification along with the corresponding minimum distances to zero.
See signident
for details.
To display the output, use print
, plot
, and in particular specialized
extractors and printing functions.
The print
method prints a high-level overview; specialized extractors such as
covmat
or runningcovmat
are also available.
The plot
method invokes a simple covariance matrix plot; specialized plotting
functions are linked in the documentation of plot.fsvdraws
.
Kastner, G., Frühwirth-Schnatter, S., and Lopes, H.F. (2017). Efficient Bayesian Inference for Multivariate Factor Stochastic Volatility Models. Journal of Computational and Graphical Statistics, 26(4), 905–917, doi:10.1080/10618600.2017.1322091.
Kastner, G. (2019). Sparse Bayesian Time-Varying Covariance Estimation in Many Dimensions Journal of Econometrics, 210(1), 98–115, doi:10.1016/j.jeconom.2018.11.007
Kastner, G. (2016). Dealing with stochastic volatility in time series using the R package stochvol. Journal of Statistical Software, 69(5), 1–30, doi:10.18637/jss.v069.i05.
Kastner, G. and Frühwirth-Schnatter, S. (2014). Ancillarity-Sufficiency Interweaving Strategy (ASIS) for Boosting MCMC Estimation of Stochastic Volatility Models. Computational Statistics & Data Analysis, 76, 408–423, doi:10.1016/j.csda.2013.01.002.
# Load exchange rate data (ships with stochvol): data(exrates, package = "stochvol") exrates$date <- NULL # Compute the percentage log returns: dat <- 100 * logret(exrates) # We are going to fit a one-factor model so the ordering is irrelevant # NOTE that these are very few draws, you probably want more... res <- fsvsample(dat, factors = 2, draws = 2000, burnin = 1000, runningstore = 6, zeromean = FALSE) voltimeplot(res) corimageplot(res, nrow(dat), plotCI = 'circle') oldpar <- par(ask = TRUE) plot(res) par(oldpar) pairs(t(res$beta[1:4, ]))
# Load exchange rate data (ships with stochvol): data(exrates, package = "stochvol") exrates$date <- NULL # Compute the percentage log returns: dat <- 100 * logret(exrates) # We are going to fit a one-factor model so the ordering is irrelevant # NOTE that these are very few draws, you probably want more... res <- fsvsample(dat, factors = 2, draws = 2000, burnin = 1000, runningstore = 6, zeromean = FALSE) voltimeplot(res) corimageplot(res, nrow(dat), plotCI = 'circle') oldpar <- par(ask = TRUE) plot(res) par(oldpar) pairs(t(res$beta[1:4, ]))
fsvsim
generates simulated data from a factor SV model.
fsvsim( n = 1000, series = 10, factors = 1, facload = "dense", idipara, facpara, heteroskedastic = rep(TRUE, series + factors), df = Inf )
fsvsim( n = 1000, series = 10, factors = 1, facload = "dense", idipara, facpara, heteroskedastic = rep(TRUE, series + factors), df = Inf )
n |
Length of the series to be generated. |
series |
Number of component series |
factors |
Number of factors |
facload |
Can either be a matrix of dimension |
idipara |
Optional matrix of idiosyncratic SV parameters
to be used for simulation. Must have exactly three columns containing
the values of |
facpara |
Optional matrix of idiosyncratic SV parameters
to be used for simulation. Must have exactly two columns containing
the values of |
heteroskedastic |
Logical vector of length |
df |
If not equal to Inf, the factors are misspecified (come from a t distribution instead of a Gaussian). Only used for testing. |
The value returned is a list object of class fsvsim
holding
The simulated data, stored in a n
times m
matrix with
colnames 'Sim1', 'Sim2', etc.
The simulated factors, stored in a r
times r
matrix.
Factor loadings matrix.
Latent factor log-variances for times 1 to n
.
Initial factor log-variances for time 0.
The parameters of the factor volatility processes.
Latent idiosyncratic log-variances for times 1 to n
.
Initial idiosyncratic log-variances for time 0.
The parameters of the idiosyncratic volatility processes.
This object can be passed to many plotting functions to indicate the data generating processes when visualizing results.
In the static factor case, the Ledermann bound is the largest
integer rank for which a unique decomposition of the covariance
matrix is possible. (This is the largest possible number of
factors which can be used for factanal
.
ledermann(m)
ledermann(m)
m |
Number of component series. |
The Ledermann bound, a nonnegative integer.
preorder
logret
computes the log returns of a multivariate time
series, with optional de-meaning.
## S3 method for class 'matrix' logret(dat, demean = FALSE, standardize = FALSE, ...) ## S3 method for class 'data.frame' logret(dat, demean = FALSE, standardize = FALSE, ...)
## S3 method for class 'matrix' logret(dat, demean = FALSE, standardize = FALSE, ...) ## S3 method for class 'data.frame' logret(dat, demean = FALSE, standardize = FALSE, ...)
dat |
The raw data, a matrix or data frame with |
demean |
Logical value indicating whether the data should be de-meaned. |
standardize |
Logical value indicating whether the data should be standardized (in the sense that each component series has an empirical variance equal to one). |
... |
Ignored. |
Matrix containing the log returns of the (de-meaned) data.
logvartimeplot
plots the idiosyncratic and factor log-variances over time.
logvartimeplot(x, fsvsimobj = NULL, show = "both", maxrows = 5)
logvartimeplot(x, fsvsimobj = NULL, show = "both", maxrows = 5)
x |
Object of class |
fsvsimobj |
To indicate data generating values in case of simulated
data, pass an object of type |
show |
If set to "fac", only factor log-volatilities will be displayed. If set to "idi", only idiosyncratic log-volatilities will be displayed. If set to "both", factor log-volatilities will be drawn first, followed by the idiosyncratic log-volatilities. |
maxrows |
Indicates the maximum number of rows to be drawn per page. |
This function displays the posterior distribution (mean +/- 2sd
)
of log-variances of both
the factors and the idiosyncratic series.
If these haven't been stored during
sampling, logvartimeplot
produces an error.
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
orderident
provides some (very ad-hoc) methods for identifying
the ordering of the factors after running the (unrestricted) MCMC
sampler by
ordering according to the argument method
.
orderident(x, method = "summed")
orderident(x, method = "summed")
x |
Object of class |
method |
Methods currently supported:
|
Returns an object of class 'fsvdraws'
with adjusted
ordering.
Other postprocessing:
signident()
paratraceplot
draws trace plots of all parameters (mu, phi,
sigma
). Can be an important tool to check MCMC convergence if inference
about (certain) parameters is sought.
## S3 method for class 'fsvdraws' paratraceplot(x, fsvsimobj = NULL, thinning = NULL, maxrows = 3, ...)
## S3 method for class 'fsvdraws' paratraceplot(x, fsvsimobj = NULL, thinning = NULL, maxrows = 3, ...)
x |
Object of class |
fsvsimobj |
To indicate data generating values in case of simulated
data, pass an object of type |
thinning |
Plot every |
maxrows |
Indicates the maximum number of rows to be drawn per page. |
... |
Ignored. |
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
plot.fsvdraws()
,
plotalot()
,
voltimeplot()
Displays the correlation matrix at the last sampling point in time.
## S3 method for class 'fsvdraws' plot(x, quantiles = c(0.05, 0.5, 0.95), col = NULL, fsvsimobj = NULL, ...)
## S3 method for class 'fsvdraws' plot(x, quantiles = c(0.05, 0.5, 0.95), col = NULL, fsvsimobj = NULL, ...)
x |
Object of class |
quantiles |
Posterior quantiles to be visualized. Must be of length 1 or 3. |
col |
Optional color palette. |
fsvsimobj |
To indicate data generating values in case of simulated
data, pass an optional object of type |
... |
Other arguments will be passed on to corrplot. |
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plotalot()
,
voltimeplot()
Draws a collection of plots to explore the posterior distribution of a fitted factor SV model.
plotalot(x, fsvsimobj = NULL, ...)
plotalot(x, fsvsimobj = NULL, ...)
x |
Object of class |
fsvsimobj |
To indicate data generating values in case of simulated
data, pass an object of type |
... |
Other arguments will be passed on to the subfunctions. |
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
voltimeplot()
predcond
simulates from the posterior predictive distribution
of the data, conditionally on realized values of the factors. This
has the advantage that the predictive density can be written as
the product of the marginals but introduces sampling uncertainty
that grows with the number of factors used.
predcond(x, ahead = 1, each = 1, ...)
predcond(x, ahead = 1, each = 1, ...)
x |
Object of class |
ahead |
Vector of timepoints, indicating how many steps to predict ahead. |
each |
Single integer (or coercible to such) indicating how often should be drawn from the posterior predictive distribution for each draw that has been stored during MCMC sampling. |
... |
Ignored. |
List of class fsvpredcond
containing two elements:
Array containing the draws of the predictive means.
Array containing the draws of the predictive volatilities (square root of variances).
Other predictors:
predcor()
,
predcov()
,
predh()
,
predloglikWB()
,
predloglik()
,
predprecWB()
set.seed(1) sim <- fsvsim(n = 500, series = 4, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate # Predict 1 day ahead: predobj <- predcond(res, each = 5) # Draw from the predictive distribution: preddraws <- matrix(rnorm(length(predobj$means[,,1]), mean = predobj$means[,,1], sd = predobj$vols[,,1]), nrow = 4) # Visualize the predictive distribution pairs(t(preddraws), col = rgb(0,0,0,.1), pch = 16)
set.seed(1) sim <- fsvsim(n = 500, series = 4, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate # Predict 1 day ahead: predobj <- predcond(res, each = 5) # Draw from the predictive distribution: preddraws <- matrix(rnorm(length(predobj$means[,,1]), mean = predobj$means[,,1], sd = predobj$vols[,,1]), nrow = 4) # Visualize the predictive distribution pairs(t(preddraws), col = rgb(0,0,0,.1), pch = 16)
predcor
simulates from the posterior predictive distribution
of the model-implied correlation matrix.
predcor(x, ahead = 1, each = 1)
predcor(x, ahead = 1, each = 1)
x |
Object of class |
ahead |
Vector of timepoints, indicating how many steps to predict ahead. |
each |
Single integer (or coercible to such) indicating how often should be drawn from the posterior predictive distribution for each draw that has been stored during MCMC sampling. |
4-dimensional array containing draws from the predictive correlation distribution.
Currently crudely implemented as a triple loop in pure R, may be slow.
Other predictors:
predcond()
,
predcov()
,
predh()
,
predloglikWB()
,
predloglik()
,
predprecWB()
set.seed(1) sim <- fsvsim(series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate # Predict 1, 10, and 100 days ahead: predobj <- predcor(res, ahead = c(1, 10, 100)) # Trace plot of draws from posterior predictive distribution # of the correlation of Sim1 and Sim2: # (one, ten, and 100 days ahead): plot.ts(predobj[1,2,,]) # Smoothed kernel density estimates of predicted covariance # of Sim1 and Sim2: plot(density(predobj[1,2,,"1"], adjust = 2)) lines(density(predobj[1,2,,"10"], adjust = 2), col = 2) lines(density(predobj[1,2,,"100"], adjust = 2), col = 3)
set.seed(1) sim <- fsvsim(series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate # Predict 1, 10, and 100 days ahead: predobj <- predcor(res, ahead = c(1, 10, 100)) # Trace plot of draws from posterior predictive distribution # of the correlation of Sim1 and Sim2: # (one, ten, and 100 days ahead): plot.ts(predobj[1,2,,]) # Smoothed kernel density estimates of predicted covariance # of Sim1 and Sim2: plot(density(predobj[1,2,,"1"], adjust = 2)) lines(density(predobj[1,2,,"10"], adjust = 2), col = 2) lines(density(predobj[1,2,,"100"], adjust = 2), col = 3)
predcov
simulates from the posterior predictive distribution
of the model-implied covariance matrix.
predcov(x, ahead = 1, each = 1)
predcov(x, ahead = 1, each = 1)
x |
Object of class |
ahead |
Vector of timepoints, indicating how many steps to predict ahead. |
each |
Single integer (or coercible to such) indicating how often should be drawn from the posterior predictive distribution for each draw that has been stored during MCMC sampling. |
4-dimensional array containing draws from the predictive covariance distribution.
Currently crudely implemented as a triple loop in pure R, may be slow.
Other predictors:
predcond()
,
predcor()
,
predh()
,
predloglikWB()
,
predloglik()
,
predprecWB()
set.seed(1) sim <- fsvsim(series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate # Predict 1, 10, and 100 days ahead: predobj <- predcov(res, ahead = c(1, 10, 100)) # Trace plot of draws from posterior predictive distribution # of the covariance of Sim1 and Sim2: # (one, ten, and 100 days ahead): plot.ts(predobj[1,2,,]) # Smoothed kernel density estimates of predicted covariance # of Sim1 and Sim2: plot(density(predobj[1,2,,"1"], adjust = 2)) lines(density(predobj[1,2,,"10"], adjust = 2), col = 2) lines(density(predobj[1,2,,"100"], adjust = 2), col = 3)
set.seed(1) sim <- fsvsim(series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate # Predict 1, 10, and 100 days ahead: predobj <- predcov(res, ahead = c(1, 10, 100)) # Trace plot of draws from posterior predictive distribution # of the covariance of Sim1 and Sim2: # (one, ten, and 100 days ahead): plot.ts(predobj[1,2,,]) # Smoothed kernel density estimates of predicted covariance # of Sim1 and Sim2: plot(density(predobj[1,2,,"1"], adjust = 2)) lines(density(predobj[1,2,,"10"], adjust = 2), col = 2) lines(density(predobj[1,2,,"100"], adjust = 2), col = 3)
predh
simulates from the posterior predictive distribution
of the latent log-variances h, both for factors as well as for
idiosyncratic series.
predh(x, ahead = 1, each = 1)
predh(x, ahead = 1, each = 1)
x |
Object of class |
ahead |
Vector of timepoints, indicating how many steps to predict ahead. |
each |
Single integer (or coercible to such) indicating how often should be drawn from the posterior predictive distribution for each draw that has been stored during MCMC sampling. |
List of class fsvpredh
containing two elements:
Array containing the draws of the latent idiosyncratic log-volatilities.
Array containing the draws of the latent factor log-volatilities.
Other predictors:
predcond()
,
predcor()
,
predcov()
,
predloglikWB()
,
predloglik()
,
predprecWB()
set.seed(1) sim <- fsvsim(series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate # Predict 1, 10, and 100 days ahead: predobj <- predh(res, ahead = c(1, 10, 100)) # Trace plot of draws from posterior predictive factor log-variance # (one, ten, and 100 days ahead): plot.ts(predobj$factorh[1,,]) # Smoothed kernel density estimates of predicted volas: plot(density(exp(predobj$factorh[1,,"1"]/2), adjust = 2)) lines(density(exp(predobj$factorh[1,,"10"]/2), adjust = 2), col = 2) lines(density(exp(predobj$factorh[1,,"100"]/2), adjust = 2), col = 3)
set.seed(1) sim <- fsvsim(series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate # Predict 1, 10, and 100 days ahead: predobj <- predh(res, ahead = c(1, 10, 100)) # Trace plot of draws from posterior predictive factor log-variance # (one, ten, and 100 days ahead): plot.ts(predobj$factorh[1,,]) # Smoothed kernel density estimates of predicted volas: plot(density(exp(predobj$factorh[1,,"1"]/2), adjust = 2)) lines(density(exp(predobj$factorh[1,,"10"]/2), adjust = 2), col = 2) lines(density(exp(predobj$factorh[1,,"100"]/2), adjust = 2), col = 3)
predloglik
approximates the predictive log likelihood by
simulating from the predictive distribution of the covariance
matrix and evaluating the corresponding multivariate normal
distribution.
predloglik( x, y, ahead = 1, each = 1, alldraws = FALSE, indicator = rep(TRUE, ncol(y)) )
predloglik( x, y, ahead = 1, each = 1, alldraws = FALSE, indicator = rep(TRUE, ncol(y)) )
x |
Object of class |
y |
Matrix of dimension |
ahead |
Vector of timepoints, indicating how many steps to predict ahead. |
each |
Single integer (or coercible to such) indicating how often should be drawn from the posterior predictive distribution for each draw that has been stored during MCMC sampling. |
alldraws |
Should all the draws be returned or just the final results? (Can be useful to assess convergence.) |
indicator |
Logical vector of length |
Vector of length length(ahead)
with log predictive
likelihoods.
Uses predcov
. If m
is large
but only few factors are used, consider also using
predloglikWB
.
Other predictors:
predcond()
,
predcor()
,
predcov()
,
predh()
,
predloglikWB()
,
predprecWB()
set.seed(1) # Simulate a time series of length 1100: sim <- fsvsim(n = 1100, series = 3, factors = 1) y <- sim$y # Estimate using only 1000 days: res <- fsvsample(y[seq_len(1000),], factors = 1) # Evaluate the 1, 10, and 100 days ahead predictive log # likelihood: ahead <- c(1, 10, 100) scores <- predloglik(res, y[1000+ahead,], ahead = ahead, each = 10) print(scores)
set.seed(1) # Simulate a time series of length 1100: sim <- fsvsim(n = 1100, series = 3, factors = 1) y <- sim$y # Estimate using only 1000 days: res <- fsvsample(y[seq_len(1000),], factors = 1) # Evaluate the 1, 10, and 100 days ahead predictive log # likelihood: ahead <- c(1, 10, 100) scores <- predloglik(res, y[1000+ahead,], ahead = ahead, each = 10) print(scores)
predloglikWB
approximates the predictive log likelihood exploiting
the factor structure and using the Woodbury idenitity and the
corresponding matrix determinant lemma. This is recommended only
if many series and few factors are present.
predloglikWB(x, y, ahead = 1, each = 1, alldraws = FALSE)
predloglikWB(x, y, ahead = 1, each = 1, alldraws = FALSE)
x |
Object of class |
y |
Matrix of dimension |
ahead |
Vector of timepoints, indicating how many steps to predict ahead. |
each |
Single integer (or coercible to such) indicating how often should be drawn from the posterior predictive distribution for each draw that has been stored during MCMC sampling. |
alldraws |
Should all the draws be returned or just the final results? (Can be useful to assess convergence.) |
Vector of length length(ahead)
with log predictive
likelihoods.
Currently crudely implemented as a triple loop in pure R, may be slow.
Uses predprecWB
. If m
is small
or many factors are used, consider also using
predcov
.
Other predictors:
predcond()
,
predcor()
,
predcov()
,
predh()
,
predloglik()
,
predprecWB()
set.seed(1) # Simulate a time series of length 1100: sim <- fsvsim(n = 1100, series = 3, factors = 1) y <- sim$y # Estimate using only 1000 days: res <- fsvsample(y[seq_len(1000),], factors = 1) # Evaluate the 1, 10, and 100 days ahead predictive log # likelihood: ahead <- c(1, 10, 100) scores <- predloglikWB(res, y[1000+ahead,], ahead = ahead, each = 10) print(scores)
set.seed(1) # Simulate a time series of length 1100: sim <- fsvsim(n = 1100, series = 3, factors = 1) y <- sim$y # Estimate using only 1000 days: res <- fsvsample(y[seq_len(1000),], factors = 1) # Evaluate the 1, 10, and 100 days ahead predictive log # likelihood: ahead <- c(1, 10, 100) scores <- predloglikWB(res, y[1000+ahead,], ahead = ahead, each = 10) print(scores)
predprecWB
simulates from the posterior predictive distribution
of the model-implied precision matrix and its determinant
using the Woodbury matrix identity and the matrix determinant lemma
predprecWB(x, ahead = 1, each = 1)
predprecWB(x, ahead = 1, each = 1)
x |
Object of class |
ahead |
Vector of timepoints, indicating how many steps to predict ahead. |
each |
Single integer (or coercible to such) indicating how often should be drawn from the posterior predictive distribution for each draw that has been stored during MCMC sampling. |
List containing two elements:
Array containing the draws of the predicted precision matrix.
Matrix containing the draws of the determinant of the predicted precision matrix.
Currently crudely implemented as a triple loop in pure R, may be slow.
Usually used for evaluating the predictive likelihood when many
series but few factors are used, see
predloglik
and predloglikWB
.
Other predictors:
predcond()
,
predcor()
,
predcov()
,
predh()
,
predloglikWB()
,
predloglik()
In factor SV models, the ordering of variables is often
chosen through a preliminary static factor analysis. These
methods are implemented in preorder
.
After a maximum likelihood factor model fit to the data,
factor loadings are ordered as follows: The variable with the
highest loading on factor 1 is placed first, the variable with
the highest loading on factor 2 second (unless this variable
is already placed first, in which case the variable with the
second highest loading is taken).
preorder( dat, factors = ledermann(ncol(dat)), type = "fixed", transload = identity )
preorder( dat, factors = ledermann(ncol(dat)), type = "fixed", transload = identity )
dat |
Matrix containing the data, with |
factors |
Number of factors to be used, defaults to the Ledermann bound. |
type |
Can be "fixed" or "dynamic". The option "fixed"
means that that a |
transload |
Function for transforming the estimated factor loadings before ordering. Defaults to the identity function. |
A vector of length m
with the ordering found.
ledermann
Pretty printing of an fsvsdraws object
## S3 method for class 'fsvdraws' print(x, ...)
## S3 method for class 'fsvdraws' print(x, ...)
x |
Object of class |
... |
Ignored. |
Returns x
invisibly.
runningcormat
extracts summary statistics from the model-implied
correlation matrix
from an fsvdraws
object for one point in time.
runningcormat(x, i, statistic = "mean", type = "cor")
runningcormat(x, i, statistic = "mean", type = "cor")
x |
Object of class |
i |
A single point in time. |
statistic |
Indicates which statistic should be extracted. Defaults
to |
type |
Indicates whether covariance ( |
Matrix containing the requested correlation matrix summary statistic.
Other extractors:
cormat.fsvdraws()
,
covmat.fsvdraws()
,
runningcovmat()
set.seed(1) sim <- fsvsim(n = 500, series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1, runningstore = 6) # estimate cor100mean <- runningcormat(res, 100) # extract mean at t = 100 cor100sd <- runningcormat(res, 100, statistic = "sd") # extract sd lower <- cor100mean - 2*cor100sd upper <- cor100mean + 2*cor100sd true <- cormat(sim, 100)[,,1] # true value # Visualize mean +/- 2sd and data generating values par(mfrow = c(3,3), mar = c(2, 2, 2, 2)) for (i in 1:3) { for (j in 1:3) { plot(cor100mean[i,j], ylim = range(lower, upper), pch = 3, main = paste(i, j, sep = ' vs. '), xlab = '', ylab = '') lines(c(1,1), c(lower[i,j], upper[i,j])) points(true[i,j], col = 3, cex = 2) } }
set.seed(1) sim <- fsvsim(n = 500, series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1, runningstore = 6) # estimate cor100mean <- runningcormat(res, 100) # extract mean at t = 100 cor100sd <- runningcormat(res, 100, statistic = "sd") # extract sd lower <- cor100mean - 2*cor100sd upper <- cor100mean + 2*cor100sd true <- cormat(sim, 100)[,,1] # true value # Visualize mean +/- 2sd and data generating values par(mfrow = c(3,3), mar = c(2, 2, 2, 2)) for (i in 1:3) { for (j in 1:3) { plot(cor100mean[i,j], ylim = range(lower, upper), pch = 3, main = paste(i, j, sep = ' vs. '), xlab = '', ylab = '') lines(c(1,1), c(lower[i,j], upper[i,j])) points(true[i,j], col = 3, cex = 2) } }
runningcovmat
extracts summary statistics from the model-implied
covariance matrix
from an fsvdraws
object for one point in time.
runningcovmat(x, i, statistic = "mean", type = "cov")
runningcovmat(x, i, statistic = "mean", type = "cov")
x |
Object of class |
i |
A single point in time. |
statistic |
Indicates which statistic should be extracted. Defaults
to |
type |
Indicates whether covariance ( |
Matrix containing the requested covariance matrix summary statistic.
Other extractors:
cormat.fsvdraws()
,
covmat.fsvdraws()
,
runningcormat()
set.seed(1) sim <- fsvsim(n = 500, series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate cov100mean <- runningcovmat(res, 100) # extract mean at t = 100 cov100sd <- runningcovmat(res, 100, statistic = "sd") # extract sd lower <- cov100mean - 2*cov100sd upper <- cov100mean + 2*cov100sd true <- covmat(sim, 100) # true value # Visualize mean +/- 2sd and data generating values par(mfrow = c(3,3), mar = c(2, 2, 2, 2)) for (i in 1:3) { for (j in 1:3) { plot(cov100mean[i,j], ylim = range(lower, upper), pch = 3, main = paste(i, j, sep = ' vs. '), xlab = '', ylab = '') lines(c(1,1), c(lower[i,j], upper[i,j])) points(true[i,j,1], col = 3, cex = 2) } }
set.seed(1) sim <- fsvsim(n = 500, series = 3, factors = 1) # simulate res <- fsvsample(sim$y, factors = 1) # estimate cov100mean <- runningcovmat(res, 100) # extract mean at t = 100 cov100sd <- runningcovmat(res, 100, statistic = "sd") # extract sd lower <- cov100mean - 2*cov100sd upper <- cov100mean + 2*cov100sd true <- covmat(sim, 100) # true value # Visualize mean +/- 2sd and data generating values par(mfrow = c(3,3), mar = c(2, 2, 2, 2)) for (i in 1:3) { for (j in 1:3) { plot(cov100mean[i,j], ylim = range(lower, upper), pch = 3, main = paste(i, j, sep = ' vs. '), xlab = '', ylab = '') lines(c(1,1), c(lower[i,j], upper[i,j])) points(true[i,j,1], col = 3, cex = 2) } }
signident
provides methods for identifying the signs of
the factor loadings after running the MCMC sampler
signident(x, method = "maximin", implementation = 3)
signident(x, method = "maximin", implementation = 3)
x |
Object of class |
method |
Can be "diagonal" or "maximin". If "diagonal" is
chosen, the diagonal elements of the factor loadings matrix
are assumed to have positive signs
and the others are arranged accordingly.
If "maximin" is chosen, for each factor, |
implementation |
Either 1, 2, or 3 (the default). Determines how the reordering is implemented. Should not be necessary to depart from the default. |
Returns an object of class 'fsvdraws'
with adjusted
factors and factor loadings. Moreover, a list element called
'identifier'
is added, providing the numbers of the series
used for identification and the corresponding minimum distances to
zero.
Other postprocessing:
orderident()
set.seed(1) sim <- fsvsim(series = 8, factors = 2) # simulate res <- fsvsample(sim$y, factors = 2, signswitch = TRUE, draws = 2000, burnin = 1000) # estimate # Plot unidentified loadings: facloaddensplot(res, fsvsimobj = sim, rows = 8) # Identify: res <- signident(res) # Plot identified loadings: facloaddensplot(res, fsvsimobj = sim, rows = 8)
set.seed(1) sim <- fsvsim(series = 8, factors = 2) # simulate res <- fsvsample(sim$y, factors = 2, signswitch = TRUE, draws = 2000, burnin = 1000) # estimate # Plot unidentified loadings: facloaddensplot(res, fsvsimobj = sim, rows = 8) # Identify: res <- signident(res) # Plot identified loadings: facloaddensplot(res, fsvsimobj = sim, rows = 8)
voltimeplot
plots the marginal volatilities over time, i.e. the
series-specific conditional standard deviations. If these haven't been
stored during sampling (because runningstore
has been set too low),
voltimeplot
throws a warning.
voltimeplot(x, these = seq_len(nrow(x$y)), legend = "topright", ...)
voltimeplot(x, these = seq_len(nrow(x$y)), legend = "topright", ...)
x |
Object of class |
these |
Index vector containing the time points to plot. Defaults
to |
legend |
Where to position the |
... |
Additional parameters will be passed on to |
Returns x
invisibly.
Other plotting:
comtimeplot()
,
corimageplot()
,
corplot()
,
cortimeplot()
,
evdiag()
,
facloadcredplot()
,
facloaddensplot()
,
facloadpairplot()
,
facloadpointplot()
,
facloadtraceplot()
,
logvartimeplot()
,
paratraceplot()
,
plot.fsvdraws()
,
plotalot()