API documentation
Index
TermStructureModels.ForecastTermStructureModels.HyperparameterTermStructureModels.LatentSpaceTermStructureModels.ParameterTermStructureModels.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.MinnesotaTermStructureModels.NIG_NIGTermStructureModels.PCATermStructureModels.PCs_2_latentsTermStructureModels.STermStructureModels.S_hatTermStructureModels.T0PTermStructureModels.T1XTermStructureModels._conditional_forecastsTermStructureModels._scenario_analysisTermStructureModels._scenario_analysis_unconditionalTermStructureModels._termPremiumTermStructureModels._unconditional_forecastsTermStructureModels.aτTermStructureModels.bτTermStructureModels.calibrate_mean_phi_constTermStructureModels.conditional_forecastsTermStructureModels.dcurvature_dτTermStructureModels.dimQTermStructureModels.erase_nonstationary_paramTermStructureModels.fitted_YieldCurveTermStructureModels.generativeTermStructureModels.hessianTermStructureModels.ineff_factorTermStructureModels.isstationaryTermStructureModels.jensens_inequalityTermStructureModels.latentspaceTermStructureModels.log_marginalTermStructureModels.loglik_meaTermStructureModels.loglik_mea2TermStructureModels.loglik_tranTermStructureModels.longvarTermStructureModels.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_phi_varFFTermStructureModels.posterior_samplerTermStructureModels.prior_CTermStructureModels.prior_gammaTermStructureModels.prior_kappaQTermStructureModels.prior_phi0TermStructureModels.prior_varFFTermStructureModels.reducedformTermStructureModels.scenario_analysisTermStructureModels.term_premiumTermStructureModels.tuning_hyperparameterTermStructureModels.yphi_XphiTermStructureModels.ν
Exported Functions
TermStructureModels.Forecast — Type@kwdef struct Forecast <: PosteriorSampleIt contains a result of the scenario analysis, the conditional prediction for yields, factors = [PCs macros], and term premiums.
yieldsfactorsTP: term premium forecasts
TermStructureModels.Hyperparameter — Type@kwdef struct Hyperparameterp::Intq::Matrixnu0Omega0::Vectormean_phi_const::Vector = zeros(length(Omega0)): It is a prior mean of a constant term in our 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 <: PosteriorSampleIt contains 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.PosteriorSample — Typeabstract type PosteriorSampleIt is a super-set of structs Parameter, ReducedForm, LatentSpace, YieldCurve, TermPremium, Forecast.
TermStructureModels.ReducedForm — Type@kwdef struct ReducedForm <: PosteriorSampleIt contains 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 ScenarioIt contains scenarios to be conditioned in the scenario analysis. When y = [yields; macros] is a observed vector in our 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 raw 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 components have 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.
We do not store time-varying components in TermPremium, and the time-varying components are the separate outputs in function term_premium.
- TP
- EH
- factorloading_TP
- factorloading_EH
- const_TP
- const_EH
TermStructureModels.YieldCurve — Type@kwdef struct YieldCurve <: PosteriorSampleIt contains a fitted yield curve. yields[t,:] = intercept + slope*latents[t,:] holds.
latents::Matrix: latent pricing factors in LatentSpaceyieldsinterceptslope
Base.getindex — Methodgetindex(x::PosteriorSample, c::Symbol)For struct <: PosteriorSample, struct[:name] calls objects in struct.
Base.getindex — Methodgetindex(x::Vector{<:PosteriorSample}, c::Symbol)For struct <: PosteriorSample, struct[:name] calls objects in struct. Output[i] = $i'$th posterior sample
Statistics.mean — Methodmean(x::Vector{<:PosteriorSample})Output[:variable name] returns the corresponding posterior mean.
Statistics.median — Methodmedian(x::Vector{<:PosteriorSample})Output[:variable name] returns the corresponding posterior median.
Statistics.quantile — Methodquantile(x::Vector{<:PosteriorSample}, q)Output[:variable name] returns a quantile of the corresponding posterior distribution.
Statistics.std — Methodstd(x::Vector{<:PosteriorSample})Output[:variable name] returns the corresponding posterior standard deviation.
Statistics.var — Methodvar(x::Vector{<:PosteriorSample})Output[:variable name] returns the corresponding posterior variance.
TermStructureModels.AR_res_var — MethodAR_res_var(TS::Vector, p)It derives an MLE error variance estimate of an AR(p) model
Input
- univariate time series
TSand the lagp
output(2)
residual variance estimate, AR(p) coefficients
TermStructureModels.GQ_XX — MethodGQ_XX(; kappaQ)kappaQ governs a 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 — MethodLDL(X)This function generate 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 — MethodPCA(yields, p; loadings=[], dQ=[])It 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.loadings=Matrix{, dQ, size(yields, 2)}is loadings for the fisrt dQ principal components. That is,principal_components = yields*loadings'.
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 demeaned.PCsare demeaned.
TermStructureModels.calibrate_mean_phi_const — Methodcalibrate_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=[], τ=[])The purpose of the function is to calibrate a prior mean of the first dQ constant terms in our VAR. Adjust your prior setting based on the prior samples in outputs.
Input
mean_phi_const_PCsis your prior mean of the firstdQconstants. Our default option set 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 sampling the prior distribution of the constant part in the term premium.
Output(2)
prior_λₚ, prior_TP
- samples from the prior distribution of
λₚ - prior samples of constant part in the τ-month term premium
TermStructureModels.conditional_forecasts — Methodconditional_forecasts(S::Vector, τ, horizon, saved_params, yields, macros, tau_n; mean_macros::Vector=[], data_scale=1200)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 conditionaing a scenario, I assume S = Vector{Scenario}.
- If we need an unconditional prediction,
τis a vector. The term premium ofτ[i]-bond is forecasted for each i.- If
τis set to[], the term premium is not forecasted.
- If
horizon: maximum length of the predicted path. It should not be small thanlength(S).saved_params: the first output of functionposterior_sampler.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.
Output
Vector{Forecast}(, iteration)t'th rows in predictedyields, predictedfactors, and predictedTPare the corresponding predicted value at timesize(yields, 1)+t.- Mathematically, it is a posterior samples from
future observation|past observation,scenario.
TermStructureModels.dcurvature_dτ — Methoddcurvature_dτ(τ; kappaQ)This function calculate the first derivative of the curvature factor loading w.r.t. the maturity.
Input
kappaQ: The decay parameterτ: The maturity that the derivative is calculated
Output
- the first derivative of the curvature factor loading w.r.t. the maturity
TermStructureModels.dimQ — MethoddimQ()It returns the dimension of Q-dynamics under the standard ATSM.
TermStructureModels.erase_nonstationary_param — Methoderase_nonstationary_param(saved_params; threshold=1)It filters out posterior samples that implies an 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 — Methodfitted_YieldCurve(τ0, saved_latent_params::Vector{LatentSpace}; data_scale=1200)It generates a fitted yield curve.
Input
τ0is a set of maturities of interest.τ0does not need to be the same as the one used for the estimation.saved_latent_paramsis a transformed posterior sample using functionlatentspace.
Output
Vector{YieldCurve}(,# of iteration)yieldsandlatentscontain initial observations.
TermStructureModels.generative — Methodgenerative(T, dP, tau_n, p, noise::Float64; kappaQ, kQ_infty, KPXF, GPXFXF, OmegaXFXF, data_scale=1200)This function generate a simulation data given parameters. Note that all parameters are the things in the latent factor state space (that is, parameters in struct LatentSpace). There is some differences in notations because it is hard to express mathcal letters in VScode. So, mathcal{F} in my paper is expressed in F in the VScode. And, "F" in my 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 — Functionhessian(f, x, index=[])It 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 — Methodineff_factor(saved_params)It returns inefficiency factors of each parameter.
Input
Vector{Parameter}fromposterior_sampler
Output
- Estimated inefficiency factors are in Tuple(
kappaQ,kQ_infty,gamma,SigmaO,varFF,phi). For example, if you want to load an inefficiency factor ofphi, you can useOutput.phi. - If
fix_const_PC1==truein your optimized struct Hyperparameter,Output.phi[1,1]can be weird. So you should ignore it.
TermStructureModels.isstationary — Methodisstationary(GPFF; threshold)It checks whether a reduced VAR matrix has unit roots. If there is at least one unit root, return is false.
Input
GPFFshould not include intercepts. Also,GPFFisdPbydP*pmatrix that 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 — Methodlatentspace(saved_params, yields, tau_n; data_scale=1200)This function translates the principal components state space into the latent factor state space.
Input
data_scale::scalar: In typical affine term structure model, theoretical yields are in decimal and not annualized. But, 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 usedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.
Output
Vector{LatentSpace}(, iteration)- latent factors contain initial observations.
TermStructureModels.log_marginal — Methodlog_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 our 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. A empty default value means that you do not use this function.[psi_const psi][i,j]is corresponds tophi[i,j].
Output
- the log marginal likelihood of the VAR system.
TermStructureModels.loglik_mea — Methodloglik_mea(yields, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, data_scale)This function generate a log likelihood of the measurement equation.
Output
- the measurement equation part of the log likelihood
TermStructureModels.loglik_tran — Methodloglik_tran(PCs, macros; phi, varFF)It calculate log likelihood of the transition equation.
Output
- log likelihood of the transition equation.
TermStructureModels.phi_2_phi₀_C — Methodphi_2_phi₀_C(; phi)It divide phi into the lagged regressor part and the contemporaneous regerssor part.
Output(3)
phi0, C = C0 + I, C0
phi0: coefficients for the lagged regressorsC: coefficients for the dependent variables when all contemporaneous variables are in the LHS of the orthogonalized equations. Therefore, the diagonals ofCis ones. Note that since the contemporaneous variables get negative signs when they are at the RHS, the signs ofCdo not change whether they are at the RHS or LHS.
TermStructureModels.phi_varFF_2_OmegaFF — Methodphi_varFF_2_OmegaFF(; phi, varFF)It construct OmegaFF from statistical parameters.
Output
OmegaFF
TermStructureModels.posterior_sampler — Methodposterior_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)This is a posterior distribution sampler.
Input
iteration: # of posterior samplestuned: optimized hyperparameters used during estimationinit_param: starting point of the sampler. It should be a type of 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. A empty default value means that you do not use this function.[psi_const psi][i,j]is corresponds tophi[i,j]. The entries ofpsiandpsi_constshould be nearly zero(e.g.,1e-10), not exactly zero.
Output(2)
Vector{Parameter}(posterior, iteration), acceptance rate of the MH algorithm
TermStructureModels.prior_kappaQ — Methodprior_kappaQ(medium_tau, pr)The function derive the maximizer decay parameter kappaQ that maximize the curvature factor loading at each candidate medium-term maturity. And then, it impose 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 — Methodreducedform(saved_params, yields, macros, tau_n; data_scale=1200)It converts posterior samples in terms of the reduced form VAR parameters.
Input
saved_paramsis the first output of functionposterior_sampler.
Output
- Posterior samples in terms of struct
ReducedForm
TermStructureModels.scenario_analysis — Methodscenario_analysis(S::Vector, τ, horizon, saved_params, yields, macros, tau_n; mean_macros::Vector=[], data_scale=1200)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 conditionaing a scenario, I assume S = Vector{Scenario}.
- Set
τis a vector of maturities that term premiums of interest has.horizon: maximum length of the predicted path. It should not be small thanlength(S).saved_params: the first output of functionposterior_sampler.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.
Output
Vector{Forecast}(, iteration)t'th rows in predictedyields, predictedfactors, and predictedTPare the corresponding predicted value at timesize(yields, 1)+t.- Mathematically, it is a posterior distribution of
E[future obs|past obs, scenario, parameters].
TermStructureModels.term_premium — Methodterm_premium(tau_interest, tau_n, saved_params, yields, macros; data_scale=1200)This function generates posterior samples of the term premiums.
Input
- maturity of interest
tau_interestfor CalculatingTP saved_paramsfrom functionposterior_sampler
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 is stored insaved_tv_TP[j][:, k, i]andsaved_tv_EH[j][:, k, i].
TermStructureModels.tuning_hyperparameter — Methodtuning_hyperparameter(yields, macros, tau_n, rho; populationsize=50, maxiter=10_000, medium_tau=collect(24:3:48), upper_q=[1 1; 1 1; 10 10; 100 100], mean_kQ_infty=0, std_kQ_infty=0.1, upper_nu0=[], mean_phi_const=[], fix_const_PC1=false, upper_p=18, mean_phi_const_PC1=[], data_scale=1200, kappaQ_prior_pr=[], init_nu0=[], is_pure_EH=false, psi_common=[], psi_const=[])It optimizes our hyperparameters by maximizing the marginal likelhood of the transition equation. Our optimizer is a differential evolutionary algorithm that utilizes bimodal movements in the eigen-space(Wang, Li, Huang, and Li, 2014) and the trivial geography(Spector and Klein, 2006).
Input
- When we compare marginal likelihoods between models, the data for the dependent variable should be the same across the models. To achieve that, we set a period of dependent variable based on
upper_p. For example, ifupper_p = 3,yields[4:end,:]andmacros[4:end,:]are the data for our dependent variable.yields[1:3,:]andmacros[1:3,:]are used for setting initial observations for all lags. populationsizeandmaxiterare options for the optimizer.populationsize: the number of candidate solutions in each generationmaxtier: the maximum number of iterations
- The lower bounds for
qandnu0are0anddP+2. - The upper bounds for
q,nu0and VAR lag can be set byupper_q,upper_nu0,upper_p.- Our default option for
upper_nu0is the time-series length of the data.
- Our default option for
- If you use our 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 a 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 a prior mean for the VAR(i) constant. Thereforemean_phi_constis a matrix only in this function. In other functions,mean_phi_constis a vector for the orthogonalized VAR system with your selected lag.- When
fix_const_PC1==true, the first element in a constant term in our orthogonalized VAR is fixed to its prior mean during the posterior sampling. data_scale::scalar: In typical affine term structure model, theoretical yields are in decimal and not annualized. But, 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 usedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.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_constandpsi = kron(ones(1, lag length), psi_common)are 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. A empty default value means that you do not use this function.[psi_const psi][i,j]is corresponds tophi[i,j]. The entries ofpsi_commonandpsi_constshould be nearly zero(e.g.,1e-10), not exactly zero.
Output(2)
optimized Hyperparameter, optimization result
- Be careful that we minimized the negative log marginal likelihood, so the second output is about the minimization problem.
Internal Functions
TermStructureModels.Aₓ — MethodAₓ(aτ_, tau_n)Input
aτ_is an output of functionaτ.
Output
Aₓ
TermStructureModels.Aₚ — MethodAₚ(Aₓ_, Bₓ_, T0P_, Wₒ)Input
Aₓ_,Bₓ_, andT0P_are outputs of functionAₓ,Bₓ, andT0P, respectively.
Output
Aₚ
TermStructureModels.Bₓ — MethodBₓ(bτ_, tau_n)Input
bτ_is an output of functionbτ.
Output
Bₓ
TermStructureModels.Bₚ — MethodBₚ(Bₓ_, T1X_, Wₒ)Input
Bₓ_andT1X_are outputs of functionBₓandT1X, respectively.
Output
Bₚ
TermStructureModels.Kphi — MethodKphi(i, V, Xphi, dP)TermStructureModels.Minnesota — MethodMinnesota(l, i, j; q, nu0, Omega0, dQ=[])It return unscaled prior variance of the Minnesota prior.
Input
- lag
l, dependent variablei, regressorjin the VAR(p) q[:,1]andq[:,2]are [own, cross, lag, intercept] shrikages for the firstdQand remainingdP-dQequations, respectively.nu0(d.f.),Omega0(scale): Inverse-Wishart prior for the error-covariance matrix of VAR(p).
Output
- Minnesota part in the prior variance
TermStructureModels.NIG_NIG — MethodNIG_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 — MethodPCs_2_latents(yields, tau_n; kappaQ, kQ_infty, KPF, GPFF, OmegaFF, data_scale)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 model, theoretical yields are in decimal and not annualized. But, 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 usedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.
Output(6)
latent, kappaQ, kQ_infty, KPXF, GPXFXF, OmegaXFXF
- latent factors contain initial observations.
TermStructureModels.S — MethodS(i; Omega0)TermStructureModels.S_hat — MethodS_hat(i, m, V, yphi, Xphi, dP; Omega0)TermStructureModels.T0P — MethodT0P(T1X_, Aₓ_, Wₚ, c)Input
T1X_andAₓ_are outputs of functionT1XandAₓ, respectively.cis a sample mean ofPCs.
Output
T0P
TermStructureModels.T1X — MethodT1X(Bₓ_, Wₚ)Input
Bₓ_if an output of functionBₓ.
Output
T1X
TermStructureModels._conditional_forecasts — Method_conditional_forecasts(S, τ, horizon, yields, macros, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, mean_macros, data_scale)TermStructureModels._scenario_analysis — Method_scenario_analysis(S, τ, horizon, yields, macros, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, mean_macros, data_scale)TermStructureModels._scenario_analysis_unconditional — Method_scenario_analysis_unconditional(τ, horizon, yields, macros, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, mean_macros, data_scale)TermStructureModels._termPremium — Method_termPremium(τ, PCs, macros, bτ_, T0P_, T1X_; kappaQ, kQ_infty, KPF, GPFF, ΩPP, data_scale)This function calculates a term premium for maturity τ.
Input
data_scale::scalar= In typical affine term structure model, theoretical yields are in decimal and not annualized. But, 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 usedata_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 Ineqaulity part inTP- Output excludes the time period for the initial observations.
TermStructureModels._unconditional_forecasts — Method_unconditional_forecasts(τ, horizon, yields, macros, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, mean_macros, data_scale)TermStructureModels.aτ — Methodaτ(N, bτ_, tau_n, Wₚ; kQ_infty, ΩPP, data_scale)
aτ(N, bτ_; kQ_infty, ΩXX, data_scale)The function has two methods(multiple dispatch).
Input
- When
Wₚ∈ arguments: It calculatesaτusingΩPP. - Otherwise: It calculates
aτusingΩXX = OmegaXFXF[1:dQ, 1:dQ], so parameters are in the latent factor space. So, we do not needWₚ. bτ_is an output of functionbτ.data_scale::scalar: In typical affine term structure model, theoretical yields are in decimal and not annualized. But, 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 usedata_scaleoption. For example, we can setdata_scale = 1200and use annualized percentage monthly yields asyields.
Output
Vector(Float64)(aτ,N)- For
i'th maturity,Output[i]is the correspondingaτ.
TermStructureModels.bτ — Methodbτ(N; kappaQ, dQ)It solves the difference equation for bτ.
Output
- for maturity
i,bτ[:, i]is a vector of factor loadings.
TermStructureModels.jensens_inequality — Methodjensens_inequality(τ, bτ_, T1X_; ΩPP, data_scale)This function evaluate the Jensen's Ineqaulity term. All term is invariant with respect to the data_scale, except for this Jensen's inequality term. So, we need to scale down the term by data_scale.
Output
- Jensen's Ineqaulity term for
aτof maturityτ.
TermStructureModels.loglik_mea2 — Methodloglik_mea2(yields, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, data_scale)This function is the same as loglik_mea but it requires ΩPP as an input.
TermStructureModels.longvar — Methodlongvar(v)It calculates the long-run variance of v using the quadratic spectral window with selection of bandwidth of Andrews(1991). We use the AR(1) approximation.
Input
- Time-series Vector
v
Output
- Estimated 2πh(0) of
v, where h(x) is the spectral density ofvat x.
TermStructureModels.mle_error_covariance — Methodmle_error_covariance(yields, macros, tau_n, p)It calculates the MLE estimates of the error covariance matrix of the VAR(p) model.
TermStructureModels.phi_hat — Methodphi_hat(i, m, V, yphi, Xphi, dP)TermStructureModels.phi_varFF_2_ΩPP — Methodphi_varFF_2_ΩPP(; phi, varFF, dQ=[])It construct ΩPP from statistical parameters.
Output
ΩPP
TermStructureModels.post_SigmaO — Methodpost_SigmaO(yields, tau_n; kappaQ, kQ_infty, ΩPP, gamma, p, data_scale)Posterior sampler for the measurement errors
Output
Vector{Dist}(IG, N-dQ)
TermStructureModels.post_gamma — Methodpost_gamma(; gamma_bar, SigmaO)Posterior sampler for the population measurement error
Output
Vector{Dist}(Gamma,length(SigmaO))
TermStructureModels.post_kQ_infty — Methodpost_kQ_infty(mean_kQ_infty, std_kQ_infty, yields, tau_n; kappaQ, phi, varFF, SigmaO, data_scale)Output
- Full conditional posterior distribution
TermStructureModels.post_kappaQ — Methodpost_kappaQ(yields, prior_kappaQ_, tau_n; kQ_infty, phi, varFF, SigmaO, data_scale)Input
prior_kappaQ_is a output of functionprior_kappaQ.
Output
- Full conditional posterior distribution
TermStructureModels.post_kappaQ2 — Methodpost_kappaQ2(yields, prior_kappaQ_, tau_n; kappaQ, kQ_infty, phi, varFF, SigmaO, data_scale, x_mode, inv_x_hess)It 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_phi_varFF — Methodpost_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)Full-conditional posterior sampler for phi and varFF
Input
prior_kappaQ_is a output of functionprior_kappaQ.- When
fix_const_PC1==true, the first element in a constant term in our orthogonalized VAR is fixed to its prior mean during the posterior sampling.
Output(3)
phi, varFF, isaccept=Vector{Bool}(undef, dQ)
- It gives a posterior sample.
TermStructureModels.prior_C — Methodprior_C(; Omega0::Vector)We translate 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 — Methodprior_gamma(yields, p)There is a hierarchcal 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 maturities. An inverse of the average residual variances is set to gamma_bar.
Output
- hyperparameter
gamma_bar
TermStructureModels.prior_phi0 — Methodprior_phi0(mean_phi_const, rho::Vector, prior_kappaQ_, tau_n, Wₚ; psi_const, psi, q, nu0, Omega0, fix_const_PC1)This part derives the prior distribution for coefficients of the lagged regressors in the orthogonalized VAR.
Input
prior_kappaQ_is a output of functionprior_kappaQ.- When
fix_const_PC1==true, the first element in a constant term in our 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 — Methodprior_varFF(; nu0, Omega0::Vector)We translate 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 — Methodyphi_Xphi(PCs, macros, p)This function generate 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 i'th equation, the dependent variable isyphi[:,i]and the regressor isXphi.Xphiis same to all orthogonalized transtion equations. The orthogonalized equations are different in terms of contemporaneous regressors. Therefore, the corresponding regressors inXphishould be excluded. The form of parameterphido that task by setting the coefficients of the excluded regressors to zeros. In particular, for lastdPbydPblock inphi, the diagonals and the upper diagonal elements should be zero.
TermStructureModels.ν — Methodν(i, dP; nu0)