API documentation
Index
TermStructureModels.ForecastTermStructureModels.HyperparameterTermStructureModels.LatentSpaceTermStructureModels.ParameterTermStructureModels.Parameter_NUTSTermStructureModels.PosteriorSampleTermStructureModels.ReducedFormTermStructureModels.ScenarioTermStructureModels.TermPremiumTermStructureModels.YieldCurveBase.getindexBase.getindexStatistics.meanStatistics.medianStatistics.quantileStatistics.stdStatistics.varTermStructureModels.AR_res_varTermStructureModels.AₓTermStructureModels.AₚTermStructureModels.BₓTermStructureModels.BₚTermStructureModels.GQ_XXTermStructureModels.KphiTermStructureModels.LDLTermStructureModels.NIG_NIGTermStructureModels.PCATermStructureModels.PCs_2_latentsTermStructureModels.STermStructureModels.S_hatTermStructureModels.T0PTermStructureModels.T1XTermStructureModels._conditional_expectationTermStructureModels._conditional_forecastTermStructureModels._termPremiumTermStructureModels._unconditional_expectationTermStructureModels._unconditional_forecastTermStructureModels.aτTermStructureModels.btauTermStructureModels.bτTermStructureModels.calibrate_mean_phi_constTermStructureModels.conditional_expectationTermStructureModels.conditional_forecastTermStructureModels.dcurvature_dτTermStructureModels.dimQTermStructureModels.erase_nonstationary_paramTermStructureModels.erase_nonstationary_paramTermStructureModels.fitted_yieldcurveTermStructureModels.generativeTermStructureModels.hessianTermStructureModels.ineff_factorTermStructureModels.ineff_factorTermStructureModels.isstationaryTermStructureModels.jensens_inequalityTermStructureModels.latentspaceTermStructureModels.log_marginalTermStructureModels.loglik_NUTSTermStructureModels.loglik_meaTermStructureModels.loglik_mea2TermStructureModels.loglik_mea_NUTSTermStructureModels.loglik_tranTermStructureModels.logprior_CTermStructureModels.logprior_phi0TermStructureModels.logprior_varFFTermStructureModels.longvarTermStructureModels.minnesotaTermStructureModels.mle_error_covarianceTermStructureModels.phi_2_phi₀_CTermStructureModels.phi_hatTermStructureModels.phi_varFF_2_OmegaFFTermStructureModels.phi_varFF_2_ΩPPTermStructureModels.post_SigmaOTermStructureModels.post_gammaTermStructureModels.post_kQ_inftyTermStructureModels.post_kappaQTermStructureModels.post_kappaQ2TermStructureModels.post_kappaQ_phi_varFF_q_nu0TermStructureModels.post_phi_varFFTermStructureModels.posterior_NUTSTermStructureModels.posterior_samplerTermStructureModels.prior_CTermStructureModels.prior_gammaTermStructureModels.prior_kappaQTermStructureModels.prior_phi0TermStructureModels.prior_varFFTermStructureModels.reducedformTermStructureModels.term_premiumTermStructureModels.tuning_hyperparameterTermStructureModels.tuning_hyperparameter_with_vsTermStructureModels.yphi_XphiTermStructureModels.ν
Exported Functions
TermStructureModels.Forecast — Type
@kwdef struct Forecast <: PosteriorSampleThis struct contains the results of the scenario analysis, the conditional prediction for yields, factors = [PCs macros], and term premiums.
yieldsfactorsTP: term premium forecastsEH: estimated expectation hypothesis component
TermStructureModels.Hyperparameter — Type
@kwdef struct Hyperparameterp::Intq::Matrixnu0Omega0::Vectormean_phi_const::Vector = zeros(length(Omega0)): This is the prior mean of the constant term in the VAR.
TermStructureModels.LatentSpace — Type
@kwdef struct LatentSpace <: PosteriorSampleWhen the model goes to the JSZ latent factor space, the statistical parameters in struct Parameter are also transformed. This struct contains the transformed parameters. Specifically, the transformation is latents[t,:] = T0P_ + inv(T1X)*PCs[t,:].
In the latent factor space, the transition equation is data[t,:] = KPXF + GPXFXF*vec(data[t-1:-1:t-p,:]') + MvNormal(O,OmegaXFXF), where data = [latent macros].
latents::MatrixkappaQkQ_inftyKPXF::VectorGPXFXF::MatrixOmegaXFXF::Matrix
TermStructureModels.Parameter — Type
@kwdef struct Parameter <: PosteriorSampleThis struct contains the statistical parameters of the model that are sampled from function posterior_sampler.
kappaQkQ_infty::Float64phi::Matrix{Float64}varFF::Vector{Float64}SigmaO::Vector{Float64}gamma::Vector{Float64}
TermStructureModels.Parameter_NUTS — Type
@kwdef struct Parameter_NUTS <: PosteriorSampleThis struct contains the statistical parameters of the model that are sampled from function posterior_NUTS.
qnu0kappaQkQ_infty::Float64phi::Matrix{Float64}varFF::Vector{Float64}SigmaO::Vector{Float64}gamma::Vector{Float64}
TermStructureModels.PosteriorSample — Type
abstract type PosteriorSampleThis is a super-set of structs Parameter, ReducedForm, LatentSpace, YieldCurve, TermPremium, Forecast.
TermStructureModels.ReducedForm — Type
@kwdef struct ReducedForm <: PosteriorSampleThis struct contains the statistical parameters in terms of the reduced form VAR(p) in P-dynamics. lambdaP and LambdaPF are parameters in the market prices of risks equation, and they only contain the first dQ non-zero equations.
kappaQkQ_inftyKPFGPFFOmegaFF::MatrixSigmaO::VectorlambdaPLambdaPFmpr::Matrix(market prices of risks, T, dP)
TermStructureModels.Scenario — Type
@kwdef struct ScenarioThis struct contains scenarios to be conditioned in the scenario analysis. When y = [yields; macros] is an observed vector in the measurement equation, Scenario.combinations*y = Scenario.values constitutes the scenario at a specific time. Vector{Scenario} is used to describe a time-series of scenarios.
combinations and values should be Matrix and Vector. If values is a scalar, combinations would be a matrix with one row vector and values should be one-dimensional vector, for example [values].
combinations::Matrixvalues::Vector
TermStructureModels.TermPremium — Type
@kwdef struct TermPremium <: PosteriorSampleThe yields are decomposed into the term premium(TP) and the expectation hypothesis component(EH). Each component has constant terms(const_TP and const_EH) and time-varying components(timevarying_TP and timevarying_EH). factorloading_EH and factorloading_TP are coefficients of the pricing factors for the time varying components. Each column of the outputs indicates the results for each maturity.
The time-varying components are not stored in TermPremium, and they are the separate outputs in function term_premium.
- TP
- EH
- factorloading_TP
- factorloading_EH
- const_TP
- const_EH
TermStructureModels.YieldCurve — Type
@kwdef struct YieldCurve <: PosteriorSampleThis struct contains the fitted yield curve. yields[t,:] = intercept + slope*latents[t,:] holds.
latents::Matrix: latent pricing factors in LatentSpaceyieldsinterceptslope
Base.getindex — Method
getindex(x::PosteriorSample, c::Symbol)For struct <: PosteriorSample, struct[:name] calls objects in struct.
Base.getindex — Method
getindex(x::Vector{<:PosteriorSample}, c::Symbol)For struct <: PosteriorSample, struct[:name] calls objects in struct. Output[i] = the i-th posterior sample
Statistics.mean — Method
mean(x::Vector{<:PosteriorSample})Output[:variable name] returns the corresponding posterior mean.
Statistics.median — Method
median(x::Vector{<:PosteriorSample})Output[:variable name] returns the corresponding posterior median.
Statistics.quantile — Method
quantile(x::Vector{<:PosteriorSample}, q)Output[:variable name] returns a quantile of the corresponding posterior distribution.
Statistics.std — Method
std(x::Vector{<:PosteriorSample})Output[:variable name] returns the corresponding posterior standard deviation.
Statistics.var — Method
var(x::Vector{<:PosteriorSample})Output[:variable name] returns the corresponding posterior variance.
TermStructureModels.AR_res_var — Method
AR_res_var(TS::Vector, p)This function derives the MLE error variance estimate of an AR(p) model.
Input
- Univariate time series
TSand lagp
Output(2)
Residual variance estimate, AR(p) coefficients
TermStructureModels.GQ_XX — Method
GQ_XX(; kappaQ)kappaQ governs the conditional mean of the Q-dynamics of X, and its slope matrix has a restricted form. This function shows that restricted form.
Output
- slope matrix of the Q-conditional mean of
X
TermStructureModels.LDL — Method
LDL(X)This function generates a matrix decomposition called LDLt. X = L*D*L', where L is a lower triangular matrix and D is a diagonal. How to conduct it can be found at Wikipedia.
Input
- Decomposed Object,
X
Output(2)
L, D
- Decomposed result is
X = L*D*L'
TermStructureModels.PCA — Method
PCA(yields, p; pca_loadings=[], dQ=[])This function derives the principal components from yields.
Input
yields[p+1:end, :]is used to construct the affine transformation, and then allyields[:,:]are transformed into the principal components.pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA. 
Output(4)
PCs, OCs, Wₚ, Wₒ, mean_PCs
PCs,OCs: firstdQand the remaining principal componentsWₚ,Wₒ: the rotation matrix forPCsandOCs, respectivelymean_PCs: the mean ofPCsbefore being demeaned.PCsare demeaned.
TermStructureModels.calibrate_mean_phi_const — Method
calibrate_mean_phi_const(mean_kQ_infty, std_kQ_infty, nu0, yields, macros, tau_n, p; mean_phi_const_PCs=[], medium_tau=collect(24:3:48), iteration=1000, data_scale=1200, kappaQ_prior_pr=[], τ=[], pca_loadings=[])This function calibrates a prior mean of the first dQ constant terms in the VAR. Adjust your prior setting based on the prior samples in the outputs.
Input
mean_phi_const_PCsis your prior mean of the firstdQconstants. The default option sets it as a zero vector.iterationis the number of prior samples.τ::scalaris a maturity for calculating the constant part in the term premium.- If τ is empty, the function does not sample the prior distribution of the constant part in the term premium.
pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA.
Output(2)
prior_λₚ, prior_TP
- samples from the prior distribution of
λₚ - prior samples of the constant part in the τ-month term premium
TermStructureModels.conditional_expectation — Method
conditional_expectation(S::Vector, tau, horizon, saved_params, yields, macros, tau_n; baseline=[], mean_macros::Vector=[], data_scale=1200, pca_loadings=[], is_parallel=false)Input
scenarios, a result of the posterior sampler, and data
S[t]= conditioned scenario at timesize(yields, 1)+t.- Set
S = []if you need an unconditional prediction. - If you are conditioning a scenario, I assume S = Vector{Scenario}.
- Set
tauis a vector of maturities that term premiums of interest has.horizon: maximum length of the predicted path. It should not be smaller thanlength(S).saved_params: the first output of functionposterior_sampler.baseline::Vector{Forecast}:baselineis the output ofconditional_expectation. It is generally set as the result whenSis empty. When provided, the scenario inSshould be specified as deviations frombaseline(i.e., the scenario path is expressed relative tobaseline), and the output forecasts will also be returned as deviations frombaseline.mean_macros::Vector: If you demeaned macro variables, you can input the mean of the macro variables. Then, the output will be generated in terms of the un-demeaned macro variables.- If
mean_macroswas used as an input when derivingbaselinewith this function,mean_macrosshould also be included as an input when usingbaselineas an input. Conversely, ifmean_macroswas not used as an input when derivingbaseline, it should not be included as an input when usingbaseline. pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA.is_parallelenables multi-threaded parallel computation when set totrue.
Output
Vector{Forecast}(, iteration)t-th rows in predictedyields, predictedfactors, predictedTP, and predictedEHare the corresponding predicted value at timesize(yields, 1)+t.- Mathematically, it is a posterior distribution of
E[future obs|past obs, scenario, parameters], orE[future obs|past obs, scenario, parameters] - E[future obs|past obs, baseline, parameters]whenbaselineis provided.
TermStructureModels.conditional_forecast — Method
conditional_forecast(S::Vector, tau, horizon, saved_params, yields, macros, tau_n; baseline=[], mean_macros::Vector=[], data_scale=1200, pca_loadings=[], is_parallel=false)Input
scenarios, a result of the posterior sampler, and data
S[t]= conditioned scenario at timesize(yields, 1)+t.- If we need an unconditional prediction,
S = []. - If you are conditioning a scenario, I assume S = Vector{Scenario}.
- If we need an unconditional prediction,
tauis a vector. The term premium oftau[i]-bond is forecasted for each i.- If
tauis set to[], the term premium is not forecasted.
- If
horizon: maximum length of the predicted path. It should not be smaller thanlength(S).saved_params: the first output of functionposterior_sampler.baseline::Vector{Forecast}:baselineis the output ofconditional_forecast. It is generally set as the result whenSis empty. When provided, the scenario inSshould be specified as deviations frombaseline(i.e., the scenario path is expressed relative tobaseline), and the output forecasts will also be returned as deviations frombaseline.mean_macros::Vector: If you demeaned macro variables, you can input the mean of the macro variables. Then, the output will be generated in terms of the un-demeaned macro variables.- If
mean_macroswas used as an input when derivingbaselinewith this function,mean_macrosshould also be included as an input when usingbaselineas an input. Conversely, ifmean_macroswas not used as an input when derivingbaseline, it should not be included as an input when usingbaseline. pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA. is_parallelenables multi-threaded parallel computation when set totrue.
Output
Vector{Forecast}(, iteration)t-th rows in predictedyields, predictedfactors, predictedTP, and predictedEHare the corresponding predicted value at timesize(yields, 1)+t.- Mathematically, it is a posterior sample from
future observation|past observation,scenario, orfuture observation|past observation,scenariominusfuture observation|past observation,baselinewhenbaselineis provided.
TermStructureModels.dcurvature_dτ — Method
dcurvature_dτ(τ; kappaQ)This function calculates the first derivative of the curvature factor loading w.r.t. the maturity.
Input
kappaQ: The decay parameterτ: The maturity at which the derivative is calculated
Output
- the first derivative of the curvature factor loading w.r.t. the maturity
TermStructureModels.dimQ — Method
dimQ()This function returns the dimension of Q-dynamics under the standard ATSM.
TermStructureModels.erase_nonstationary_param — Method
erase_nonstationary_param(saved_params::Vector{Parameter_NUTS}; threshold=1)This function filters out posterior samples that imply a unit root VAR system. Only stationary posterior samples remain.
Input
saved_paramsis the output of functionposterior_NUTS.- Posterior samples with eigenvalues of the P-system greater than
thresholdare removed.
Output(2):
stationary samples, acceptance rate(%)
- The second output indicates how many posterior samples remain.
TermStructureModels.erase_nonstationary_param — Method
erase_nonstationary_param(saved_params::Vector{Parameter}; threshold=1)This function filters out posterior samples that imply a unit root VAR system. Only stationary posterior samples remain.
Input
saved_paramsis the first output of functionposterior_sampler.- Posterior samples with eigenvalues of the P-system greater than
thresholdare removed.
Output(2):
stationary samples, acceptance rate(%)
- The second output indicates how many posterior samples remain.
TermStructureModels.fitted_yieldcurve — Method
fitted_yieldcurve(tau_vec, saved_latent_params::Vector{LatentSpace}; data_scale=1200, is_parallel=false)This function generates the fitted yield curve.
Input
tau_vecis a set of maturities of interest.tau_vecdoes not need to be the same as the one used for the estimation.saved_latent_paramsis a transformed posterior sample using functionlatentspace.is_parallelenables multi-threaded parallel computation when set totrue.
Output
Vector{YieldCurve}(,# of iteration)yieldsandlatentscontain initial observations.
TermStructureModels.generative — Method
generative(T, dP, tau_n, p, noise::Float64; kappaQ, kQ_infty, KPXF, GPXFXF, OmegaXFXF, data_scale=1200)This function generates simulation data given parameters. Note that all parameters are in the latent factor state space (i.e., parameters in struct LatentSpace). There are some differences in notation because it is difficult to express mathcal letters in VSCode. Therefore, mathcal{F} in the paper is expressed as F in VSCode, and "F" in the paper is expressed as XF.
Input
noise: Variance of the measurement errors
Output(3)
yields, latents, macros
yields = Matrix{Float64}(obs,T,length(tau_n))latents = Matrix{Float64}(obs,T,dimQ())macros = Matrix{Float64}(obs,T,dP - dimQ())
TermStructureModels.hessian — Function
hessian(f, x, index=[])This function calculates the Hessian matrix of a scalar function f at x. If index is not empty, it calculates the Hessian matrix of the function with respect to the selected variables.
TermStructureModels.ineff_factor — Method
ineff_factor(saved_params::Vector{Parameter_NUTS}; is_parallel=false)This function returns the inefficiency factors for each parameter.
Input
Vector{Parameter_NUTS}fromposterior_NUTSis_parallelenables multi-threaded parallel computation when set totrue.
Output
- Estimated inefficiency factors are returned as a Tuple(
q,nu0,kappaQ,kQ_infty,gamma,SigmaO,varFF,phi). For example, if you want to access the inefficiency factor ofphi, you can useOutput.phi. - If
fix_const_PC1==truein your optimized Hyperparameter struct,Output.phi[1,1]may be unreliable and should be ignored.
TermStructureModels.ineff_factor — Method
ineff_factor(saved_params::Vector{Parameter}; is_parallel=false)This function returns the inefficiency factors for each parameter.
Input
Vector{Parameter}fromposterior_sampleris_parallelenables multi-threaded parallel computation when set totrue.
Output
- Estimated inefficiency factors are returned as a Tuple(
kappaQ,kQ_infty,gamma,SigmaO,varFF,phi). For example, if you want to access the inefficiency factor ofphi, you can useOutput.phi. - If
fix_const_PC1==truein your optimized Hyperparameter struct,Output.phi[1,1]may be unreliable and should be ignored.
TermStructureModels.isstationary — Method
isstationary(GPFF; threshold)This function checks whether a reduced VAR matrix has unit roots. If there is at least one unit root, the return is false.
Input
GPFFshould not include intercepts. Also,GPFFis adPbydP*pmatrix where the coefficient at lag 1 comes first, and the lagpslope matrix comes last.- Posterior samples with eigenvalues of the P-system greater than
thresholdare removed. Typically,thresholdis set to 1.
Output
boolean
TermStructureModels.latentspace — Method
latentspace(saved_params, yields, tau_n; data_scale=1200, pca_loadings=[], is_parallel=false)This function translates the principal components state space into the latent factor state space.
Input
data_scale::scalar: In typical affine term structure models, theoretical yields are in decimal and not annualized. However, for convenience (public data usually contains annualized percentage yields) and numerical stability, we sometimes want to scale up yields, so want to use (data_scale*theoretical yields) as variableyields. In this case, you can use thedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA. is_parallelenables multi-threaded parallel computation when set totrue.
Output
Vector{LatentSpace}(, iteration)- Latent factors contain initial observations.
TermStructureModels.log_marginal — Method
log_marginal(PCs, macros, rho, tuned::Hyperparameter, tau_n, Wₚ; psi=[], psi_const=[], medium_tau, kappaQ_prior_pr, fix_const_PC1)This file calculates a value of the marginal likelihood. Only the transition equation is used to calculate it.
Input
- tuned is a point where the marginal likelihood is evaluated.
psi_constandpsiare multiplied with prior variances of coefficients of the intercept and lagged regressors in the orthogonalized transition equation. They are used for imposing zero prior variances. An empty default value means that you do not use this function.[psi_const psi][i,j]corresponds tophi[:,1:1+dP*p][i,j].
Output
- the log marginal likelihood of the VAR system.
TermStructureModels.loglik_mea — Method
loglik_mea(yields, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, data_scale, pca_loadings)This function generates the log likelihood of the measurement equation.
Output
- the measurement equation part of the log likelihood
TermStructureModels.loglik_tran — Method
loglik_tran(PCs, macros; phi, varFF)This function calculates the log likelihood of the transition equation.
Output
- log likelihood of the transition equation.
TermStructureModels.phi_2_phi₀_C — Method
phi_2_phi₀_C(; phi)This function divides phi into the lagged regressor part and the contemporaneous regressor part.
Output(3)
phi0, C = C0 + I, C0
phi0: coefficients for the lagged regressorsC: coefficients for the dependent variables when all contemporaneous variables are on the LHS of the orthogonalized equations. Therefore, the diagonals ofCare ones. Note that since the contemporaneous variables get negative signs when they are on the RHS, the signs ofCdo not change whether they are on the RHS or LHS.
TermStructureModels.phi_varFF_2_OmegaFF — Method
phi_varFF_2_OmegaFF(; phi, varFF)This function constructs OmegaFF from statistical parameters.
Output
OmegaFF
TermStructureModels.posterior_NUTS — Method
posterior_NUTS(p, yields, macros, tau_n, rho, NUTS_nadapt, iteration; init_param=[], prior_q, prior_nu0, psi=[], psi_const=[], gamma_bar=[], prior_mean_diff_kappaQ, prior_std_diff_kappaQ, mean_kQ_infty=0, std_kQ_infty=0.1, fix_const_PC1=false, data_scale=1200, pca_loadings=[], NUTS_target_acceptance_rate=0.65, NUTS_max_depth=10)This function implements the NUTS-within-Gibbs sampler. Gibbs blocks that cannot be updated with conjugate priors are sampled using the NUTS sampler.
Input
p: The lag length of the VAR systemNUTS_nadapt: Number of iterations for tuning settings in the NUTS sampler. The warmup samples are included in the output, so you should discard them.iteration: Number of posterior samplesinit_param: Starting point of the sampler. It should be of type Parameter_NUTS.prior_q: A 4 by 2 matrix that contains the prior distribution for q. All entries should be objects inDistributions.jl. For hyperparameters that do not need to be optimized, assigning aDirac(::Float64)prior to the corresponding entry fixes that hyperparameter and optimizes only the remaining hyperparameters.prior_nu0: The prior distribution for nu0 - (dP + 1). It should be an object inDistributions.jl.psi_constandpsiare multiplied with prior variances of coefficients of the intercept and lagged regressors in the orthogonalized transition equation. They are used for imposing zero prior variances. An empty default value means that you do not use this function.[psi_const psi][i,j]corresponds tophi[:,1:1+dP*p][i,j].psishould be a (dP × dP*p) matrix.prior_mean_diff_kappaQandprior_std_diff_kappaQare vectors that contain the means and standard deviations of the Normal distributions for[kappaQ[1]; diff(kappaQ)]. Once Normal priors are assigned to these parameters, the prior forkappaQ[1]is truncated to (0, 1), and the priors fordiff(kappaQ)are truncated to (−1, 0).pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA. NUTS_target_acceptance_rate,NUTS_max_depthare the arguments of the NUTS sampler inAdvancedHMC.jl.
Output
Vector{Parameter_NUTS}(posterior, iteration)
TermStructureModels.posterior_sampler — Method
posterior_sampler(yields, macros, tau_n, rho, iteration, tuned::Hyperparameter; medium_tau=collect(24:3:48), init_param=[], psi=[], psi_const=[], gamma_bar=[], kappaQ_prior_pr=[], mean_kQ_infty=0, std_kQ_infty=0.1, fix_const_PC1=false, data_scale=1200, pca_loadings=[], kappaQ_proposal_mode=[])This function samples from the posterior distribution.
Input
iteration: Number of posterior samplestuned: Optimized hyperparameters used during estimationinit_param: Starting point of the sampler. It should be of type Parameter.psi_constandpsiare multiplied with prior variances of coefficients of the intercept and lagged regressors in the orthogonalized transition equation. They are used for imposing zero prior variances. An empty default value means that you do not use this function.[psi_const psi][i,j]corresponds tophi[:,1:1+dP*p][i,j].psishould be a (dP × dP*p) matrix.kappaQ_prior_pris a vector of prior distributions forkappaQunder the JSZ model: each element specifies the prior forkappaQ[i]and must be provided as aDistributions.jlobject. This option is only needed when using the JSZ model.pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA.kappaQ_proposal_mode=Vector{, dQ}contains the center of the proposal distribution forkappaQ. If it is empty, it is optimized by MLE.
Output(2)
Vector{Parameter}(posterior, iteration), acceptance rate of the MH algorithm
TermStructureModels.prior_kappaQ — Method
prior_kappaQ(medium_tau, pr)This function derives the maximizer decay parameter kappaQ that maximizes the curvature factor loading at each candidate medium-term maturity. Then, it imposes a discrete prior distribution on the maximizers with a prior probability vector pr.
Input
medium_tau::Vector(candidate medium maturities, # of candidates)pr::Vector(probability, # of candidates)
Output
- discrete prior distribution that has a support of the maximizers
kappaQ
TermStructureModels.reducedform — Method
reducedform(saved_params, yields, macros, tau_n; data_scale=1200, pca_loadings=[], is_parallel=false)This function converts posterior samples to the reduced form VAR parameters.
Input
saved_paramsis the first output of functionposterior_sampler.pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA.is_parallelenables multi-threaded parallel computation when set totrue.
Output
- Posterior samples in terms of struct
ReducedForm
TermStructureModels.term_premium — Method
term_premium(tau_interest, tau_n, saved_params, yields, macros; data_scale=1200, pca_loadings=[], is_parallel=false)This function generates posterior samples of the term premiums.
Input
- Maturity of interest
tau_interestfor calculatingTP saved_paramsfrom functionposterior_samplerpca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA. is_parallelenables multi-threaded parallel computation when set totrue.
Output(3)
saved_TP, saved_tv_TP, saved_tv_EH
saved_TP::Vector{TermPremium}(, iteration)saved_tv_TP::Vector{Array}(, iteration)saved_tv_EH::Vector{Array}(, iteration)- Both the term premiums and expectation hypothesis components are decomposed into the time-invariant part and time-varying part. For the maturity
tau_interest[i]andj-th posterior sample, the time-varying parts are saved insaved_tv_TP[j][:, :, i]andsaved_tv_EH[j][:, :, i]. The time-varying parts driven by thek-th pricing factor are stored insaved_tv_TP[j][:, k, i]andsaved_tv_EH[j][:, k, i].
TermStructureModels.tuning_hyperparameter — Method
tuning_hyperparameter(yields, macros, tau_n, rho; populationsize=50, maxiter=10_000, medium_tau=collect(24:3:48), upper_q=[1 1; 1 1; 1 1; 4 4; 100 100], mean_kQ_infty=0, std_kQ_infty=0.1, upper_nu0=[], mean_phi_const=[], fix_const_PC1=false, upper_p=24, mean_phi_const_PC1=[], data_scale=1200, kappaQ_prior_pr=[], init_nu0=[], is_pure_EH=false, psi=[], psi_const=[], pca_loadings=[], prior_mean_diff_kappaQ=[], prior_std_diff_kappaQ=[], optimizer=:LBFGS, ml_tol=1.0, init_x=[])This function optimizes the hyperparameters by maximizing the marginal likelihood of the transition equation.
Input
- When comparing marginal likelihoods between models, the data for the dependent variable should be the same across models. To achieve this, we set the period of the dependent variable based on
upper_p. For example, ifupper_p = 3,yields[4:end,:]andmacros[4:end,:]are the data for the dependent variable.yields[1:3,:]andmacros[1:3,:]are used for setting initial observations for all lags. optimizer: The optimization algorithm to use.:LBFGS(default): Uses unconstrained LBFGS fromOptim.jlwith hybrid parameter transformations (exp for non-negativity, sigmoid for bounded parameters). Alternates between optimizing hyperparameters (with fixed lag) and selecting the best lag (with fixed hyperparameters) until convergence.:BBO: Uses a differential evolutionary algorithm (BlackBoxOptim.jl). The lag and hyperparameters are optimized simultaneously.
ml_tol: Tolerance for parsimony in lag selection (only for:LBFGS). After finding the lag with the best marginal likelihood, the algorithm iteratively selects smaller lags if their marginal likelihood is withinml_tolof the best. This favors simpler models (smaller lags) when performance is comparable.init_x: Initial values for hyperparameters and lag (only for:LBFGS). Should be a vector of length 12 in the format[vec(q); nu0-(dP+1); p]. If empty (default), uses[0.1, 0.1, 0.1, 2.0, 1.0, 0.1, 0.1, 0.1, 2.0, 1.0, 1.0, 1].populationsizeandmaxiterare options for the optimizer.populationsize: the number of candidate solutions in each generation (only for:BBO)maxiter: the maximum number of iterations
- The lower bounds for
qandnu0are0anddP+2. - The upper bounds for
q,nu0, and VAR lag can be set byupper_q,upper_nu0, andupper_p.- The default option for
upper_nu0is the time-series length of the data.
- The default option for
- If you use the default option for
mean_phi_const,mean_phi_const[dQ+1:end]is a zero vector.mean_phi_const[1:dQ]is calibrated to make the prior mean ofλₚa zero vector.- After step 2,
mean_phi_const[1]is replaced withmean_phi_const_PC1if it is not empty.
mean_phi_const = Matrix(your prior, dP, upper_p)mean_phi_const[:,i]is the prior mean for the VAR(i) constant. Therefore,mean_phi_constis a matrix only in this function. In other functions,mean_phi_constis a vector for the orthogonalized VAR system with the selected lag.- When
fix_const_PC1==true, the first element in the constant term in the orthogonalized VAR is fixed to its prior mean during posterior sampling. data_scale::scalar: In a typical affine term structure model, theoretical yields are in decimals and not annualized. However, for convenience (public data usually contains annualized percentage yields) and numerical stability, we sometimes want to scale up yields and use (data_scale*theoretical yields) as the variableyields. In this case, you can use thedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.kappaQ_prior_pris a vector of prior distributions forkappaQunder the JSZ model: each element specifies the prior forkappaQ[i]and must be provided as aDistributions.jlobject. Alternatively, you can supplyprior_mean_diff_kappaQandprior_std_diff_kappaQ, which define means and standard deviations for Normal priors on[kappaQ[1]; diff(kappaQ)]; the implied Normal prior for eachkappaQ[i]is then truncated to (0, 1). These options are only needed when using the JSZ model.is_pure_EH::Bool: Whenmean_phi_const=[],is_pure_EH=falsesetsmean_phi_constto zero vectors. Otherwise,mean_phi_constis set to imply the pure expectation hypothesis undermean_phi_const=[].psi_constandpsiare multiplied with prior variances of coefficients of the intercept and lagged regressors in the orthogonalized transition equation. They are used for imposing zero prior variances. An empty default value means that you do not use this function.[psi_const psi][i,j]corresponds tophi[:,1:1+dP*p][i,j].psiis a (dP × dPupperp) matrix; when a shorter lag p < upperp is selected, `psi[:, 1:dPp]` is automatically used.pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA.
Output(2)
Optimized hyperparameter, optimization result
- Note that we minimize the negative log marginal likelihood, so the second output is for the minimization problem.
- When
optimizer=:LBFGS, the second output is a NamedTuple with fieldsminimizer,minimum,p,all_minimizer,all_minimum.
TermStructureModels.tuning_hyperparameter_with_vs — Method
tuning_hyperparameter_with_vs(yields, macros, tau_n, rho; populationsize=50, maxiter=10_000, medium_tau=collect(24:3:48), upper_q=[1 1; 1 1; 1 1; 4 4; 100 100], mean_kQ_infty=0, std_kQ_infty=0.1, upper_nu0=[], mean_phi_const=[], fix_const_PC1=false, upper_p=24, mean_phi_const_PC1=[], data_scale=1200, kappaQ_prior_pr=[], init_nu0=[], is_pure_EH=false, psi_const=[], pca_loadings=[], prior_mean_diff_kappaQ=[], prior_std_diff_kappaQ=[], optimizer=:LBFGS, ml_tol=1.0, init_x=[])This function optimizes the hyperparameters with automatic variable selection: selects which macro variables affect latent factors (PCs).
Input
- When comparing marginal likelihoods between models, the data for the dependent variable should be the same across models. To achieve this, we set the period of the dependent variable based on
upper_p. For example, ifupper_p = 3,yields[4:end,:]andmacros[4:end,:]are the data for the dependent variable.yields[1:3,:]andmacros[1:3,:]are used for setting initial observations for all lags. optimizer: The optimization algorithm to use.:LBFGS(default): Alternates between lag selection, forward stepwise variable selection for coefficients of macro variables on latent factors, and hyperparameter optimization. Variable selection stops when log marginal likelihood improvement ≤ 1.0.:BBO: Uses BlackBoxOptim.jl to optimize lag, hyperparameters, and variable selection simultaneously.
ml_tol: Tolerance for parsimony in lag selection (only for:LBFGS). After finding the lag with the best marginal likelihood, the algorithm iteratively selects smaller lags if their marginal likelihood is withinml_tolof the best. This favors simpler models (smaller lags) when performance is comparable.init_x: Initial values for hyperparameters and lag (only for:LBFGS). Should be a vector of length 12 in the format[vec(q); nu0-(dP+1); p]. If empty (default), uses[0.1, 0.1, 0.1, 2.0, 1.0, 0.1, 0.1, 0.1, 2.0, 1.0, 1.0, 1].populationsizeandmaxiterare options for the optimizer.populationsize: the number of candidate solutions in each generation (only for:BBO)maxiter: the maximum number of iterations
- The lower bounds for
qandnu0are0anddP+2. - The upper bounds for
q,nu0, and VAR lag can be set byupper_q,upper_nu0, andupper_p.- The default option for
upper_nu0is the time-series length of the data.
- The default option for
- If you use the default option for
mean_phi_const,mean_phi_const[dQ+1:end]is a zero vector.mean_phi_const[1:dQ]is calibrated to make the prior mean ofλₚa zero vector.- After step 2,
mean_phi_const[1]is replaced withmean_phi_const_PC1if it is not empty.
mean_phi_const = Matrix(your prior, dP, upper_p)mean_phi_const[:,i]is the prior mean for the VAR(i) constant. Therefore,mean_phi_constis a matrix only in this function. In other functions,mean_phi_constis a vector for the orthogonalized VAR system with the selected lag.- When
fix_const_PC1==true, the first element in the constant term in the orthogonalized VAR is fixed to its prior mean during posterior sampling. data_scale::scalar: In a typical affine term structure model, theoretical yields are in decimals and not annualized. However, for convenience (public data usually contains annualized percentage yields) and numerical stability, we sometimes want to scale up yields and use (data_scale*theoretical yields) as the variableyields. In this case, you can use thedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.kappaQ_prior_pris a vector of prior distributions forkappaQunder the JSZ model: each element specifies the prior forkappaQ[i]and must be provided as aDistributions.jlobject. Alternatively, you can supplyprior_mean_diff_kappaQandprior_std_diff_kappaQ, which define means and standard deviations for Normal priors on[kappaQ[1]; diff(kappaQ)]; the implied Normal prior for eachkappaQ[i]is then truncated to (0, 1). These options are only needed when using the JSZ model.is_pure_EH::Bool: Whenmean_phi_const=[],is_pure_EH=falsesetsmean_phi_constto zero vectors. Otherwise,mean_phi_constis set to imply the pure expectation hypothesis undermean_phi_const=[].psi_constis multiplied with the prior variance of the intercept coefficients in the orthogonalized transition equation.pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA.
Output(3)
Optimized hyperparameter, optimization result, psi matrix
- The second output contains optimization results: when
optimizer=:LBFGS, a NamedTuple withminimizer,minimum,p,all_minimizer,all_minimum,selected_vars,psi; whenoptimizer=:BBO, a NamedTuple withopt(bboptimize result),selected_vars,psi.selected_varsis a sorted list of (lag, variable) tuples indicating which columns are included beyond the always-included columns 1:dQ. - The third output is
psi(dP × dPp), the prior variance scaling matrix for lagged regressors in the orthogonalized transition equation. Backward variable selection is applied to all columns except lag-1 latent factors (j ≤ dQ, k = 1): settingpsi[1:dQ, col] = 0excludes a variable's effect on latent factors. For lag k, variable j, the column index is (k-1)dP+j.
Internal Functions
TermStructureModels.Aₓ — Method
Aₓ(aτ_, tau_n)Input
aτ_is an output of functionaτ.
Output
Aₓ
TermStructureModels.Aₚ — Method
Aₚ(Aₓ_, Bₓ_, T0P_, Wₒ)Input
Aₓ_,Bₓ_, andT0P_are outputs of functionAₓ,Bₓ, andT0P, respectively.
Output
Aₚ
TermStructureModels.Bₓ — Method
Bₓ(bτ_, tau_n)Input
bτ_is an output of functionbτ.
Output
Bₓ
TermStructureModels.Bₚ — Method
Bₚ(Bₓ_, T1X_, Wₒ)Input
Bₓ_andT1X_are outputs of functionBₓandT1X, respectively.
Output
Bₚ
TermStructureModels.Kphi — Method
Kphi(i, V, Xphi, dP)TermStructureModels.NIG_NIG — Method
NIG_NIG(y, X, β₀, B₀, α₀, δ₀)Normal-InverseGamma-Normal-InverseGamma update
- prior:
β|σ² ~ MvNormal(β₀,σ²B₀),σ² ~ InverseGamma(α₀,δ₀) - likelihood:
y|β,σ² = Xβ + MvNormal(zeros(T,1),σ²I(T))
Output(2)
β, σ²
- posterior sample
TermStructureModels.PCs_2_latents — Method
PCs_2_latents(yields, tau_n; kappaQ, kQ_infty, KPF, GPFF, OmegaFF, data_scale, pca_loadings=[])Notation XF is for the latent factor space and notation F is for the PC state space.
Input
data_scale::scalar: In typical affine term structure models, theoretical yields are in decimal and not annualized. However, for convenience (public data usually contains annualized percentage yields) and numerical stability, we sometimes want to scale up yields, so want to use (data_scale*theoretical yields) as variableyields. In this case, you can use thedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA. 
Output(6)
latent, kappaQ, kQ_infty, KPXF, GPXFXF, OmegaXFXF
- Latent factors contain initial observations.
TermStructureModels.S — Method
S(i; Omega0)TermStructureModels.S_hat — Method
S_hat(i, m, V, yphi, Xphi, dP; Omega0)TermStructureModels.T0P — Method
T0P(T1X_, Aₓ_, Wₚ, c)Input
T1X_andAₓ_are outputs of functionT1XandAₓ, respectively.cis a sample mean ofPCs.
Output
T0P
TermStructureModels.T1X — Method
T1X(Bₓ_, Wₚ)Input
Bₓ_is an output of functionBₓ.
Output
T1X
TermStructureModels._conditional_expectation — Method
_conditional_expectation(S, τ, horizon, yields, macros, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, mean_macros, data_scale, pca_loadings)TermStructureModels._conditional_forecast — Method
_conditional_forecast(S, τ, horizon, yields, macros, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, mean_macros, data_scale, pca_loadings)TermStructureModels._termPremium — Method
_termPremium(τ, PCs, macros, bτ_, T0P_, T1X_; kappaQ, kQ_infty, KPF, GPFF, ΩPP, data_scale)This function calculates the term premium for maturity τ.
Input
data_scale::scalar= In typical affine term structure models, theoretical yields are in decimal and not annualized. However, for convenience (public data usually contains annualized percentage yields) and numerical stability, we sometimes want to scale up yields, so want to use (data_scale*theoretical yields) as variableyields. In this case, you can use thedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.
Output(4)
TP, timevarying_TP, const_TP, jensen
TP: term premium of maturityτtimevarying_TP: contributions of each[PCs macros]onTPat each time $t$ (row: time, col: variable)const_TP: Constant part ofTPjensen: Jensen's Inequality part inTP- The output excludes the time period for the initial observations.
TermStructureModels._unconditional_expectation — Method
_unconditional_expectation(τ, horizon, yields, macros, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, mean_macros, data_scale, pca_loadings)TermStructureModels._unconditional_forecast — Method
_unconditional_forecast(τ, horizon, yields, macros, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, mean_macros, data_scale, pca_loadings)TermStructureModels.aτ — Method
aτ(N, bτ_, tau_n, Wₚ; kQ_infty, ΩPP, data_scale)
aτ(N, bτ_; kQ_infty, ΩXX, data_scale)This function has two methods (multiple dispatch).
Input
- When
Wₚ∈ arguments: This function calculatesaτusingΩPP. - Otherwise: This function calculates
aτusingΩXX = OmegaXFXF[1:dQ, 1:dQ], so parameters are in the latent factor space andWₚis not needed. bτ_is an output of functionbτ.data_scale::scalar: In typical affine term structure models, theoretical yields are in decimal and not annualized. However, for convenience (public data usually contains annualized percentage yields) and numerical stability, we sometimes want to scale up yields, so want to use (data_scale*theoretical yields) as variableyields. In this case, you can use thedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.
Output
Vector(Float64)(aτ,N)- For the
i-th maturity,Output[i]is the correspondingaτ.
TermStructureModels.btau — Method
btau(N; kappaQ)This function solves the difference equation for bτ in the closed form expression, assuming the distinct eigenvalues under the JSZ model.
Output
- For maturity
i,btau[:, i]is a vector of factor loadings.
TermStructureModels.bτ — Method
bτ(N; kappaQ, dQ)This function solves the difference equation for bτ.
Output
- For maturity
i,bτ[:, i]is a vector of factor loadings.
TermStructureModels.jensens_inequality — Method
jensens_inequality(τ, bτ_, T1X_; ΩPP, data_scale)This function evaluates the Jensen's Inequality term. All terms are invariant with respect to the data_scale, except for this Jensen's inequality term, so the term needs to be scaled down by data_scale.
Output
- Jensen's Inequality term for
aτof maturityτ.
TermStructureModels.loglik_NUTS — Method
loglik_NUTS(i, yields, PCs, tau_n, macros, dims_phi, p; phiQ, varFFQ, diff_kappaQ, kQ_infty, phi, varFF, SigmaO, data_scale, pca_loadings)This function calculates the likelihood of the NUTS block.
TermStructureModels.loglik_mea2 — Method
loglik_mea2(yields, tau_n, p; kappaQ, kQ_infty, ΩPP, SigmaO, data_scale, pca_loadings)This function is the same as loglik_mea but it requires ΩPP as an input.
TermStructureModels.loglik_mea_NUTS — Method
loglik_mea_NUTS(yields, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, data_scale, pca_loadings)This function generates the log likelihood of the measurement equation. It is used for posterior_NUTS.
Output
- the measurement equation part of the log likelihood
TermStructureModels.logprior_C — Method
logprior_C(C; Omega0::Vector)This is a companion function of prior_C. It calculates the log density of the prior distribution for C.
TermStructureModels.logprior_phi0 — Method
logprior_phi0(phi0, mean_phi_const, rho::Vector, GQ_XX_mean, p, dQ, dP; psi_const, psi, q, nu0, Omega0, fix_const_PC1)This is a companion function of prior_phi0. It calculates the log density of the prior distribution for phi0.
TermStructureModels.logprior_varFF — Method
logprior_varFF(varFF; nu0, Omega0::Vector)This is a companion function of prior_varFF. It calculates the log density of the prior distribution for varFF.
TermStructureModels.longvar — Method
longvar(v)This function calculates the long-run variance of v using the quadratic spectral window with bandwidth selection of Andrews (1991). The AR(1) approximation is used.
Input
- Time-series vector
v
Output
- Estimated 2πh(0) of
v, where h(x) is the spectral density ofvat x.
TermStructureModels.minnesota — Method
minnesota(l, i, j; q, nu0, Omega0, dQ=[])This function returns the unscaled prior variance of the Minnesota prior.
Input
- lag
l, dependent variablei, regressorjin the VAR(p) q[:,1]andq[:,2]are [own, inner cross, outer cross, lag, intercept] shrinkages for the firstdQand remainingdP-dQequations, respectively. Here, when the dependent variable is a principal component, inner cross refers to the other principal components (excluding itself), whereas outer cross refers to the macroeconomic variables. Likewise, when the dependent variable is a macroeconomic variable, inner cross refers to the other macroeconomic variables (excluding itself), whereas outer cross refers to the principal components.nu0(d.f.),Omega0(scale): Inverse-Wishart prior for the error-covariance matrix of VAR(p).
Output
- Minnesota part in the prior variance
TermStructureModels.mle_error_covariance — Method
mle_error_covariance(yields, macros, tau_n, p; pca_loadings=[])This function calculates the MLE estimates of the error covariance matrix of the VAR(p) model.
pca_loadings=Matrix{, dQ, size(yields, 2)}stores the loadings for the first dQ principal components (soprincipal_components = yields * pca_loadings'), and you may optionally provide these loadings externally; if omitted, the package computes them internally via PCA. 
TermStructureModels.phi_hat — Method
phi_hat(i, m, V, yphi, Xphi, dP)TermStructureModels.phi_varFF_2_ΩPP — Method
phi_varFF_2_ΩPP(; phi, varFF, dQ=[])This function constructs ΩPP from statistical parameters.
Output
ΩPP
TermStructureModels.post_SigmaO — Method
post_SigmaO(yields, tau_n; kappaQ, kQ_infty, ΩPP, gamma, p, data_scale, pca_loadings)Posterior sampler for the measurement errors
Output
Vector{Dist}(IG, N-dQ)
TermStructureModels.post_gamma — Method
post_gamma(; gamma_bar, SigmaO)Posterior sampler for the population measurement error
Output
Vector{Dist}(Gamma,length(SigmaO))
TermStructureModels.post_kQ_infty — Method
post_kQ_infty(mean_kQ_infty, std_kQ_infty, yields, tau_n; kappaQ, phi, varFF, SigmaO, data_scale, pca_loadings)Output
- Full conditional posterior distribution
TermStructureModels.post_kappaQ — Method
post_kappaQ(yields, prior_kappaQ_, tau_n; kQ_infty, phi, varFF, SigmaO, data_scale, pca_loadings)Input
prior_kappaQ_is an output of functionprior_kappaQ.
Output
- Full conditional posterior distribution
TermStructureModels.post_kappaQ2 — Method
post_kappaQ2(yields, prior_kappaQ_, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, data_scale, x_mode, inv_x_hess, pca_loadings)This function conducts the Metropolis-Hastings algorithm for the reparameterized kappaQ under the unrestricted JSZ form. x_mode and inv_x_hess constitute the mean and variance of the Normal proposal distribution.
- Reparameterization: kappaQ[1] = x[1] kappaQ[2] = x[1] + x[2] kappaQ[3] = x[1] + x[2] + x[3]
- Jacobian: [1 0 0 1 1 0 1 1 1]
- The determinant = 1
TermStructureModels.post_kappaQ_phi_varFF_q_nu0 — Method
post_kappaQ_phi_varFF_q_nu0(yields, macros, tau_n, mean_phi_const, rho, prior_q, prior_nu0, prior_diff_kappaQ; phi, psi, psi_const, varFF, q, nu0, kappaQ, kQ_infty, SigmaO, fix_const_PC1, data_scale, pca_loadings, sampler, chain, is_warmup)Full-conditional posterior sampler for kappaQ, phi and varFF
Input
prior_q: The 4 by 2 matrix that contains the prior distribution for q. All entries should be objects inDistributions.jl.prior_nu0: The prior distribution for nu0 - (dP + 1). It should be an object inDistributions.jl.prior_diff_kappaQis a vector of the truncated normals(Distributions.truncated(Distributions.Normal(), lower, upper)). It has a prior for[kappaQ[1]; diff(kappaQ)].- When
fix_const_PC1==true, the first element in a constant term in the orthogonalized VAR is fixed to its prior mean during the posterior sampling. samplerandchainare the objects inTuring.jl.- If the current step is in the warmup phase, set
is_warmup=true.
Output(6)
chain, q, nu0, kappaQ, phi, varFF
TermStructureModels.post_phi_varFF — Method
post_phi_varFF(yields, macros, mean_phi_const, rho, prior_kappaQ_, tau_n; phi, psi, psi_const, varFF, q, nu0, Omega0, kappaQ, kQ_infty, SigmaO, fix_const_PC1, data_scale, pca_loadings)Full-conditional posterior sampler for phi and varFF
Input
prior_kappaQ_is an output of functionprior_kappaQ.- When
fix_const_PC1==true, the first element in a constant term in the orthogonalized VAR is fixed to its prior mean during the posterior sampling.
Output(3)
phi, varFF, isaccept=Vector{Bool}(undef, dQ)
- Returns a posterior sample.
TermStructureModels.prior_C — Method
prior_C(; Omega0::Vector)This function translates the Inverse-Wishart prior to a series of the Normal-Inverse-Gamma (NIG) prior distributions. If the dimension is dₚ, there are dₚ NIG prior distributions. This function generates Normal priors.
Output:
- unscaled prior of
Cin the LDLt decomposition,OmegaFF = inv(C)*diagm(varFF)*inv(C)'
Important note
prior variance for C[i,:] = varFF[i]*variance of output[i,:]
TermStructureModels.prior_gamma — Method
prior_gamma(yields, p; pca_loadings)There is a hierarchical structure in the measurement equation. The prior means of the measurement errors are gamma[i] and each gamma[i] follows Gamma(1,gamma_bar) distribution. This function decides gamma_bar empirically. OLS is used to estimate the measurement equation and then a variance of residuals is calculated for each maturity. An inverse of the average residual variances is set to gamma_bar.
Output
- hyperparameter
gamma_bar
TermStructureModels.prior_phi0 — Method
prior_phi0(mean_phi_const, rho::Vector, prior_kappaQ_, tau_n, Wₚ; psi_const, psi, q, nu0, Omega0, fix_const_PC1)This function derives the prior distribution for coefficients of the lagged regressors in the orthogonalized VAR.
Input
prior_kappaQ_is an output of functionprior_kappaQ.- When
fix_const_PC1==true, the first element in a constant term in the orthogonalized VAR is fixed to its prior mean during the posterior sampling.
Output
- Normal prior distributions on the slope coefficient of lagged variables and intercepts in the orthogonalized equation.
Output[:,1]for intercepts,Output[:,1+1:1+dP]for the first lag,Output[:,1+dP+1:1+2*dP]for the second lag, and so on.
Important note
prior variance for phi[i,:] = varFF[i]*var(output[i,:])
TermStructureModels.prior_varFF — Method
prior_varFF(; nu0, Omega0::Vector)This function translates the Inverse-Wishart prior to a series of the Normal-Inverse-Gamma (NIG) prior distributions. If the dimension is dₚ, there are dₚ NIG prior distributions. This function generates Inverse-Gamma priors.
Output:
- prior of
varFFin the LDLt decomposition,OmegaFF = inv(C)*diagm(varFF)*inv(C)' - Each element in the output follows Inverse-Gamma priors.
TermStructureModels.yphi_Xphi — Method
yphi_Xphi(PCs, macros, p)This function generates the dependent variable and the corresponding regressors in the orthogonalized transition equation.
Output(4)
yphi, Xphi = [ones(T - p) Xphi_lag Xphi_contemporaneous], [ones(T - p) Xphi_lag], Xphi_contemporaneous
yphiandXphiis a full matrix. For the i'th equation, the dependent variable isyphi[:,i]and the regressor isXphi.Xphiis the same for all orthogonalized transition equations. The orthogonalized equations are different in terms of contemporaneous regressors. Therefore, the corresponding regressors inXphishould be excluded. The form of parameterphiperforms that task by setting the coefficients of the excluded regressors to zeros. In particular, for the lastdPbydPblock inphi, the diagonals and the upper diagonal elements should be zero.
TermStructureModels.ν — Method
ν(i, dP; nu0)