Large BVAR Module Documentation
This section documents the functions and classes in the large_bvar.py module.
List of Functions and Classes
Detailed Documentation
- covbayesvar.large_bvar.FIS(Y, Z, R, T, S)
Fixed Interval Smoother (FIS) based on Durbin and Koopman, 2001, p. 64-71.
- Parameters:
Y (numpy.ndarray) – Data array of shape (n, nobs), where n is the number of variables and nobs is the time dimension.
Z (numpy.ndarray) – System matrix (Z) of shape (n, m), where m is the dimension of the state vector.
R (numpy.ndarray) – System matrix (R) of shape (n, n).
T (numpy.ndarray) – Transition matrix (T) of shape (m, m).
S (dict) – Dictionary containing estimates from Kalman filter SKF. - S[‘Am’]: Estimates (a_{t|t-1}) of shape (m, nobs). - S[‘Pm’]: (P_{t|t-1} = ext{Cov}(a_{t|t-1})) of shape (m, m, nobs).
- Returns:
- Dictionary containing smoothed estimates added to S:
S[‘AmT’]: Smoothed estimates (a_{t|T}) of shape (m, nobs).
S[‘PmT’]: (P_{t|T} = ext{Cov}(a_{t|T})) of shape (m, m, nobs).
- Return type:
dict
- covbayesvar.large_bvar.MissData(y, C, R, c1)
Eliminates the rows in y, matrices C, R, and vector c1 that correspond to missing data (NaN) in y.
- Parameters:
y (numpy.ndarray) – Vector of observable data with dimensions (N, 1), where N is the number of observations.
C (numpy.ndarray) – Measurement matrix with dimensions (N, M), where M is the number of state variables.
R (numpy.ndarray) – Covariance matrix with dimensions (N, N).
c1 (numpy.ndarray) – Constant vector with dimensions (N, 1).
- Returns:
A tuple containing updated y, C, R, and c1 after eliminating rows corresponding to missing data.
y (numpy.ndarray): Updated vector with dimensions (N_new, 1), where N_new is the number of non-NaN entries in y.
C (numpy.ndarray): Updated matrix with dimensions (N_new, M).
R (numpy.ndarray): Updated covariance matrix with dimensions (N_new, N_new).
c1 (numpy.ndarray): Updated constant vector with dimensions (N_new, 1).
- Return type:
tuple
- covbayesvar.large_bvar.SKF(Y, Z, R, T, Q, A_0, P_0, c1, c2)
Kalman filter for stationary systems with time-varying system matrices and missing data.
- The model is:
[ y_t = Z imes a_t + epsilon_t ] [ a_{t+1} = T imes a_t + u_t ]
- Parameters:
Y (numpy.ndarray) – Data with dimensions (n, nobs), where nobs is the number of observations and n is the number of observable variables.
Z (numpy.ndarray) – Measurement matrix with dimensions (n, m), where m is the number of state variables.
R (numpy.ndarray) – Covariance matrix R with dimensions (n, n).
T (numpy.ndarray) – Transition matrix T with dimensions (m, m).
Q (numpy.ndarray) – Covariance matrix Q with dimensions (m, m).
A_0 (numpy.ndarray) – Initial state vector with dimensions (m, 1).
P_0 (numpy.ndarray) – Initial covariance matrix with dimensions (m, m).
c1 (numpy.ndarray) – Constant vector c1 with dimensions (n, 1).
c2 (numpy.ndarray) – Constant vector c2 with dimensions (m, 1).
- Returns:
- A dictionary containing:
’Am’: Predicted state vector ( A_t|t-1 ) with dimensions (m, nobs).
’Pm’: Predicted covariance of ( A_t|t-1 ) with dimensions (m, m, nobs).
’AmU’: Filtered state vector ( A_t|t ) with dimensions (m, nobs).
’PmU’: Filtered covariance of ( A_t|t ) with dimensions (m, m, nobs).
’ZF’: A list of arrays, each with dimensions depending on missing data. (nobs x 1, each cell m x n)
’V’: A list of arrays, each with dimensions depending on missing data. (nobs x 1, each cell n x 1)
- Return type:
dict
- covbayesvar.large_bvar.TypecastToArray(variables)
Converts a list of variables to their array equivalents, if applicable.
This function processes a list of variables (variables). For each variable, if it is a non-empty list, a float, or an int, it converts the variable to a numpy array. Empty lists are skipped. The function returns a list of the processed variables.
- Parameters:
variables (list) – A list of variables to be processed. Each variable can be of any type (list, float, int, etc.).
- Returns:
- A list of processed variables, where each non-empty list, float, or int
variable is converted to a numpy array. Empty lists are excluded.
- Return type:
list
Example
>>> variables = [1.0, [], [3, 4, 5], 2] >>> TypecastToArray(variables) [array([1.]), array([3, 4, 5]), array([2])]
- covbayesvar.large_bvar.VARcf_DKcks(X, p, beta, Su, nDraws=0)
Computes conditional forecasts for the missing observations in X using a VAR, Kalman filter and the Durban and Koopman smoother.
- Parameters:
X (numpy.ndarray) – Matrix of observable variables of shape (T, N).
p (int) – Number of lags in VAR.
beta (numpy.ndarray) – Coefficients of the VAR of shape ((N * p + 1), N).
Su (numpy.ndarray) – Covariance matrix of the VAR of shape (N, N).
nDraws (int, optional) – Number of draws. If == 0 then we run a simple Kalman smoother, otherwise we draw nDraws number of draws of the states. Default is 0.
- Returns:
Matrix where NaNs from X are replaced by the conditional forecasts. Shape is (T, N).
- Return type:
numpy.ndarray
- covbayesvar.large_bvar.beta_coef(x, mosd)
Computes the coefficients for the Beta distribution.
- Parameters:
x (list) – Contains alpha and beta values for the Beta distribution
mosd (list) – Contains mode and standard deviation values.
- Returns:
List with two results that represent two coefficients
- Return type:
list
- covbayesvar.large_bvar.bfgsi(H0, dg, dx)
Perform a Broyden-Fletcher-Goldfarb-Shanno (BFGS) update on the inverse Hessian matrix.
- Parameters:
H0 (numpy.ndarray) – The current estimate of the inverse Hessian matrix. Must be a square matrix.
dg (numpy.ndarray) – The previous change in the gradient (as a column vector). Must be a vector of the same dimension as one side of H0.
dx (numpy.ndarray) – The previous change in the variable x (as a column vector). Must be a vector of the same dimension as one side of H0.
- Returns:
The updated inverse Hessian matrix. If the update fails, the original H0 is returned.
- Return type:
numpy.ndarray
Notes
The function uses the BFGS formula to compute the updated inverse Hessian.
The update may fail if the dot product of dg and dx is too close to zero, in which case a warning is printed.
Example
>>> H0 = np.diag([1, 2, 3]) >>> dg = np.array([0.1, -0.2, 0.3]) >>> dx = np.array([0.4, -0.5, 0.6]) >>> bfgsi(H0, dg, dx)
- covbayesvar.large_bvar.bvarFcst(y, beta, hz)
Computes the forecasts for a vector autoregression (VAR) model at the specified forecast horizons.
This function takes historical data (y), estimated VAR coefficients (beta), and a list of forecast horizons (hz). It then computes the forecasts for each variable in y at each horizon in hz.
- Parameters:
y (numpy.ndarray) – A 2D array of observed data with shape (T, n), where T is the number of time periods and n is the number of variables in the VAR model.
beta (numpy.ndarray) – A 2D array of coefficients for the VAR model with shape (k, n), where k is the number of coefficients for each variable (including the intercept and lags of all variables) and n is the number of variables.
hz (list or array-like) – A list or array of integers representing the forecast horizons. For example, hz=[1, 2, 3] will compute forecasts for 1, 2, and 3 periods ahead.
- Returns:
- A 2D array with shape (len(hz), n) containing the forecasted values for each variable
at each specified horizon. The rows correspond to the horizons in hz, and the columns correspond to the variables in y.
- Return type:
numpy.ndarray
Example
>>> # Example usage >>> y = np.array([[1.2, 0.5], [1.3, 0.7], [1.1, 0.4]]) # Historical data (3 periods, 2 variables) >>> beta = np.array([[0.5, 0.3], [0.1, -0.1], [0.2, 0.0]]) # Coefficients (3 coefficients, 2 variables) >>> hz = [1, 2] # Forecast for 1 and 2 periods ahead >>> forecast = bvarFcst(y, beta, hz) >>> print(forecast) # Output: Forecasted values at horizons 1 and 2
- covbayesvar.large_bvar.bvarGLP(y, lags, **kwargs)
Estimate the BVAR model of Giannone, Lenza and Primiceri (2015)
- Parameters:
y (numpy.ndarray) – Data matrix.
lags (int) – Number of lags in the VAR.
**kwargs – Additional arguments to specify the BVAR model settings. - mcmc (int) - MCMCconst (int) - MNpsi (int or float) - sur (int) - noc (int) - Ndraws (int) - hyperpriors (int)
- Example of dimensions of inputs:
lags = 13
y.shape = (544, 40)
varargs = (mcmc=1, MCMCconst=1, MNpsi=0, sur=1, noc=1, Ndraws=2000, hyperpriors=1)
- Returns:
Results of the BVAR estimation.
- Return type:
dict
- covbayesvar.large_bvar.bvarGLP_covid(y, lags, priors_params=None, **kwargs)
Estimate the BVAR model of Giannone, Lenza and Primiceri (2015), augmented for changes in volatility due to Covid (March 2020). Designed for monthly data.
The path of common volatility is controlled by 3 hyperparameters and has the form [eta(1) eta(2)*eta(3)**[0:end]].
- Parameters:
y (numpy.ndarray) – Data matrix.
lags (int) – Number of lags in the VAR.
**kwargs – Additional arguments to specify the BVAR model settings. - mcmc (int) - MCMCconst (int) - MNpsi (int or float) - sur (int) - noc (int) - Ndraws (int) - hyperpriors (int) - Tcovid (int)
- Example of dimensions of inputs:
>>> lags = 13 >>> y.shape = (544, 40) >>> varargs = (mcmc=1, MCMCconst=1, MNpsi=0, sur=1, noc=1, Ndraws=2000, hyperpriors=1, Tcovid=507)
- Returns:
Results of the BVAR estimation.
- Return type:
dict
- covbayesvar.large_bvar.bvarIrfs(beta, sigma, nshock, hmax, structural=False)
Computes structural or reduced form Impulse Response Functions (IRFs) using Cholesky ordering.
This function calculates IRFs up to a specified horizon based on the provided VAR model coefficients and covariance matrix of the error terms. The IRFs are generated using a Cholesky decomposition of the covariance matrix to apply a shock in a specified position.
- Parameters:
beta (numpy.ndarray) – Coefficient matrix of the VAR model. Size: [k, n], where k is the number of coefficients (including the intercept) and n is the number of variables in the VAR model.
sigma (numpy.ndarray) – Covariance matrix of the VAR model residuals. Size: [n, n], where n is the number of variables in the VAR model.
nshock (int) – Position of the variable to which the shock is applied. The position corresponds to the column number in ‘beta’.
hmax (int) – Maximum horizon for the impulse response.
structural (bool, optional) – If True, returns structural IRFs. Default is False.
- Returns:
- Computed impulse response functions. Size: [hmax, n],
where hmax is the maximum horizon for the impulse response and n is the number of variables in the VAR model.
- Return type:
numpy.ndarray
Example
>>> beta = np.array([[0.2, 0.3], [0.1, 0.4], [0.5, 0.1], [0.3, 0.2], [0.1, 0.3]]) >>> sigma = np.array([[0.5, 0.1], [0.1, 0.6]]) >>> nshock = 1 >>> hmax = 5 >>> result_irf = bvar_irfs(beta, sigma, nshock, hmax) >>> print(result_irf)
- covbayesvar.large_bvar.check_params(par)
Check the parameters for acceptability and fill in defaults for unspecified ones.
- Parameters:
par (dict) – A dictionary containing the parameters.
- Returns:
The dictionary with checked and updated parameters.
- Return type:
dict
- Raises:
ValueError – If any parameter is invalid.
Example
>>> par = { 'DerivativeOrder': 2, 'MethodOrder': 4, 'RombergTerms': 2,is it 'MaxStep': 100, 'StepRatio': 2, 'NominalStep': None, 'Vectorized': 'no', 'FixedStep': None, 'Style': 'central' }
>>> check_params(par)
- covbayesvar.large_bvar.cholred(S)
Compute the reduced Cholesky decomposition of a matrix.
- Parameters:
S (array_like) – Input matrix (n x n).
- Returns:
Reduced Cholesky decomposition (n x n).
- Return type:
array_like
- covbayesvar.large_bvar.cols(x)
Return the number of columns in a matrix x.
- Parameters:
x (array_like) – Input matrix.
- Returns:
Number of columns in x.
- Return type:
int
- covbayesvar.large_bvar.computeIrfs(beta, G, nshock, hmax)
Computes Impulse Response Functions (IRFs) up to a specified horizon.
This function calculates IRFs based on the provided VAR model coefficients and a matrix G, which represent the effect of shocks in the model.
- Parameters:
beta (numpy.ndarray) – Coefficient matrix of the VAR model. Size: [k, n], where k is the number of coefficients (including the intercept) and n is the number of variables in the VAR model.
G (numpy.ndarray) – Matrix representing the effect of shocks in the model. Size: [n, n], where n is the number of variables in the VAR model.
nshock (int) – Position of the variable to which the shock is applied. The position corresponds to the column number in ‘beta’.
hmax (int) – Maximum horizon for the impulse response.
- Returns:
- Computed impulse response functions. Size: [hmax, n],
where hmax is the maximum horizon for the impulse response and n is the number of variables in the VAR model.
- Return type:
numpy.ndarray
Example
>>> beta = np.array([[0.2, 0.3], [0.1, 0.4], ...]) # Replace with actual data >>> G = np.array([[...], [...]]) # Replace with actual data >>> nshock = 1 >>> hmax = 24 >>> result_irf = computeIrfs(beta, G, nshock, hmax) >>> print(result_irf)
- covbayesvar.large_bvar.csminit(fcn, x0, f0, g0, badg, H0, *varargin)
Performs a line search to find a suitable step size for optimization.
This function conducts a line search to find a suitable step size (lambda) in the descent direction for optimization. It uses a combination of growing and shrinking strategies, adjusting lambda until certain improvement criteria are met.
- Parameters:
fcn (callable) – Function handle to the objective function.
x0 (numpy.ndarray) – Initial point, shape (n,).
f0 (float) – Function value at the initial point.
g0 (numpy.ndarray) – Gradient at the initial point, shape (n,).
badg (int) – Flag indicating if the gradient is bad (potentially inaccurate), scalar.
H0 (numpy.ndarray) – Approximate inverse Hessian or Hessian matrix at the initial point, shape (n, n).
*varargin – Additional arguments passed to the target function.
- Returns:
Best function value found during the line search. numpy.ndarray: Point corresponding to the best function value, shape (n,). int: Number of function evaluations. int: Return code indicating the termination condition.
- Return type:
float
Note
This function is typically used within iterative optimization algorithms, such as quasi-Newton methods, to ensure that the step size is chosen to provide sufficient improvement in the objective function value.
- covbayesvar.large_bvar.csminwel(fcn, x0, H0, grad, crit, nit, *varargin)
Minimizes a function using a quasi-Newton method.
- Return type:
Tuple[float,ndarray,ndarray,ndarray,int,int,int]- Parameters:
fcn (Callable) – Objective function to be minimized.
x0 (np.ndarray) – Initial value of the parameter vector.
H0 (np.ndarray) – Initial value for the inverse Hessian. Must be positive definite.
grad (Union[Callable, np.ndarray], optional) – Either a function that calculates the gradient, or a null array. If null, the program calculates a numerical gradient.
crit (float) – Convergence criterion. Iteration will cease when it’s impossible to improve the function value by more than crit.
nit (int) – Maximum number of iterations.
varargin (Any) – Additional parameters that get handed off to fcn each time it is called.
- Returns:
fh (float): The value of the function at the minimum.
xh (np.ndarray): The value of the parameters that minimize the function.
gh (np.ndarray): The gradient of the function at the minimum.
H (np.ndarray): The estimated inverse Hessian at the minimum.
itct (int): The total number of iterations performed.
fcount (int): The total number of function evaluations.
retcodeh (int): Return code that provides information about why the algorithm terminated.
- Return type:
Tuple[float, np.ndarray, np.ndarray, np.ndarray, int, int, int]
- covbayesvar.large_bvar.csolve(FUN, x, gradfun, crit, itmax, *varargin)
Finds the solution to a system of nonlinear equations using iterative methods.
- Parameters:
FUN (function) – The function representing the system of equations. Accepts a vector or matrix x.
x (list or np.array) – Initial guess for the solution.
gradfun (function or None) – Function to evaluate the gradient matrix. If None, a numerical gradient is used.
crit (float) – Tolerance level; if the sum of absolute values returned by FUN is less than this, the equation is considered solved.
itmax (int) – Maximum number of iterations.
*varargin – Additional arguments passed on to FUN and gradfun.
- Returns:
- A tuple containing:
x (list or np.array): Solution to the system of equations.
- rc (int): Return code indicating the status of the solution.
0: Normal solution.
1, 3: No solution (likely a numerical problem or discontinuity).
4: Termination due to reaching the maximum number of iterations.
- Return type:
tuple
Example
- def fun(x):
return [x[0]**2 + x[1] - 3, x[0] + x[1]**2 - 3]
x0 = [1, 1] crit = 1e-6 itmax = 100
x, rc = csolve(fun, x0, None, crit, itmax)
- covbayesvar.large_bvar.derivest(fun, x0, varargin)
Estimate the n’th derivative of fun at x0 and provide an error estimate.
- Parameters:
fun (callable) – Function to differentiate. It should be vectorized.
x0 (float or np.ndarray) – Point(s) at which to differentiate fun.
- Keyword Arguments:
DerivativeOrder (int) – Specifies the derivative order estimated. Default is 1.
MethodOrder (int) – Specifies the order of the basic method used for the estimation. Default is 4.
Style (str) – Specifies the style of the basic method used for the estimation (‘central’, ‘forward’, ‘backward’). Default is ‘central’.
RombergTerms (int) – Number of Romberg terms for extrapolation. Default is 2.
FixedStep (float) – Fixed step size. Default is None.
MaxStep (float) – Specifies the maximum excursion from x0 that will be allowed. Default is 100.
StepRatio (float) – The ratio used between sequential steps. Default is 2.0000001.
Vectorized (str) – Whether the function is vectorized or not (‘yes’, ‘no’). Default is ‘yes’.
- Returns:
Derivative estimate for each element of x0. errest (float or np.ndarray): 95% uncertainty estimate of the derivative. finaldelta (float or np.ndarray): The final overall stepsize chosen.
- Return type:
der (float or np.ndarray)
- covbayesvar.large_bvar.disturbance_smoother_var(y, c, Z, G, C, B, H, s00, P00, T, n, ns, ne, SS)
Performs draws from the posterior of the disturbances and unobservable states of a state-space model. The model is defined by the input matrices and vectors.
- Parameters:
y (np.ndarray) – Observations, dimension T x n.
c (np.ndarray) – Constant term in observation equation, dimension n x T or n.
Z (np.ndarray) – Matrix in observation equation, dimension n x ns x T or n x ns.
G (np.ndarray) – Matrix in observation equation, dimension n x n x T or n x n.
C (np.ndarray) – Constant term in state equation, dimension ns.
B (np.ndarray) – Matrix in state equation, dimension ns x ns.
H (np.ndarray) – Matrix in state equation, dimension ns x ne x T or ns x ne.
s00 (np.ndarray) – Initial state, dimension ns.
P00 (np.ndarray) – Initial state covariance, dimension ns x ns.
T (int) – Number of time steps.
n (int) – Dimension of observation vector.
ns (int) – Dimension of state vector.
ne (int) – Dimension of disturbance vector.
SS (str) – Method for computing the smoother, either ‘simulation’ or ‘kalman’.
- Returns:
sdraw (np.ndarray): Draw of the state, dimension ns x T. epsdraw (np.ndarray): Draw of the disturbance, dimension ne x T for ‘simulation’
and an empty array for ‘kalman’.
- Return type:
tuple
- Raises:
ValueError – If SS is not ‘simulation’ or ‘kalman’.
- covbayesvar.large_bvar.drsnbrck(x)
Compute the derivative for the Rosenbrock problem.
- Parameters:
x (numpy.array) – Input vector of shape (2, 1)
- Returns:
Derivative of shape (2, 1) badg (int): Flag indicating if the gradient is bad (always 0)
- Return type:
dr (numpy.array)
- covbayesvar.large_bvar.fdamat(sr, parity, nterms)
Compute matrix for finite difference approximation (FDA) derivation.
- Parameters:
sr (float) – The ratio between successive steps.
parity (int) – The parity of the derivative terms. - 0: One-sided, all terms included but zeroth order - 1: Only odd terms included - 2: Only even terms included
nterms (int) – The number of terms in the series.
- Returns:
The FDA matrix.
- Return type:
numpy.ndarray
- covbayesvar.large_bvar.form_companion_matrices(betadraw, G, n, lags, TTfcst)
Forms the matrices of the VAR companion form.
This function forms various matrices used in the VAR companion form, such as those for the observation and state equations. It takes into account a given forecast horizon and various other parameters.
- Parameters:
betadraw (numpy.ndarray) – Beta coefficients for the VAR model. Shape should be (1 + n * lags, n).
G (numpy.ndarray) – Matrix G in the state equation. Shape should be (n, n).
n (int) – The number of variables in the VAR model.
lags (int) – The number of lags in the VAR model.
TTfcst (int) – The forecast horizon.
- Returns:
- Tuple containing:
varc (numpy.ndarray): Vector of zeros of shape (n, TTfcst).
varZ (numpy.ndarray): 3D array with the Z matrix replicated TTfcst times. Shape is (n, n*lags, TTfcst).
varG (numpy.ndarray): 3D array of zeros of shape (n, n, TTfcst).
varC (numpy.ndarray): Vector containing the first n elements of betadraw. Shape is (n*lags, ).
varT (numpy.ndarray): State transition matrix. Shape is (n*lags, n*lags).
varH (numpy.ndarray): 3D array for the H matrix. Shape is (n*lags, n, TTfcst).
- Return type:
tuple
- covbayesvar.large_bvar.form_companion_matrices_covid(betadraw, G, etapar, tstar, n, lags, TTfcst)
Forms the matrices of the VAR companion form with COVID-related adjustments.
- Parameters:
betadraw (numpy.ndarray) – Beta coefficients for the VAR model. Shape should be (1 + n * lags, n).
G (numpy.ndarray) – Matrix G in the state equation. Shape should be (n, n).
etapar (numpy.ndarray) – Array containing the parameters for COVID adjustments. Shape should be (4,).
tstar (int) – The starting point of COVID effects in the forecast horizon.
n (int) – The number of variables in the VAR model.
lags (int) – The number of lags in the VAR model.
TTfcst (int) – The forecast horizon.
- Returns:
- Tuple containing:
varc (numpy.ndarray): Vector of zeros of shape (n, TTfcst).
varZ (numpy.ndarray): 3D array with the Z matrix replicated TTfcst times. Shape is (n, n*lags, TTfcst).
varG (numpy.ndarray): 3D array of zeros of shape (n, n, TTfcst).
varC (numpy.ndarray): Vector containing the first n elements of betadraw. Shape is (n*lags, ).
varT (numpy.ndarray): State transition matrix. Shape is (n*lags, n*lags).
varH (numpy.ndarray): 3D array for the H matrix with COVID-related adjustments. Shape is (n*lags, n, TTfcst).
- Return type:
tuple
- covbayesvar.large_bvar.gamma_coef(mode, sd, plotit)
Computes the coefficients of Gamma distribution coefficients and makes plots, if requested The parameters of the Gamma distribution are k = shape parameter: affects the PDF of the Gamma distribution, including skewness and mode theta = scale parameter: affects the spread of the distribution i.e. it shrinks or stretches the distribution along the x-axis.
- Parameters:
mode (float) – Mode of the Gamma distribution.
sd (float) – Standard deviation of the Gamma distribution.
plotit (int) – Flag to determine if the plot should be shown (1) or not (0).
- Returns:
Dictionary containing the ‘k’ and ‘theta’ parameters of the Gamma distribution.
- Return type:
dict
- covbayesvar.large_bvar.gradest(fun, x0)
Estimate the gradient vector of an analytical function of n variables.
- Parameters:
fun (callable) – Analytical function to differentiate. Must be a function of the vector or array x0.
x0 (numpy.ndarray) – Vector location at which to differentiate fun. If x0 is an nxm array, then fun is a function of n*m variables.
- Returns:
- A tuple containing:
- grad (numpy.ndarray): Vector of first partial derivatives of fun.
Will be a row vector of length x0.size.
- err (numpy.ndarray): Vector of error estimates corresponding to each
partial derivative in grad.
- finaldelta (numpy.ndarray): Vector of final step sizes chosen for each
partial derivative.
- Return type:
tuple
Examples
>>> # Example using lambda functions in Python >>> grad, err, finaldelta = gradest(lambda x: np.sum(x ** 2), np.array([1, 2, 3]))
- covbayesvar.large_bvar.hessdiag(fun, x0)
Compute the diagonal elements of the Hessian matrix (vector of second partials)
- Parameters:
fun – callable Scalar analytical function to differentiate.
x0 – np.ndarray Vector location at which to differentiate fun. If x0 is an nxm array, then fun is a function of n*m variables.
- Returns:
- np.ndarray
Vector of second partial derivatives of fun. These are the diagonal elements of the Hessian matrix.
- err: np.ndarray
Vector of error estimates corresponding to each second partial derivative in HD.
finaldelta: np.ndarray V ector of final step sizes chosen for each second partial derivative.
- Return type:
HD
- covbayesvar.large_bvar.hessian(fun, x0)
Compute the Hessian matrix of second partial derivatives for a scalar function.
Given a scalar function of one or more variables, compute the Hessian matrix, a square matrix of second-order partial derivatives of the function. It is a generalization of the second derivative test for single-variable functions.
- Args:
- fun (callable): A scalar function that accepts a NumPy array and returns a scalar.
The function to differentiate must be a function of the vector or array x0. The function does not need to be vectorized.
- x0 (np.ndarray): A NumPy array representing the point at which the Hessian matrix
is to be computed. If x0 is an n x m array, then fun is a function of n * m variables.
- Returns:
- tuple: A tuple containing:
- hess (np.ndarray): An n x n symmetric matrix of second partial derivatives
of fun, evaluated at x0.
- err (np.ndarray): An n x n array of error estimates corresponding to each
second partial derivative in hess.
- Raises:
- ValueError: If fun is not callable or if x0 does not allow for the computation
of the Hessian matrix due to incompatible dimensions or data types.
- Examples:
To use this function, define a scalar function of interest. For example, the Rosenbrock function, which is minimized at [1, 1]:
>>> rosen = lambda x: (1 - x[0])**2 + 105 * (x[1] - x[0]**2)**2 >>> hess, err = hessian(rosen, np.array([1, 1])) >>> print("Hessian matrix:
- “, hess)
>>> print("Error estimates:
“, err)
The Hessian matrix and error estimates for the function at the point [1, 1] will be printed to the console.
- Notes:
The hessian function is not a tool for frequent use on an expensive-to-evaluate objective function, especially in a large number of dimensions. Its computation will use roughly O(6*n^2) function evaluations for n parameters.
- See Also:
hessdiag, gradest, and rombextrap: Auxiliary functions that are required for the computation of the Hessian matrix and must be defined elsewhere in the codebase.
- covbayesvar.large_bvar.kfilter_const(y, c, Z, G, C, T, H, shat, sig)
Kalman filter with constant variance for the state-space model.
- Parameters:
y (np.array) – Observation vector at time t. Shape (n, 1).
c (float) – Constant term in observation equation.
Z (np.array) – Observation loading matrix. Shape (n, m).
G (np.array) – Observation noise loading matrix. Shape (n, n).
C (float) – Constant term in state equation.
T (np.array) – State transition matrix. Shape (m, m).
H (np.array) – State noise loading matrix. Shape (m, m).
shat (np.array) – Prior state estimate. Shape (m, 1).
sig (np.array) – Prior state covariance matrix. Shape (m, m).
- Returns:
- Tuple containing the following elements:
shatnew (np.array): Updated state estimate. Shape (m, 1).
signew (np.array): Updated state covariance matrix. Shape (m, m).
v (np.array): Prediction error. Shape (n, 1).
k (np.array): Kalman gain. Shape (m, n).
sigmainv (np.array): Inverse of the innovation covariance. Shape (n, n).
- Return type:
tuple
- covbayesvar.large_bvar.lag(x, n=1, v=0)
Create a matrix or vector of lagged values.
- Parameters:
x (numpy.ndarray) – Input matrix or vector (nobs x k).
n (int, optional) – Order of lag. Default is 1.
v (int or float, optional) – Initial values for lagged entries. Default is 0.
- Returns:
Matrix or vector of lags (nobs x k).
- Return type:
numpy.ndarray
Examples
>>> lag(x) # Creates a matrix (or vector) of x, lagged 1 observation. >>> lag(x, n=2) # Creates a matrix (or vector) of x, lagged 2 observations. >>> lag(x, n=2, v=999) # Lagged with custom initial values of 999.
Notes
If n <= 0, an empty array is returned.
- covbayesvar.large_bvar.lag_matrix(Y, lags)
Create a matrix of lagged (time-shifted) series.
- Parameters:
Y (np.ndarray) – Time series data. Y may be a vector or a matrix. If Y is a vector, it represents a single series. If Y is a numObs-by-numSeries matrix, it represents numObs observations of numSeries series.
lags (list) – List of integer delays or leads applied to each series in Y. To include an unshifted copy of a series in the output, use a zero lag.
- Returns:
- numObs-by-(numSeries*numLags) matrix of lagged versions of the series in Y.
Unspecified observations (presample and postsample data) are padded with NaN values.
- Return type:
np.ndarray
- covbayesvar.large_bvar.logMLVAR_formcmc(par, y, x, lags, T, n, b, MIN, MAX, SS, Vc, pos, mn, sur, noc, y0, draw, hyperpriors, priorcoef, MCMCMsur, long_run)
Compute the log-posterior (or logML if hyperpriors=0), and draws from the posterior distribution of the coefficients and of the covariance matrix of the residuals of the BVAR model by Giannone, Lenza, and Primiceri (2015).
- Parameters:
par (np.ndarray) – Parameters for the model, shaped (p, 1).
y (np.ndarray) – Output matrix, shaped (T, n).
x (np.ndarray) – Input matrix, shaped (T, k).
lags (int) – Number of lags in the VAR model.
T (int) – Number of time periods.
n (int) – Number of variables.
b (np.ndarray) – Prior mean for VAR coefficients, shaped (k, n).
MIN (dict) – Minimum hyperparameter values.
MAX (dict) – Maximum hyperparameter values.
SS (np.ndarray) – Sum of squares, shaped (n, 1).
Vc (float) – Prior variance for the constant.
pos (np.ndarray) – Position index (currently not used).
mn (dict) – Additional settings.
sur (int) – Indicator for Minnesota prior.
noc (int) – Indicator for no-cointegration prior.
y0 (np.ndarray) – Initial values for y, shaped (1, n).
draw (int) – Indicator for drawing from the posterior.
hyperpriors (int) – Indicator for using hyperpriors.
priorcoef (dict) – Coefficients for the prior.
Returns
tuple – Contains the following elements - logML (float): The log marginal likelihood. betadraw (np.ndarray or None): Drawn VAR coefficients from the posterior, shaped (k, n). Returns None if ‘draw’ is set to 0. drawSIGMA (np.ndarray or None): Drawn covariance matrix from the posterior, shaped (n, n). Returns None if ‘draw’ is set to 0.
- covbayesvar.large_bvar.logMLVAR_formcmc_covid(par, y, x, lags, T, n, b, MIN, MAX, SS, Vc, pos, mn, sur, noc, y0, draw, hyperpriors, priorcoef, Tcovid=None)
Compute the log-posterior (or logML if hyperpriors=0), and draws from the posterior distribution of the coefficients and of the covariance matrix of the residuals of the BVAR model by Giannone, Lenza, and Primiceri (2015). The function also accounts for a change in volatility due to COVID-19.
- Parameters:
par (np.ndarray) – Parameters for the model, shaped (p, 1).
y (np.ndarray) – Output matrix, shaped (T, n).
x (np.ndarray) – Input matrix, shaped (T, k).
lags (int) – Number of lags in the VAR model.
T (int) – Number of time periods.
n (int) – Number of variables.
b (np.ndarray) – Prior mean for VAR coefficients, shaped (k, n).
MIN (dict) – Minimum hyperparameter values.
MAX (dict) – Maximum hyperparameter values.
SS (np.ndarray) – Sum of squares, shaped (n, 1).
Vc (float) – Prior variance for the constant.
pos (np.ndarray) – Position index (currently not used).
mn (dict) – Additional settings.
sur (int) – Indicator for Minnesota prior.
noc (int) – Indicator for no-cointegration prior.
y0 (np.ndarray) – Initial values for y, shaped (1, n).
draw (int) – Indicator for drawing from the posterior.
hyperpriors (int) – Indicator for using hyperpriors.
priorcoef (dict) – Coefficients for the prior.
Tcovid (int, optional) – Time index for COVID-19 structural break. Defaults to None.
Returns
tuple – Contains the following elements - - logML (float): The log marginal likelihood. - betadraw (np.ndarray or None): Drawn VAR coefficients from the posterior, shaped (k, n). - Returns None if ‘draw’ is set to 0. - drawSIGMA (np.ndarray or None): Drawn covariance matrix from the posterior, shaped (n, n). - Returns None if ‘draw’ is set to 0.
- covbayesvar.large_bvar.logMLVAR_formin(par, y, x, lags, T, n, b, MIN, MAX, SS, Vc, pos, mn, sur, noc, y0, hyperpriors, priorcoef, MCMCMsur, long_run)
- Compute the log-posterior, posterior mode of the coefficients, and covariance matrix of the residuals for
a BVAR model.
This function implements the Bayesian Vector Autoregression (BVAR) model of Giannone, Lenza, and Primiceri (2015), extended to account for a change in volatility due to COVID-19.
- Parameters:
par (array-like) – Parameters for the model, shaped (p, 1).
y (array-like) – Output matrix, shaped (T, n).
x (array-like) – Input matrix, shaped (T, k).
lags (int) – Number of lags in the VAR model.
T (int) – Number of time periods.
n (int) – Number of variables.
b (array-like) – Prior mean for VAR coefficients, shaped (k, n).
MIN (dict) – Minimum hyperparameter values.
MAX (dict) – Maximum hyperparameter values.
SS (array-like) – Sum of squares, shaped (n, 1).
Vc (float) – Prior variance for the constant.
pos (array-like) – Position index (currently not used).
mn (dict) – Additional settings.
sur (int) – Indicator for Minnesota prior.
noc (int) – Indicator for no-cointegration prior.
y0 (array-like) – Initial values for y, shaped (1, n).
hyperpriors (int) – Indicator for using hyperpriors.
priorcoef (dict) – Coefficients for the prior.
- Returns:
- Contains logML, betahat, and sigmahat.
logML (float): Log marginal likelihood (or log-posterior if hyperpriors=0).
betahat (array-like): Posterior mode of the VAR coefficients, shaped (k, n).
sigmahat (array-like): Posterior mode of the covariance matrix, shaped (n, n).
- Return type:
tuple
Example
>>> logML, betahat, sigmahat = logMLVAR_formin_covid(par, y, x, lags, T, n, b, MIN, MAX, SS, Vc, pos, mn, sur, noc, y0, hyperpriors, priorcoef, MCMCMsur, long_run)
- covbayesvar.large_bvar.logMLVAR_formin_covid(par, y, x, lags, T, n, b, MIN, MAX, SS, Vc, pos, mn, sur, noc, y0, hyperpriors, priorcoef, Tcovid=None)
- Compute the log-posterior, posterior mode of the coefficients, and covariance matrix of the residuals for
a BVAR model.
This function implements the Bayesian Vector Autoregression (BVAR) model of Giannone, Lenza, and Primiceri (2015), extended to account for a change in volatility due to COVID-19.
- Parameters:
par (array-like) – Parameters for the model, shaped (p, 1).
y (array-like) – Output matrix, shaped (T, n).
x (array-like) – Input matrix, shaped (T, k).
lags (int) – Number of lags in the VAR model.
T (int) – Number of time periods.
n (int) – Number of variables.
b (array-like) – Prior mean for VAR coefficients, shaped (k, n).
MIN (dict) – Minimum hyperparameter values.
MAX (dict) – Maximum hyperparameter values.
SS (array-like) – Sum of squares, shaped (n, 1).
Vc (float) – Prior variance for the constant.
pos (array-like) – Position index (currently not used).
mn (dict) – Additional settings.
sur (int) – Indicator for Minnesota prior.
noc (int) – Indicator for no-cointegration prior.
y0 (array-like) – Initial values for y, shaped (1, n).
hyperpriors (int) – Indicator for using hyperpriors.
priorcoef (dict) – Coefficients for the prior.
Tcovid (int, optional) – Time index for COVID-19 structural break. Defaults to None.
- Returns:
- Contains logML, betahat, and sigmahat.
logML (float): Log marginal likelihood (or log-posterior if hyperpriors=0).
betahat (array-like): Posterior mode of the VAR coefficients, shaped (k, n).
sigmahat (array-like): Posterior mode of the covariance matrix, shaped (n, n).
- Return type:
tuple
Example
>>> logML, betahat, sigmahat = logMLVAR_formin_covid(par, y, x, lags, T, n, b, MIN, MAX, SS, Vc, pos, mn, sur, noc, y0, hyperpriors, priorcoef, Tcovid)
- covbayesvar.large_bvar.log_beta_pdf(x, al, bet)
Compute the log probability density function (PDF) of the Beta distribution.
- Parameters:
x (float) – Value at which to evaluate the PDF.
al (float) – Alpha parameter of the Beta distribution.
bet (float) – Beta parameter of the Beta distribution.
- Returns:
Log PDF of the Beta distribution.
- Return type:
float
- covbayesvar.large_bvar.log_gamma_pdf(x, k, theta)
Computes the log of the Gamma probability density function (PDF) for given values.
- Parameters:
x (float or numpy.ndarray) – Points at which to evaluate the log of the Gamma PDF. Scalar or array.
k (float) – Shape parameter of the Gamma distribution. Scalar.
theta (float) – Scale parameter of the Gamma distribution. Scalar.
- Returns:
- Log of the Gamma PDF evaluated at each point in x.
The output will have the same shape as x.
- Return type:
float or numpy.ndarray
Example
>>> log_gamma_pdf(2.0, 1.0, 1.0) -2.0
>>> log_gamma_pdf(np.array([2.0, 3.0]), 1.0, 1.0) array([-2., -3.])
- covbayesvar.large_bvar.log_ig2pdf(x, alpha, beta)
Compute the log probability density function (PDF) of the Inverse Gamma distribution.
- Parameters:
x (float) – Value at which to evaluate the PDF.
alpha (float) – Shape parameter of the Inverse Gamma distribution.
beta (float) – Scale parameter of the Inverse Gamma distribution.
- Returns:
Log PDF of the Inverse Gamma distribution.
- Return type:
float
- covbayesvar.large_bvar.make_positive_definite(matrix)
Ensures that a given square matrix is positive definite.
This function first checks if the matrix is already positive definite by looking at its eigenvalues. If any eigenvalues are negative, it then attempts to make the matrix positive definite by adding a small value to its diagonal elements and checking for positive definiteness via Cholesky decomposition.
- Parameters:
matrix (numpy.ndarray) – A square matrix.
- Returns:
A positive definite matrix.
- Return type:
numpy.ndarray
- Raises:
ValueError – If the matrix cannot be made positive definite after the maximum number of attempts.
- covbayesvar.large_bvar.numgrad(fcn, x, *args)
Compute the numerical gradient of a given function using a central difference approximation.
- Return type:
Tuple[ndarray,int]- Parameters:
fcn (Callable) – Function whose gradient is to be computed.
x (np.ndarray) – Point at which the gradient is to be computed.
args (Any) – Additional arguments passed to the target function.
- Returns:
- A tuple containing the numerical gradient at point x and a flag indicating
if any component of the gradient is bad.
- Return type:
Tuple[np.ndarray, int]
Example
>>> f = lambda x: x[0]**2 + x[1]**2 >>> x = np.array([1, 1]) >>> g, badg = numgrad(f, x)
- covbayesvar.large_bvar.ols1(y, x)
Perform Ordinary Least Squares (OLS) regression.
This function computes the OLS coefficients, fitted values, residuals, estimated variance of the residuals, and R-squared for a given set of observed dependent and independent variables.
- Parameters:
y (numpy.ndarray) – The dependent variable. Must be a column vector of shape (nobs, 1).
x (numpy.ndarray) – The independent variables. Must be a matrix of shape (nobs, nvar).
- Raises:
ValueError – If y and x have different numbers of observations.
- Returns:
- A dictionary containing the following keys:
”nobs”: Number of observations.
”nvar”: Number of independent variables.
”bhatols”: OLS coefficient estimates.
”yhatols”: Fitted values.
”resols”: Residuals.
”sig2hatols”: Estimated variance of residuals.
”sigbhatols”: Estimated variance-covariance matrix of OLS coefficients.
”XX”: X’X matrix used in OLS.
”R2”: R-squared value.
- Return type:
dict
Example
>>> y = np.array([[1], [2], [3]]) >>> x = np.array([[1, 1], [1, 2], [1, 3]]) >>> result = ols1(y, x)
- covbayesvar.large_bvar.parse_pv_pairs(default_params, pv_pairs)
Parses sets of property-value pairs and allows defaults.
- Parameters:
default_params (dict) – A dictionary with one field for every potential property-value pair. Each field will contain the default value for that property. If no default is supplied for a given property, then that field must be None.
pv_pairs (list) – A list of property-value pairs. Case is ignored when comparing properties to the list of field names. Also, any unambiguous shortening of a field/property name is allowed.
- Returns:
A dictionary that reflects any updated property-value pairs in pv_pairs.
- Return type:
dict
Example
>>> default_params = {'DerivativeOrder': 1, 'MethodOrder': 4, 'RombergTerms': 2, 'MaxStep': 100, 'StepRatio': 2, 'NominalStep': None, 'Vectorized': 'yes', 'FixedStep': None, 'Style': 'central'} >>> pv_pairs = ['deriv', 2, 'vectorized', 'no'] >>> updated_params = parse_pv_pairs(default_params, pv_pairs) >>> print(updated_params)
- covbayesvar.large_bvar.plot_joint_marginal(YY, Y1CondLim, xlab, ylab, dot_color, line_color, vis=False, LW=1.5)
Plots the joint distribution in the center, with marginals on the side. This version also plots a version conditioning on a set of limits on the first variable.
- Parameters:
YY (array_like) – Matrix containing the data to be plotted.
Y1CondLim (array_like) – Limits for the first variable’s conditioning.
xlab (str) – Label for the x-axis.
ylab (str) – Label for the y-axis.
vis (str, optional) – Figure visibility (‘on’ or ‘off’). Defaults to ‘off’.
LW (float, optional) – Line width. Defaults to 1.5.
- Returns:
The function plots the joint distribution, marginals, and conditionals.
- Return type:
None
- covbayesvar.large_bvar.plot_joint_marginal_overlay(YY_unc, YY_con, xlab, ylab, dot_color_unc='grey', line_color_unc='black', dot_color_con='lightcoral', line_color_con='red', LW=1.5, vis=False, clip=True, clip_bounds=(1, 99))
- covbayesvar.large_bvar.plot_joint_marginal_overlay2(YY_unc, YY_con, xlab, ylab, dot_color_unc='grey', line_color_unc='black', dot_color_con='lightcoral', line_color_con='red', LW=1.5, vis=False)
- covbayesvar.large_bvar.plot_weighted_joint_and_marginals(YY, wStar, xlab, ylab, vis=False, LW=1.5, Y0=None)
Plots the joint distribution in the center, with marginals on the side. This version places Variable 1’s marginal on the opposite side to avoid overlapping.
- Parameters:
YY (array_like) – Data to be plotted (2D array with columns as variables).
wStar (array_like) – Weights for the weighted contours and marginals.
xlab (str) – Label for the x-axis.
ylab (str) – Label for the y-axis.
vis (bool, optional) – Whether to display the plot. Defaults to False.
LW (float, optional) – Line width for the marginals. Defaults to 1.5.
Y0 (array_like, optional) – Reference value to highlight. Defaults to None.
- Returns:
Matplotlib figure and axis objects.
- Return type:
fig, ax
- covbayesvar.large_bvar.printpdf(h, outfilename)
Saves the given figure as a PDF file with specified dimensions.
- Parameters:
h (matplotlib.figure.Figure) – The figure object to be saved.
outfilename (str) – The path and name of the output PDF file.
Example
fig, ax = plt.subplots() ax.plot([1, 2, 3], [1, 2, 1]) printpdf(fig, “output.pdf”)
- covbayesvar.large_bvar.quantile_plot(time, quantiles, base_color=None, run_scenario_analysis=False, show_plot=False)
Plots a line chart with filled quantile bands.
- Parameters:
Time (array-like) – Time values for the x-axis.
Quantiles (array-like) – Quantiles to be plotted, either a 5 or 7 column matrix.
baseColor (tuple, optional) – RGB color value for the plot. Defaults to blue.
- Raises:
ValueError – If the quantile matrix is not of size 5 or 7.
Example
>>> Time = np.arange(0, 10, 0.1) >>> Quantiles = np.column_stack([np.sin(Time) * i for i in [0.5, 0.75, 1.0, 0.75, 0.5]]) >>> quantile_plot(Time, Quantiles)
- covbayesvar.large_bvar.rombextrap(StepRatio, der_init, rombexpon)
Do Romberg extrapolation for each estimate.
- Parameters:
StepRatio (float) – Ratio decrease in step.
der_init (np.ndarray) – Initial derivative estimates, shaped (n, 1).
rombexpon (list) – Higher order terms to cancel using the Romberg step.
- Returns:
- Contains the following elements -
der_romb (np.ndarray): Derivative estimates returned, shaped (n, 1). errest (np.ndarray): Error estimates, shaped (n, 1).
- Return type:
tuple
- covbayesvar.large_bvar.rosenbrock(x)
Rosenbrock function.
- Parameters:
x (list or numpy.ndarray) – A vector of length 2.
- Returns:
The result of the Rosenbrock function evaluated at the given vector x.
- Return type:
float
- covbayesvar.large_bvar.runKF_DK(y, A, C, Q, R, x_0, Sig_0, c1, c2)
Runs Kalman filter using the Durbin and Koopman simulation smoother.
- Parameters:
y (numpy.ndarray) – Matrix of observable variables of shape (n, T), where n is the number of variables and T
dimension. (is the time)
A (numpy.ndarray) – Transition matrix of shape (m, m), where m is the dimension of the state vector.
C (numpy.ndarray) – Measurement matrix of shape (n, m).
Q (numpy.ndarray) – Covariance matrix Q of shape (m, m).
R (numpy.ndarray) – Covariance matrix R of shape (n, n).
x_0 (numpy.ndarray) – Initial state vector of shape (m,).
Sig_0 (numpy.ndarray) – Initial covariance matrix of shape (m, m).
c1 (numpy.ndarray) – Constant vector c1 of shape (n,).
c2 (numpy.ndarray) – Constant vector c2 of shape (m,).
- Returns:
Smoothed state vector of shape (m, T).
- Return type:
numpy.ndarray
- covbayesvar.large_bvar.set_priors(y, lags, **kwargs)
This function sets up the default choices for the priors of the BVAR of Giannone, Lenza and Primiceri (2015)
- Parameters:
kwargs (dict) – Keyword arguments for various options (see the script for details). The optional keywords customize priors
- Returns:
- A tuple containing the following elements:
r (dict): Dictionary containing the set default choices for the priors.
mode (dict): Dictionary containing the mode values for hyperpriors.
sd (dict): Dictionary containing the standard deviations for hyperpriors.
priorcoef (dict): Dictionary containing coefficients for hyperpriors.
MIN (dict): Dictionary containing the minimum bounds for variables.
MAX (dict): Dictionary containing the maximum bounds for variables.
var_info (list): List containing information about variables in the function’s scope.
- Return type:
tuple
Examples
>>> some_kwargs = {'hyperpriors': 1, 'Vc': 10e6} >>> r, mode, sd, priorcoef, MIN, MAX, var_info = set_priors(**some_kwargs) >>> # Now, r, mode, sd, priorcoef, MIN, MAX, and var_info can be used in the bvarGLP_covid function
- covbayesvar.large_bvar.set_priors_covid(priors_params=None, **kwargs)
This function sets up the default choices for the priors of the BVAR of Giannone, Lenza and Primiceri (2015), augmented with a change in volatility at the time of Covid (March 2020).
- Parameters:
kwargs (dict) – Keyword arguments for various options (see the script for details). The optional keywords customize priors
- Returns:
- A tuple containing the following elements:
r (dict): Dictionary containing the set default choices for the priors.
mode (dict): Dictionary containing the mode values for hyperpriors.
sd (dict): Dictionary containing the standard deviations for hyperpriors.
priorcoef (dict): Dictionary containing coefficients for hyperpriors.
MIN (dict): Dictionary containing the minimum bounds for variables.
MAX (dict): Dictionary containing the maximum bounds for variables.
var_info (list): List containing information about variables in the function’s scope.
- Return type:
tuple
Examples
>>> some_kwargs = {'hyperpriors': 1, 'Vc': 10e6} >>> r, mode, sd, priorcoef, MIN, MAX, var_info = set_priors_covid(**some_kwargs) >>> # Now, r, mode, sd, priorcoef, MIN, MAX, and var_info can be used in the bvarGLP_covid function
- covbayesvar.large_bvar.swap2(vec, ind1, val1, ind2, val2)
Swap the values at the specified indices in the input vector.
- Parameters:
vec (list or ndarray) – The input vector.
ind1 (int) – The index of the first element to swap.
val1 (float or int) – The value to insert at index ind1.
ind2 (int) – The index of the second element to swap.
val2 (float or int) – The value to insert at index ind2.
- Returns:
The modified vector with values swapped.
- Return type:
list or ndarray
Example
Input dimensions for ind1 = 2, ind2 = 1, val1 = 0.0089, val2 = 43.72, vec is a 7-element list or ndarray of zeros.
- covbayesvar.large_bvar.swapelement(vec, ind, val)
Replace the element at a specified index ‘ind’ with a new ‘val’ in the vector vec.
- Parameters:
vec (list or numpy.ndarray) – The original vector.
ind (int) – The index of the element to be swapped.
val (float) – The new value to be placed at index ind.
- Returns:
The vector after the swap.
- Return type:
list or numpy.ndarray
Example
>>> swapelement([1, 2, 3], 1, 4) [1, 4, 3]
- covbayesvar.large_bvar.transform_data(spec, data_raw)
Transforms the raw data based on the specified transformation.
- Parameters:
spec (dict) – A dictionary containing a field called ‘Transformation’ that specifies the transformation to apply to each column of data in data_raw. The ‘Transformation’ field should be a list of strings, where each string is either ‘log’ (indicating a logarithmic transformation) or ‘lin’ (indicating a linear transformation).
data_raw (numpy.ndarray) – A matrix containing the raw data to be transformed.
- Returns:
A matrix containing the transformed data.
- Return type:
numpy.ndarray
- covbayesvar.large_bvar.trimr(x, n1, n2)
Return a matrix (or vector) x stripped of the specified rows.
- Parameters:
x (numpy.array) – Input matrix (or vector) (n x k)
n1 (int) – First n1 rows to strip
n2 (int) – Last n2 rows to strip
- Returns:
x with the first n1 and last n2 rows removed
- Return type:
z (numpy.array)
- covbayesvar.large_bvar.vec2mat(vec, n, m)
Forms the matrix M, such that M[i, j] = vec[i + j - 1].
- Parameters:
vec (numpy.ndarray) – Input vector.
n (int) – Number of rows for the output matrix.
m (int) – Number of columns for the output matrix.
- Returns:
The resulting matrix.
- Return type:
numpy.ndarray
Example
>>> vec = np.array([1, 2, 3, 4, 5, 6]) >>> vec2mat(vec, 2, 3) array([[1, 2], [2, 3], [3, 4]])
- covbayesvar.large_bvar.verify_bvar_results(bvar_results)
Check if the first beta and sigma matrices are all zeros. If so, replace them with the second beta and sigma matrices.
- Parameters:
bvar_results (dict) – The results from the BVAR estimation.
- Returns:
The corrected bvar_results.
- Return type:
dict
- covbayesvar.large_bvar.wquantile(X, p, w)
Calculate weighted quantiles for each time period.
- Parameters:
X (ndarray) – Input data of shape (T, nDraws), where T is the number of time periods and nDraws is the number of draws.
p (float or list of floats) – Target quantile(s) to compute (e.g., 0.5 for the median).
w (ndarray) – Weights of shape (nDraws,). Should sum to 1.
- Returns:
An array of shape (T, len(p)) containing the weighted quantiles for each time period.
- Return type:
ndarray