├── Contents.m ├── GUI ├── ARMAX.fig ├── ARMAX.m ├── ARMAX_about.fig ├── ARMAX_about.m ├── ARMAX_close_dialog.fig ├── ARMAX_close_dialog.m ├── ARMAX_viewer.fig ├── ARMAX_viewer.m └── OxLogo.mat ├── README.md ├── addToPath.m ├── bootstrap ├── block_bootstrap.m ├── bsds.m ├── mcs.m └── stationary_bootstrap.m ├── buildZipFile.m ├── crosssection ├── ols.m └── pca.m ├── distributions ├── composite_likelihood.m ├── gedcdf.m ├── gedinv.m ├── gedloglik.m ├── gedpdf.m ├── gedrnd.m ├── iscompatible.m ├── mvnormloglik.m ├── normloglik.m ├── skewtcdf.m ├── skewtinv.m ├── skewtloglik.m ├── skewtpdf.m ├── skewtrnd.m ├── stdtcdf.m ├── stdtinv.m ├── stdtloglik.m ├── stdtpdf.m └── stdtrnd.m ├── docs ├── MATLAB_Function_Reference_2012_final.lyx ├── MATLAB_Function_Reference_2012_final.pdf ├── chapters │ ├── bootstrap_and_multiple_hypothesis_tests.lyx │ ├── bootstrap_and_multiple_hypothesis_tests.lyx~ │ ├── cross_sectional_analysis.lyx │ ├── density_estimation.lyx │ ├── helper_functions.lyx │ ├── kerneldensity.pdf │ ├── nonstationary_time_series.lyx │ ├── stationary_time_series.lyx │ ├── tsresidualplot.pdf │ ├── vector_autoregressions.lyx │ └── volatility_modeling.lyx └── icon.lyx ├── duplication ├── chi2cdf.m ├── kurtosis.m ├── normcdf.m ├── norminv.m ├── normpdf.m └── skewness.m ├── icon.png ├── mex_source ├── agarch_core.c ├── armaxerrors.c ├── composite_likelihood.c ├── egarch_core.c ├── igarch_core.c └── tarch_core.c ├── multivariate ├── bekk.m ├── bekk_constraint.m ├── bekk_likelihood.m ├── bekk_parameter_transform.m ├── bekk_simulate.m ├── ccc_mvgarch.m ├── ccc_mvgarch_joint_likelihood.m ├── ccc_mvgarch_likelihood.m ├── ccc_mvgarch_simulate.m ├── dcc.m ├── dcc_fit_variance.m ├── dcc_inference_objective.m ├── dcc_likelihood.m ├── dcc_reconstruct_variance.m ├── gogarch.m ├── gogarch_likelihood.m ├── matrix_garch.m ├── matrix_garch_display.m ├── matrix_garch_likelihood.m ├── matrix_garch_simulate.m ├── o_mvgarch.m ├── ogarch_likelihood.m ├── rarch.m ├── rarch_constraint.m ├── rarch_likelihood.m ├── rarch_parameter_transform.m ├── rarch_simulate.m ├── rcc.m ├── rcc_constraint.m ├── rcc_likelihood.m ├── riskmetrics.m ├── riskmetrics2006.m ├── scalar_vt_vech.m ├── scalar_vt_vech_itransform.m ├── scalar_vt_vech_likelihood.m ├── scalar_vt_vech_simulate.m ├── scalar_vt_vech_starting_values.m └── scalar_vt_vech_transform.m ├── project_icon_v2.pdn ├── realized ├── ES_20090817.mat ├── Since the changed in QRV - 2.docx ├── Since the changed in QRV.docx ├── ToDo.docx ├── realized_bipower_variation.m ├── realized_compute_median.m ├── realized_convert2unit.m ├── realized_covariance.m ├── realized_hayashi_yoshida.m ├── realized_kernel.m ├── realized_kernel_bandwidth.m ├── realized_kernel_core.m ├── realized_kernel_jitter_lag_length.m ├── realized_kernel_weights.m ├── realized_min_med_variance.m ├── realized_multiscale_variance.m ├── realized_multivariate_kernel.m ├── realized_noise_estimate.m ├── realized_options.m ├── realized_preaveraged_bipower_variation.m ├── realized_preaveraged_variance.m ├── realized_price_filter.m ├── realized_qmle_variance.m ├── realized_quantile_scales.mat ├── realized_quantile_variance.m ├── realized_quantile_variance_scale.m ├── realized_quantile_weight_simulation.m ├── realized_quarticity.m ├── realized_range.m ├── realized_range_simulation.m ├── realized_range_simulation_results.mat ├── realized_refresh_time.m ├── realized_refresh_time_bivariate.m ├── realized_return_filter.m ├── realized_semivariance.m ├── realized_subsample.m ├── realized_test.m ├── realized_threshold_multipower_variation.m ├── realized_threshold_variance.m ├── realized_twoscale_variance.m ├── realized_variance.m ├── realized_variance_optimal_sampling.m ├── seconds2unit.m ├── seconds2wall.m ├── unit2seconds.m ├── unit2wall.m ├── wall2seconds.m └── wall2unit.m ├── sandbox ├── heavy_test.m ├── sarima.m ├── sarimax_errors.m ├── sarimax_likelihood.m ├── sarma2arma.m └── sdiff.m ├── tests ├── berkowitz.m ├── jarquebera.m ├── kolmogorov.m ├── ljungbox.m └── lmtest1.m ├── timeseries ├── acf.m ├── aichqcsbic.m ├── aicsbic.m ├── arma_forecaster.m ├── armaroots.m ├── armaxerrors.m ├── armaxfilter.m ├── armaxfilter_core.m ├── armaxfilter_likelihood.m ├── armaxfilter_simulate.m ├── augdf.m ├── augdf_cvsim_tieup.m ├── augdfautolag.m ├── augdfcv.m ├── beveridgenelson.m ├── bkfilter.m ├── convert_ma_roots.m ├── grangercause.m ├── heterogeneousar.m ├── hp_filter.m ├── impulseresponse.m ├── impulseresponse_bootstrap.m ├── inverse_ar_roots.m ├── olsnw.m ├── pacf.m ├── sacf.m ├── spacf.m ├── tsresidualplot.m ├── vectorar.m ├── vectorarvcv.m └── weights_to_frequency_response.m ├── univariate ├── agarch.m ├── agarch_core.m ├── agarch_display.m ├── agarch_itransform.m ├── agarch_likelihood.m ├── agarch_parameter_check.m ├── agarch_simulate.m ├── agarch_starting_values.m ├── agarch_transform.m ├── aparch.m ├── aparch_core.m ├── aparch_display.m ├── aparch_itransform.m ├── aparch_likelihood.m ├── aparch_loglikelihood.m ├── aparch_parameter_check.m ├── aparch_simulate.m ├── aparch_starting_values.m ├── aparch_transform.m ├── egarch.m ├── egarch_core.m ├── egarch_display.m ├── egarch_itransform.m ├── egarch_likelihood.m ├── egarch_nlcon.m ├── egarch_parameter_check.m ├── egarch_simulate.m ├── egarch_starting_values.m ├── egarch_transform.m ├── figarch.m ├── figarch_itransform.m ├── figarch_likelihood.m ├── figarch_parameter_check.m ├── figarch_simulate.m ├── figarch_starting_values.m ├── figarch_transform.m ├── figarch_weights.m ├── heavy.m ├── heavy_likelihood.m ├── heavy_parameter_transform.m ├── heavy_simulate.m ├── igarch.m ├── igarch_core.m ├── igarch_display.m ├── igarch_itransform.m ├── igarch_likelihood.m ├── igarch_parameter_check.m ├── igarch_starting_values.m ├── igarch_transform.m ├── tarch.m ├── tarch_core.m ├── tarch_core_simple.m ├── tarch_display.m ├── tarch_itransform.m ├── tarch_likelihood.m ├── tarch_parameter_check.m ├── tarch_simulate.m ├── tarch_starting_values.m └── tarch_transform.m └── utility ├── c2mdate.m ├── chol2vec.m ├── corr_ivech.m ├── corr_vech.m ├── cov2corr.m ├── covnw.m ├── covvar.m ├── demean.m ├── dirod.m ├── gradient_2sided.m ├── hessian_2sided.m ├── hessian_2sided_nrows.m ├── ivech.m ├── m2cdate.m ├── mprint.m ├── mvstandardize.m ├── newlagmatrix.m ├── phi2r.m ├── phi2u.m ├── pltdens.m ├── r2phi.m ├── r2z.m ├── randchar.m ├── robustvcv.m ├── standardize.m ├── vec2chol.m ├── vech.m ├── x2mdate.m └── z2r.m /Contents.m: -------------------------------------------------------------------------------- 1 | % MFE Toolbox Toolbox 2 | % Version 4.0 28-Oct-2009 -------------------------------------------------------------------------------- /GUI/ARMAX.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/GUI/ARMAX.fig -------------------------------------------------------------------------------- /GUI/ARMAX_about.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/GUI/ARMAX_about.fig -------------------------------------------------------------------------------- /GUI/ARMAX_close_dialog.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/GUI/ARMAX_close_dialog.fig -------------------------------------------------------------------------------- /GUI/ARMAX_viewer.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/GUI/ARMAX_viewer.fig -------------------------------------------------------------------------------- /GUI/OxLogo.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/GUI/OxLogo.mat -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MFE Toolbox 2 | 3 | This is the code repository for the MFE Toolbox, a set of MATLAB routines 4 | primarily for modeling financial time series, although many of the 5 | functions are useful in other econometric problems, such as modeling 6 | macroeconomic time series data or applications to cross-sectional data. 7 | 8 | -------------------------------------------------------------------------------- /addToPath.m: -------------------------------------------------------------------------------- 1 | function addToPath(arg) 2 | 3 | % Adds the MFE Toolbox to the current path and optionally saves the path 4 | silent = false; 5 | if nargin>0 && strcmpi(arg,'-silent') 6 | silent = true; 7 | end 8 | 9 | dirList = {'bootstrap',... 10 | 'crosssection',... 11 | 'distributions',... 12 | 'GUI',... 13 | 'multivariate',... 14 | 'tests',... 15 | 'timeseries',... 16 | 'univariate',... 17 | 'utility',... 18 | 'realized',... 19 | }; 20 | optionalDirList = {'duplication'}; 21 | mexDir = 'dlls'; 22 | 23 | for i=1:length(dirList) 24 | addpath(fullfile(pwd,dirList{i})); 25 | end 26 | 27 | 28 | user_entry = ''; 29 | while ~ismember({user_entry},{'Y','N'}) && ~silent 30 | user_entry = input('Add MATLAB work-a-like functions? [Y/N(default)] ','s'); 31 | user_entry = upper(user_entry); 32 | if isempty(user_entry) 33 | user_entry = 'N'; 34 | end 35 | end 36 | 37 | if strcmpi(user_entry,'Y') 38 | for i=1:length(optionalDirList) 39 | addpath(fullfile(pwd,optionalDirList{i})); 40 | end 41 | end 42 | 43 | user_entry = ''; 44 | while ~ismember({user_entry},{'Y','N'}) && ~silent 45 | user_entry = input('Make path permanent? [Y/N (default)] ','s'); 46 | user_entry = upper(user_entry); 47 | if isempty(user_entry) 48 | user_entry = 'N'; 49 | end 50 | end 51 | 52 | if strcmpi(user_entry,'Y') 53 | try 54 | savepath 55 | catch ME 56 | warning('MFEToolbox:Path',['There was a problem saving the path. The error was: \n' ME.message]) 57 | end 58 | end 59 | 60 | if strcmpi(computer,'PCWIN64') 61 | user_entry = ''; 62 | while ~ismember({user_entry},{'Y','N'}) && ~silent 63 | user_entry = input('Add MEX files to path? [Y(default)/N] ','s'); 64 | user_entry = upper(user_entry); 65 | if isempty(user_entry) 66 | user_entry = 'Y'; 67 | end 68 | end 69 | if strcmp(user_entry,'Y') || silent 70 | addpath(fullfile(pwd,mexDir)); 71 | end 72 | end 73 | 74 | -------------------------------------------------------------------------------- /bootstrap/block_bootstrap.m: -------------------------------------------------------------------------------- 1 | function [bsdata, indices]=block_bootstrap(data,B,w) 2 | % Implements a circular block bootstrap for bootstrapping stationary, dependent series 3 | % 4 | % USAGE: 5 | % [BSDATA, INDICES]=block_bootstrap(DATA,B,W) 6 | % 7 | % INPUTS: 8 | % DATA - T by 1 vector of data to be bootstrapped 9 | % B - Number of bootstraps 10 | % W - Block length 11 | % 12 | % OUTPUTS: 13 | % BSDATA - T by B matrix of bootstrapped data 14 | % INDICES - T by B matrix of locations of the original BSDATA=DATA(indexes); 15 | % 16 | % COMMENTS: 17 | % To generate bootstrap sequences for other uses, such as bootstrapping vector processes, 18 | % set DATA to (1:N)'. 19 | % 20 | % See also stationary_bootstrap 21 | 22 | % Author: Kevin Sheppard 23 | % kevin.sheppard@economics.ox.ac.uk 24 | % Revision: 2 Date: 12/31/2001 25 | 26 | 27 | %%%%%%%%%%%%%%%%%%%%%%%%% 28 | % Input Checking 29 | %%%%%%%%%%%%%%%%%%%%%%%%% 30 | if nargin~=3 31 | error('3 inputs required') 32 | end 33 | % Get the length of the data 34 | [t,k]=size(data); 35 | if k>1 36 | error('DATA must be a column vector') 37 | end 38 | if t<2 39 | error('DATA must have at least 2 observations.') 40 | end 41 | if ~isscalar(w) || w<1 || floor(w)~=w || w>t 42 | error('W must be a positive scalar integer smaller than T') 43 | end 44 | if ~isscalar(B) || B<1 || floor(B)~=B 45 | error('B must be a positive scalar integer') 46 | end 47 | %%%%%%%%%%%%%%%%%%%%%%%%% 48 | % Input Checking 49 | %%%%%%%%%%%%%%%%%%%%%%%%% 50 | 51 | % Compute the number of blocks needed 52 | s=ceil(t/w); 53 | % Generate the starting points 54 | Bs=floor(rand(s,B)*t)+1; 55 | indices=zeros(s*w,B); 56 | index=1; 57 | % Adder is a variable that needs to be added each loop 58 | adder=repmat((0:w-1)',1,B); 59 | for i=1:w:t 60 | indices(i:(i+w-1),:)=repmat(Bs(index,:),w,1)+adder; 61 | index=index+1; 62 | end 63 | indices=indices(1:t,:); 64 | indices(indices>t) = indices(indices>t)-t; 65 | bsdata=data(indices); 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /bootstrap/stationary_bootstrap.m: -------------------------------------------------------------------------------- 1 | function [bsdata, indices]=stationary_bootstrap(data,B,w) 2 | % Implements the stationary bootstrap for bootstrapping stationary, dependent series 3 | % 4 | % USAGE: 5 | % [BSDATA, INDICES] = stationary_bootstrap(DATA,B,W) 6 | % 7 | % INPUTS: 8 | % DATA - T by 1 vector of data to be bootstrapped 9 | % B - Number of bootstraps 10 | % W - Average block length. P, the probability of starting a new block is defined P=1/W 11 | % 12 | % OUTPUTS: 13 | % BSDATA - T by B matrix of bootstrapped data 14 | % INDICES - T by B matrix of locations of the original BSDATA=DATA(indexes); 15 | % 16 | % COMMENTS: 17 | % To generate bootstrap sequences for other uses, such as bootstrapping vector processes, 18 | % set DATA to (1:N)'. 19 | % 20 | % See also block_bootstrap 21 | 22 | % Author: Kevin Sheppard 23 | % kevin.sheppard@economics.ox.ac.uk 24 | % Revision: 2 Date: 12/31/2001 25 | 26 | 27 | 28 | %%%%%%%%%%%%%%%%%%%%%%%%% 29 | % Input Checking 30 | %%%%%%%%%%%%%%%%%%%%%%%%% 31 | if nargin~=3 32 | error('3 inputs required') 33 | end 34 | % Get the length of the data 35 | [t,k]=size(data); 36 | if k>1 37 | error('DATA must be a column vector') 38 | end 39 | if t<2 40 | error('DATA must have at least 2 observations.') 41 | end 42 | if ~isscalar(w) || w<=0 43 | error('W must be a positive scalar.') 44 | end 45 | if ~isscalar(B) || B<1 || floor(B)~=B 46 | error('B must be a positive scalar integer') 47 | end 48 | %%%%%%%%%%%%%%%%%%%%%%%%% 49 | % Input Checking 50 | %%%%%%%%%%%%%%%%%%%%%%%%% 51 | 52 | % Define the probability of a new block 53 | p=1/w; 54 | % Set up the bsdata and indices 55 | indices=zeros(t,B); 56 | % Initial positions 57 | indices(1,:)=ceil(t*rand(1,B)); 58 | % Set up the random numbers 59 | select=rand(t,B)p) or move to a new starting value 63 | % (randt) = indices(indices>t)-t; 67 | % The indices make finding the bsdata simple 68 | bsdata=data(indices); -------------------------------------------------------------------------------- /distributions/composite_likelihood.m: -------------------------------------------------------------------------------- 1 | function ll = composite_likelihood(S,data,indices) 2 | % Computes the negative of the composite normal loglikelihood (bivariate) for a K-dimensional array 3 | % 4 | % USAGE: 5 | % [LL] = composite_likelihood(S,DATA,INDICES) 6 | % 7 | % INPUTS: 8 | % S - K by K covariance matrix 9 | % DATA - Either a K by K matrix (e.g. outer-produces) or a 1 by K vector (e.g. returns) 10 | % INDICES - Q by 2 array of indices to use when computing the composite likleihood 11 | % 12 | % OUTPUTS: 13 | % LL - Composite likelihood 14 | % 15 | % COMMENTS: 16 | % This is a helper function for various multivariate GARCH models. A MEX file version of this file 17 | % is available which provides a large speed-up. 18 | % 19 | % See also DCC, SCALAR_VEC_VECH, BEKK, RARCH 20 | 21 | q = size(indices,1); 22 | [m,n] = size(data); 23 | likConst = 3.67575413281869; 24 | ll = 0; 25 | if m==n 26 | for k=1:q 27 | i = indices(k,1); 28 | j = indices(k,2); 29 | s11 = S(i,i); 30 | s12 = S(i,j); 31 | s22 = S(j,j); 32 | det = s11*s22-s12*s12; 33 | x11 = data(i,i); 34 | x12 = data(i,j); 35 | x22 = data(j,j); 36 | ll = ll + 0.5*(likConst + log(det) + (s22*x11 - 2*s12*x12 + s11*x22)/det)/q; 37 | end 38 | else 39 | for k=1:q 40 | i = indices(k,1); 41 | j = indices(k,2); 42 | s11 = S(i,i); 43 | s12 = S(i,j); 44 | s22 = S(j,j); 45 | det = s11*s22-s12*s12; 46 | x11 = data(i)*data(i); 47 | x12 = data(i)*data(j); 48 | x22 = data(j)*data(j); 49 | ll = ll + 0.5*(likConst + log(det) + (s22*x11 - 2*s12*x12 + s11*x22)/det)/q; 50 | end 51 | end -------------------------------------------------------------------------------- /distributions/gedcdf.m: -------------------------------------------------------------------------------- 1 | function p = gedcdf(x,v) 2 | % Cumulative Distribution Function (CDF) of the Generalized Error Distribution(GED) 3 | % 4 | % USAGE: 5 | % P = gedcdf(X,V) 6 | % 7 | % INPUTS: 8 | % X - Generalized Error Distribution distributed random variables 9 | % V - Degree of freedom parameters, either scalar or size(x) 10 | % 11 | % OUTPUTS: 12 | % P - Cumulative distribution evaluated at x 13 | % 14 | % COMMENTS: 15 | % V>1 16 | % A scalar GED r.v. with variance normalized to 1 has probability 17 | % density given by: 18 | % f(x,V) = [V/(lda*2^(1+1/V)*gamma(1/V))]*exp(-0.5*|x/lda|^V) 19 | % lda = [2^(-2/V)*gamma(1/V)/gamma(3/V)]^0.5 20 | % Uses GAMCDF 21 | % 22 | % REFERENCES: 23 | % [1] Tadikamalla (1980), J.Am.Stat.Assoc. (75) 24 | % [2] Nelson (1991), Econometrica 25 | % 26 | % See also GEDPDF, GEDINV, GEDRND, GEDLOGLIK GAMCDF 27 | 28 | % Copyright: 29 | % Ivana Komunjer 30 | % komunjer@hss.caltech.edu 31 | % Revision: 1 Date: 23/08/2002 32 | % Modifications Copyright: 33 | % Kevin Sheppard 34 | % kevin.sheppard@economics.ox.ac.uk 35 | % Revision: 3 Date: 8/1/2005 36 | if nargin~=2 37 | error('Requires two input arguments.') 38 | end 39 | 40 | [err, errtext, sizeOut, v] = iscompatible(1,v,size(x)); 41 | 42 | if err 43 | error(errtext) 44 | end 45 | 46 | % Initialize P to zero. 47 | p = zeros(size(x)); 48 | scalex = (gamma(3./v)./gamma(1./v)).^0.5; 49 | 50 | % Return NaN if the argument V is outside its limits. 51 | p(v < 1) = NaN; 52 | 53 | ku = find(x >= 0 & ~(v < 1)); 54 | vku = v(ku); 55 | xku = x(ku); 56 | scalexku = scalex(ku); 57 | if any(ku), 58 | p(ku) = 0.5*(1 + gamcdf((abs(xku.*scalexku)).^vku,1./vku)); 59 | end 60 | 61 | kl = find(x < 0 & ~(v < 1)); 62 | vkl = v(kl); 63 | xkl = x(kl); 64 | scalexkl = scalex(kl); 65 | if any(kl), 66 | p(kl) = 0.5*(1 - gamcdf((abs(xkl.*scalexkl)).^vkl,1./vkl)); 67 | end 68 | 69 | % Make sure that round-off errors never make P less than 0 or greater than 1. 70 | p(p < 0) = 0; 71 | p(p > 1) = 1; -------------------------------------------------------------------------------- /distributions/gedinv.m: -------------------------------------------------------------------------------- 1 | function x = gedinv(p,v) 2 | % Inverse Cumulative Distribution Function (CDF) of the Generalized Error 3 | % Distribution (GED); Maps [0,1] to a GED with shape parameter V 4 | % 5 | % USAGE: 6 | % X = gedinv(P,V) 7 | % 8 | % INPUTS: 9 | % P - Values to be inverted, P in [0,1] 10 | % V - Shape parameters, either scalar or size(X) 11 | % 12 | % OUTPUTS: 13 | % X - GED random variables corresponding to P 14 | % 15 | % COMMENTS: 16 | % A scalar GED r.v. with variance normalized to 1 has probability 17 | % density given by: 18 | % f(x,V) = [V/(lda*2^(1+1/V)*gamma(1/V))]*exp(-0.5*|x/lda|^V) 19 | % lda = [2^(-2/V)*gamma(1/V)/gamma(3/V)]^0.5 20 | % GAMINV does the computational work 21 | % 22 | % REFERENCES: 23 | % [1] Tadikamalla (1980), J.Am.Stat.Assoc. (75) 24 | % [2] Nelson (1991), Econometrica 25 | % 26 | % See also GEDCDF, GEDINV, GEDRND, GEDLOGLIK 27 | 28 | % Copyright: Ivana Komunjer 29 | % komunjer@hss.caltech.edu 30 | % Revision: 1 Date: 23/08/2002 31 | % Modifications Copyright: 32 | % Kevin Sheppard 33 | % kevin.sheppard@economics.ox.ac.uk 34 | % Revision: 3 Date: 9/1/2005 35 | 36 | if nargin~=2 37 | error('Requires two input arguements.') 38 | end 39 | 40 | [err, errtext, sizeOut, v] = iscompatible(1,v,size(p)); 41 | 42 | if err 43 | error(errtext) 44 | end 45 | 46 | % Initialize X to zero. 47 | x = zeros(size(p)); 48 | scalex = (gamma(3./v)./gamma(1./v)).^0.5; 49 | 50 | k = find(p<0 | p>1 | v < 1); 51 | if any(k), 52 | tmp = NaN; 53 | x(k) = tmp(ones(size(k))); 54 | end 55 | 56 | % The inverse cdf of 0 is 0, and the inverse cdf of 1 is 1. 57 | k0 = find(p == 0 & v >= 1); 58 | if any(k0), 59 | x(k0) = zeros(size(k0)); 60 | end 61 | 62 | k1 = find(p == 1 & v >= 1); 63 | if any(k1), 64 | tmp = Inf; 65 | x(k1) = tmp(ones(size(k1))); 66 | end 67 | 68 | % Tadikamalla's Method: uses the fact that Y=abs(X)^v has 69 | % a Gamma distribution with shape parameter 1/v 70 | kl = find(p > 0 & p < 0.5 & v >= 1); 71 | if any(kl(:)) 72 | pkl = p(kl); 73 | vkl = v(kl); 74 | xkl = gaminv(1-2*pkl,1./vkl); 75 | xkl = (-1)*xkl.^(1./vkl); 76 | x(kl) = xkl; 77 | end 78 | 79 | ku = find(p >= 0.5 & p < 1 & v >= 1); 80 | if any(ku(:)) 81 | pku = p(ku); 82 | vku = v(ku); 83 | xku = gaminv(2*pku-1,1./vku); 84 | xku = xku.^(1./vku); 85 | x(ku) = xku; 86 | end 87 | 88 | % need to standardize the quantiles 89 | x = x./scalex; 90 | 91 | -------------------------------------------------------------------------------- /distributions/gedloglik.m: -------------------------------------------------------------------------------- 1 | function [LL,LLS]=gedloglik(x,mu,sigma2,v) 2 | % Log likelihood for the Generalized Error Distribution (GED) distribution 3 | % 4 | % USAGE: 5 | % [LL,LLS]=gedloglik(X,MU,SIGMA2,V) 6 | % 7 | % INPUTS: 8 | % X - Standardized T random variables, either scalar or column vector 9 | % MU - Mean of X, either scalar or size(x) 10 | % SIGMA2 - Variance of X, either scalar or size(x) 11 | % V - Degree of freedom parameters, either scalar or size(x) 12 | % 13 | % OUTPUTS: 14 | % LL - Log-likelihood evaluated at X 15 | % LLS - Vector of log-likelihoods corresponding to X 16 | % 17 | % COMMENTS: 18 | % V>1 19 | % f(x,V) = [v/(lda*2^(1+1/v)*gamma(1/v))]*exp(-0.5*|x/lda|^v) 20 | % lda = [2^(-2/v)*gamma(1/v)/gamma(3/v)]^0.5 21 | % 22 | % REFERENCES: 23 | % [1] Tadikamalla (1980), J.Am.Stat.Assoc. (75) 24 | % [2] Nelson (1991), Econometrica 25 | % 26 | % See also GEDCDF, GEDINV, GEDRND, GEDPDF 27 | 28 | % Copyright: Kevin Sheppard 29 | % kevin.sheppard@economics.ox.ac.uk 30 | % Revision: 1 Date: 9/1/2005 31 | 32 | [T,K]=size(x); 33 | 34 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 35 | % Input Checking 36 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 37 | if K~=1 38 | error('X must be a column vector'); 39 | end 40 | 41 | if nargin==4 42 | if length(mu)~=1 && ~all(size(mu)==[T K]) 43 | error('mu must be either a scalar or the same size as X'); 44 | end 45 | if any(sigma2<=0) 46 | error('sigma2 must contain only positive elements') 47 | end 48 | if length(sigma2)==1 49 | sigma2=sigma2*ones(T,K); 50 | elseif size(sigma2,1)~=T || size(sigma2,2)~=1 51 | error('sigma2 must be a scalar or a vector with the same dimensions as X'); 52 | end 53 | if length(v)>1 || v<=1 54 | error('V must be a scalar greater than 1'); 55 | end 56 | x=x-mu; 57 | else 58 | error('Only 4 inputs supported'); 59 | end 60 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 61 | % Input Checking 62 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 63 | 64 | %Compute the log likelihood 65 | logl=0.5*(-2/v*log(2)+gammaln(1/v)-gammaln(3/v)); 66 | l=exp(logl); 67 | LL = (T * log(v)) - (T*logl) - (T*gammaln(1/v)) - T*(1+1/v)*log(2); 68 | LL = LL - 0.5 * sum(log(sigma2)) - 0.5 * sum((abs(x./(sqrt(sigma2)*l))).^v); 69 | 70 | %Compute the individual LLS if needed 71 | if nargout>1 72 | LLS = log(v) - logl - gammaln(1/v) - (1+1/v)*log(2) - 0.5 * log(sigma2) - 0.5 * (abs(x./(sqrt(sigma2)*l))).^v; 73 | % LLS=log(v)-logl-0.5*abs(x./l).^v-logl-(1+1/v)*log(2)-gammaln(1/v); 74 | end 75 | -------------------------------------------------------------------------------- /distributions/gedpdf.m: -------------------------------------------------------------------------------- 1 | function y = gedpdf(x,v) 2 | % Probability Density Function (PDF) for the Generalized Error Distribution (GED) 3 | % 4 | % USAGE: 5 | % Y = gedpdf(X,V) 6 | % 7 | % INPUTS: 8 | % X - Generalized Error Distribution distributed random variables 9 | % V - Degree of freedom parameters, either scalar or size(x) 10 | % 11 | % OUTPUTS: 12 | % Y - Probability density evaluated at x 13 | % 14 | % COMMENTS: 15 | % V>=1 16 | % A scalar GED r.v. with variance normalized to 1 has probability 17 | % density given by: 18 | % f(x,V) = [V/(lda*2^(1+1/V)*gamma(1/V))]*exp(-0.5*|x/lda|^V) 19 | % lda = [2^(-2/V)*gamma(1/V)/gamma(3/V)]^0.5 20 | % 21 | % REFERENCES: 22 | % [1] Tadikamalla (1980), J.Am.Stat.Assoc. (75) 23 | % [2] Nelson (1991), Econometrica 24 | % 25 | % See also GEDCDF, GEDINV, GEDRND, GEDLOGLIK 26 | 27 | % Copyright: Ivana Komunjer 28 | % komunjer@hss.caltech.edu 29 | % Revision: 1 Date: 23/08/2002 30 | % Modifications Copyright: 31 | % Kevin Sheppard 32 | % kevin.sheppard@economics.ox.ac.uk 33 | % Revision: 3 Date: 8/1/2005 34 | 35 | if nargin~=2 36 | error('Requires two input arguments.') 37 | end 38 | 39 | [err, errtext, sizeOut, v] = iscompatible(1,v,size(x)); 40 | 41 | if err 42 | error(errtext) 43 | end 44 | 45 | % Initialize D to zero. 46 | y = zeros(size(x)); 47 | 48 | % Return NaN if the argument V is outside its limit. 49 | y(v < 1) = NaN; 50 | 51 | k = find(v >= 1); 52 | vk = v(k); xk = x(k); 53 | if any(k) 54 | ldak = ((2.^(-2./vk)).*(gamma(1./vk))./(gamma(3./vk))).^(0.5); 55 | y(k) = vk.*exp(-0.5*((abs(xk./ldak)).^vk))./(ldak.*gamma(1./vk).*(2.^(1+1./vk))); 56 | end -------------------------------------------------------------------------------- /distributions/gedrnd.m: -------------------------------------------------------------------------------- 1 | function r = gedrnd(v,varargin) 2 | % Generate random variables from a Generalized Error Distribution (GED) with V degrees of freedom 3 | % 4 | % USAGE: 5 | % R=gedrnd(V) 6 | % R=gedrnd(V,S1) 7 | % R=gedrnd(V,S1,S2,S3,...,SN) 8 | % R=gedrnd(V,[S1 S2 S3 ... SN]) 9 | % 10 | % INPUTS: 11 | % V - Degree of freedom parameter. Either scalar or matrix. 12 | % Sx - [OPTIONAL] Size of output. 13 | % R will be: 14 | % 1 by 1 if V is scalar and no S are entered 15 | % size(V) if V is non-scalar and no S are entered 16 | % S1 by S1 if V is scalar and only S1 is entered 17 | % [S1 S2 ... SN] otherwise 18 | % If V is non-scalar and S are provided, size(V) must equal [S1 S2 ... SN] 19 | % 20 | % OUTPUTS: 21 | % R - GED distributed random variables 22 | % 23 | % COMMENTS: 24 | % V>=1 25 | % A scalar GED r.v. with variance normalized to 1 has probability 26 | % density given by: 27 | % f(x,v) = [v/(lda*2^(1+1/v)*gamma(1/v))]*exp(-0.5*|x/lda|^v) 28 | % lda = [2^(-2/v)*gamma(1/v)/gamma(3/v)]^0.5 29 | % If X~GED(v) then abs(X)^v = Y~Gamma(1/v) (cf. Tadikamalla 1980). 30 | % GAMRND does the computational work. 31 | % 32 | % REFERENCES: 33 | % [1] Tadikamalla (1980), J.Am.Stat.Assoc. (75) 34 | % [2] Nelson (1991), Econometrica 35 | % 36 | % See also GEDPDF, GEDCDF, GEDINV, GEDLL, GAMRND 37 | 38 | % Copyright: Ivana Komunjer 39 | % komunjer@hss.caltech.edu 40 | % Modifications Copyright: 41 | % Kevin Sheppard 42 | % kevin.sheppard@economics.ox.ac.uk 43 | % Revision: 3 Date: 9/1/2005 44 | 45 | if nargin < 1, 46 | error('Requires at least one input argument.'); 47 | end 48 | 49 | v(v<1)=NaN; 50 | 51 | [err, errtext, sizeOut] = iscompatible(1,v,varargin{:}); 52 | 53 | if err 54 | error(errtext) 55 | end 56 | 57 | % Return NaN if the argument V is outside its limit. 58 | r = gamrnd(1./v,1,sizeOut); 59 | r = r.^(1./v); 60 | rndsgn = 2*((rand(sizeOut)>0.5)-0.5); % generates a random sign -1 or +1 61 | r = r.*rndsgn; 62 | 63 | scalex = (gamma(3./v)./gamma(1./v)).^0.5; % standardizes the obtained values 64 | r = r./scalex; -------------------------------------------------------------------------------- /distributions/normloglik.m: -------------------------------------------------------------------------------- 1 | function [LL,lls]=normloglik(x,mu,sigma2) 2 | % Log-likelihood for the normal distribution 3 | % 4 | % USAGE: 5 | % [LL,LLS]=normloglik(X,MU,SIGMA2) 6 | % 7 | % INPUTS: 8 | % X - Normal random variables, either scalar or column vector 9 | % MU - Mean of X, either scalar or size(x) 10 | % SIGMA2 - Variance of X, either scalar or size(x) 11 | % 12 | % OUTPUTS: 13 | % LL - Log-likelihood evaluated at X 14 | % LLS - Vector of log-likelihoods corresponding to X 15 | % 16 | % COMMENTS: 17 | % 18 | % REFERENCES: 19 | % [1] Cassella and Berger (1990) 'Statistical Interence' 20 | % 21 | % See also NORMCDF, NORMINV, NORMRND, NORMPDF 22 | 23 | % Copyright: Kevin Sheppard 24 | % kevin.sheppard@economics.ox.ac.uk 25 | % Revision: 1 Date: 9/1/2005 26 | 27 | [T,K]=size(x); 28 | 29 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 30 | % Input Checking 31 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 32 | if K~=1 33 | error('x must be a column vector'); 34 | end 35 | 36 | if nargin==1 37 | sigma2=ones(T,K); 38 | elseif nargin==2 39 | %Check mu's conformability 40 | if length(mu)~=1 && ~all(size(mu)==[T K]) 41 | error('mu must be either a scalar or the same size as X'); 42 | end 43 | x=x-mu; 44 | sigma2=ones(T,K); 45 | elseif nargin==3 46 | if length(mu)~=1 && ~all(size(mu)==[T K]) 47 | error('mu must be either a scalar or the same size as X'); 48 | end 49 | if any(sigma2<=0) 50 | error('sigma2 must contain only positive elements') 51 | end 52 | if length(sigma2)==1 53 | sigma2=sigma2*ones(T,K); 54 | elseif size(sigma2,1)~=T || size(sigma2,2)~=1 55 | error('sigma2 must be a scalar or a vector with the same dimensions as x'); 56 | end 57 | x=x-mu; 58 | else 59 | error('Only 1 to 3 inputs supported'); 60 | end 61 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 62 | % Input Checking 63 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 64 | 65 | 66 | if nargout>1 67 | %Compute the individual log likelihoods if needed 68 | lls = -0.5*(log(2*pi) + log(sigma2) + x.^2./sigma2); 69 | % Use these to comput the LL 70 | LL = sum(lls); 71 | else 72 | %Compute the log likelihood 73 | LL = -0.5 * (sum(log(sigma2)) + sum((x.^2)./sigma2) + T*log(2*pi)); 74 | end 75 | -------------------------------------------------------------------------------- /distributions/skewtcdf.m: -------------------------------------------------------------------------------- 1 | function p = skewtcdf(x,v,lambda) 2 | % Cumulative Distribution Function (CDF) of Hansen's (1994) Skewed T distribution 3 | % 4 | % USAGE: 5 | % P = skewtcdf(X,V,LAMBDA) 6 | % 7 | % INPUTS: 8 | % X - Standardized T random variables 9 | % V - Degree of freedom parameters, either scalar or size(X) 10 | % LAMBDA - Asymmetry Parameter 11 | % 12 | % OUTPUTS: 13 | % P - Cumulative distribution evaluated at x 14 | % 15 | % COMMENTS: 16 | % V>2 17 | % -1=-a./b).*((1-lambda)/2 + (1+lambda).*(tcdf(y2,v)-0.5)); 50 | 51 | %Original Nonvector code 52 | %cdf = -999.99*ones(T,1); 53 | %for tt = 1:T; 54 | % if x(tt)<(-a(tt)/b(tt)) 55 | % cdf(tt) = (1-lambda(tt)).*tdis_cdf(y1(tt),v(tt)); 56 | % else 57 | % cdf(tt) = ((1-lambda(tt))/2 + (1+lambda(tt)).*(tdis_cdf(y2(tt),v(tt))-0.5)); 58 | % end 59 | %end -------------------------------------------------------------------------------- /distributions/skewtinv.m: -------------------------------------------------------------------------------- 1 | function x=skewtinv(p,v,lambda) 2 | % Inverse Cumulative Distribution Function (CDF) of Hansen's (1994) 'skewed t' 3 | % distribution; Maps [0,1] to a Skewed-t with V degrees of freedom, shape LAMBDA 4 | % 5 | % USAGE: 6 | % X=skewtinv(P,V,LAMBDA) 7 | % 8 | % INPUTS: 9 | % P - Values to be inverted, P in [0,1] 10 | % V - Degree of freedom parameters, either scalar or size(X) 11 | % LAMBDA - Degree of freedom parameters, either scalar or size(X) 12 | % 13 | % OUTPUTS: 14 | % X - Skewed T distributed random variables corresponding to P 15 | % 16 | % COMMENTS: 17 | % V>2 18 | % -.99.99)=NaN; 43 | 44 | c = gamma((v+1)/2)./(sqrt(pi*(v-2)).*gamma(v/2)); 45 | a = 4*lambda.*c.*((v-2)./(v-1)); 46 | b = sqrt(1 + 3*lambda.^2 - a.^2); 47 | 48 | f1 = find(p<((1-lambda)/2)); 49 | f2 = find(p>=((1-lambda)/2)); 50 | 51 | inv1 = (1-lambda(f1))./b(f1).*sqrt((v(f1)-2)./v(f1)).*tinv(p(f1)./(1-lambda(f1)),v(f1))-a(f1)./b(f1); 52 | inv2 = (1+lambda(f2))./b(f2).*sqrt((v(f2)-2)./v(f2)).*tinv(0.5+1./(1+lambda(f2)).*(p(f2)-(1-lambda(f2))./2),v(f2))-a(f2)./b(f2); 53 | x = repmat(NaN,sizeOut); 54 | x(f1) = inv1; 55 | x(f2) = inv2; -------------------------------------------------------------------------------- /distributions/skewtloglik.m: -------------------------------------------------------------------------------- 1 | function [LL,LLS]=skewtloglik(x,mu,sigma2,v,lambda) 2 | % Log likelihood for Hansen's Skewed T distribution 3 | % 4 | % USAGE: 5 | % [LL,LLS]=skewtloglik(X,MU,SIGMA2,V,LAMBDA) 6 | % 7 | % INPUTS: 8 | % X - Standardized T random variables, either scalar or column vector 9 | % MU - Mean of X, either scalar or size(x) 10 | % SIGMA2 - Variance of X, either scalar or size(x) 11 | % V - Degree of freedom parameters, either scalar or size(x) 12 | % LAMBDA - Asymmetry parameter 13 | % 14 | % OUTPUTS: 15 | % LL - Log-likelihood evaluated at X 16 | % LLS - Vector of log-likelihoods corresponding to X 17 | % 18 | % COMMENTS: 19 | % V>2, -11 || v<=2 52 | error('V must be a scalar greater than 2'); 53 | end 54 | if length(lambda)>1 || lambda<=-1 || lambda>=1 55 | error('LAMBDA must be a scalar between -1 and 1'); 56 | end 57 | x=x-mu; 58 | else 59 | error('Only 5 inputs supported'); 60 | end 61 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 62 | % Input Checking 63 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 64 | 65 | %Compute the log likelihood 66 | logc = gammaln((v+1)/2) - gammaln(v/2) - 0.5*log(pi*(v-2)); 67 | c = exp(logc); 68 | 69 | a = 4*lambda.*c.*((v-2)./(v-1)); 70 | logb = 0.5*log(1 + 3*lambda.^2 - a.^2); 71 | b = exp(logb); 72 | 73 | stdresid=x./sqrt(sigma2); 74 | 75 | find1 = (stdresid<(-a./b)); 76 | find2 = (stdresid>=(-a./b)); 77 | LL1 = logb + logc - (v+1)/2.*log(1+1./(v-2).*((b.*stdresid(find1)+a)./(1-lambda)).^2); 78 | LL2 = logb + logc - (v+1)/2.*log(1+1./(v-2).*((b.*stdresid(find2)+a)./(1+lambda)).^2); 79 | LL = sum(LL1) + sum(LL2) - 0.5*sum(log(sigma2)); 80 | 81 | %Compute the individual log likelihoods if needed 82 | if nargout>1 83 | LLS=zeros(T,1); 84 | LLS(find1)=LL1 - 0.5*log(sigma2(find1)); 85 | LLS(find2)=LL2 - 0.5*log(sigma2(find2)); 86 | end 87 | -------------------------------------------------------------------------------- /distributions/skewtpdf.m: -------------------------------------------------------------------------------- 1 | function y = skewtpdf(x, v, lambda) 2 | % Probability Density Function (PDF) of Hansen's (1994) Skewed T distribution 3 | % 4 | % USAGE: 5 | % Y = skewtpdf(X,V,LAMBDA) 6 | % 7 | % INPUTS: 8 | % X - Standardized T random variables 9 | % V - Degree of freedom parameters, either scalar or size(x) 10 | % LAMBDA - Asymmetry Parameter 11 | % 12 | % OUTPUTS: 13 | % Y - Probability density evaluated at X 14 | % 15 | % COMMENTS: 16 | % V>2 17 | % -11)=NaN; 37 | 38 | [err, errtext, sizeOut, v, lambda] = iscompatible(2,v,lambda,size(x)); 39 | 40 | if err 41 | error(errtext) 42 | end 43 | 44 | c = gamma((v+1)/2)./(sqrt(pi*(v-2)).*gamma(v/2)); 45 | a = 4*lambda.*c.*((v-2)./(v-1)); 46 | b = sqrt(1 + 3*lambda.^2 - a.^2); 47 | 48 | y1 = b.*c.*(1 + 1./(v-2).*((b.*x+a)./(1-lambda)).^2).^(-(v+1)/2); 49 | y2 = b.*c.*(1 + 1./(v-2).*((b.*x+a)./(1+lambda)).^2).^(-(v+1)/2); 50 | y = y1.*(x<(-a./b)) + y2.*(x>=(-a./b)); -------------------------------------------------------------------------------- /distributions/skewtrnd.m: -------------------------------------------------------------------------------- 1 | function r = skewtrnd(v,lambda,varargin) 2 | % Generate random variables from Hansen's Skewed T distribution 3 | % with V degrees of freedom and skewness parameter LAMBDA 4 | % 5 | % USAGE: 6 | % R=skewtrnd(V,LAMBDA) 7 | % R=skewtrnd(V,LAMBDA,S1) 8 | % R=skewtrnd(V,LAMBDA,S1,S2,S3,...,SN) 9 | % R=skewtrnd(V,LAMBDA,[S1 S2 S3 ... SN]) 10 | % 11 | % INPUTS: 12 | % V - Degree of freedom parameter. Either scalar or matrix. 13 | % LAMBDA - Skewness parameter 14 | % Sx - [OPTIONAL] Size of output. 15 | % R will be: 16 | % 1 by 1 if V is scalar and no S are entered 17 | % size(V) if V is non-scalar and no S are entered 18 | % S1 by S1 if V is scalar and only S1 is entered 19 | % [S1 S2 ... SN] otherwise 20 | % If V is non-scalar and S are provided, size(V) must equal [S1 S2 ... SN] 21 | % 22 | % OUTPUTS: 23 | % R - Skewed T distributed random variables 24 | % 25 | % COMMENTS: 26 | % V>2 27 | % -.992 16 | % Uses TCDF 17 | % 18 | % REFERENCES: 19 | % [1] Cassella and Berger (1990) 'Statistical Inference' 20 | % 21 | % See also STDTPDF, STDTINV, STDTRND, STDTLOGLIK, TCDF 22 | 23 | % Copyright: 24 | % Kevin Sheppard 25 | % kevin.sheppard@economics.ox.ac.uk 26 | % Revision: 3 Date: 8/1/2005 27 | 28 | if nargin~=2 29 | error('2 inputs required') 30 | end 31 | 32 | [err, errtext, sizeOut, v] = iscompatible(1,v,size(x)); 33 | if err 34 | error(errtext) 35 | end 36 | 37 | %Compute the st 38 | stdev=sqrt(v./(v-2)); 39 | stdev(v<=2)=NaN; 40 | x=x.*stdev; 41 | 42 | p=tcdf(x,v); 43 | -------------------------------------------------------------------------------- /distributions/stdtinv.m: -------------------------------------------------------------------------------- 1 | function x=stdtinv(p,v) 2 | % Inverse Cumulative Distribution Function (CDF) of the Standardized T 3 | % distribution; Maps [0,1] to a standardized Students-t with V degrees of freedom 4 | % 5 | % USAGE: 6 | % X = stdtinv(P,V) 7 | % 8 | % INPUTS: 9 | % P - Values to be inverted, P in [0,1] 10 | % V - Degree of freedom parameters, either scalar or size(X) 11 | % 12 | % OUTPUTS: 13 | % X - Standardized T distributed random variables corresponding to P 14 | % 15 | % COMMENTS: 16 | % V>2 17 | % 18 | % REFERENCES: 19 | % [1] Cassella and Berger (1990) 'Statistical Interence' 20 | % 21 | % See also STDTCDF, STDTINV, STDTRND, STDTLOGLIK, TPDF 22 | 23 | % Copyright: 24 | % Kevin Sheppard 25 | % kevin.sheppard@economics.ox.ac.uk 26 | % Revision: 3 Date: 9/1/2005 27 | 28 | 29 | if nargin~=2 30 | error('2 inputs required') 31 | end 32 | 33 | [err, errtext, sizeOut, v] = iscompatible(1,v,size(p)); 34 | if err 35 | error(errtext) 36 | end 37 | 38 | x=tinv(p,v); 39 | 40 | stdev=sqrt(v./(v-2)); 41 | stdev(v<=2)=NaN; 42 | x=x./stdev; -------------------------------------------------------------------------------- /distributions/stdtloglik.m: -------------------------------------------------------------------------------- 1 | function [ll,lls]=stdtloglik(x,mu,sigma2,nu) 2 | % Log likelihood of the Standardized T distribution 3 | % 4 | % USAGE: 5 | % [LL,LLS]=stdtloglik(X,MU,SIGMA2,NU) 6 | % 7 | % INPUTS: 8 | % X - Standardized T random variables, either scalar or column vector 9 | % MU - Mean of X, either scalar or size(x) 10 | % SIGMA2 - Variance of X, either scalar or size(x) 11 | % V - Degree of freedom parameters, either scalar or size(x) 12 | % 13 | % OUTPUTS: 14 | % LL - Log-likelihood evaluated at X 15 | % LLS - Vector of log-likelihoods corresponding to X 16 | % 17 | % COMMENTS: 18 | % V>2 19 | % 20 | % REFERENCES: 21 | % [1] Cassella and Berger (1990) 'Statistical Inference' 22 | % 23 | % See also STDTCDF, STDTINV, STDTRND, STDTPDF 24 | 25 | % Copyright: 26 | % Kevin Sheppard 27 | % kevin.sheppard@economics.ox.ac.uk 28 | % Revision: 1 Date: 9/1/2004 29 | 30 | [T,K]=size(x); 31 | 32 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 33 | % Input Checking 34 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 35 | if K~=1 36 | error('X must be a column vector'); 37 | end 38 | 39 | if nargin==4 40 | if length(mu)~=1 && ~all(size(mu)==[T K]) 41 | error('mu must be either a scalar or the same size as X'); 42 | end 43 | if any(sigma2<=0) 44 | error('sigma2 must contain only positive elements') 45 | end 46 | if length(sigma2)==1 47 | sigma2=sigma2*ones(T,K); 48 | elseif size(sigma2,1)~=T || size(sigma2,2)~=1 49 | error('sigma2 must be a scalar or a vector with the same dimensions as X'); 50 | end 51 | if length(nu)>1 || nu<=2 52 | error('nu must be a scalar greater than 2'); 53 | end 54 | x=x-mu; 55 | else 56 | error('Only 4 inputs supported'); 57 | end 58 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 59 | % Input Checking 60 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 61 | 62 | %Compute the log likelihood 63 | ll = T*gammaln(0.5*(nu+1)) - T*gammaln(nu/2) - T/2*log(pi*(nu-2)) ... 64 | - 0.5*sum(log(sigma2)) - ((nu+1)/2)*sum(log(1 + (x.^2)./(sigma2*(nu-2)))); 65 | 66 | %Compute the individual log likelihoods if needed 67 | if nargout>1 68 | lls = gammaln(0.5*(nu+1)) - gammaln(nu/2) - 1/2*log(pi*(nu-2))... 69 | - 0.5*(log(sigma2)) - ((nu+1)/2)*(log(1 + (x.^2)./(sigma2*(nu-2)))); 70 | end 71 | -------------------------------------------------------------------------------- /distributions/stdtpdf.m: -------------------------------------------------------------------------------- 1 | function y=stdtpdf(x,mu,sigma2,nu) 2 | % Probability Density Function (PDF) for the Standardized T distribution 3 | % 4 | % USAGE: 5 | % Y = stdtpdf(X,MU,SIGMA2,NU) 6 | % 7 | % INPUTS: 8 | % X - Standardized T random variables 9 | % MU - Mean of X, either scalar or size(x) 10 | % SIGMA2 - Variance of X, either scalar or size(x) 11 | % NU - Degree of freedom parameters, either scalar or size(x) 12 | % 13 | % OUTPUTS: 14 | % Y - Probability density evaluated at X 15 | % 16 | % COMMENTS: 17 | % NU>2 18 | % 19 | % REFERENCES: 20 | % [1] Cassella and Berger (1990) 'Statistical Inference' 21 | % 22 | % See also STDTCDF, STDTINV, STDTRND, STDTLOGLIK, TPDF 23 | 24 | % Copyright: 25 | % Kevin Sheppard 26 | % kevin.sheppard@economics.ox.ac.uk 27 | % Revision: 6 Date: 8/21/2014 28 | 29 | [T,K]=size(x); 30 | 31 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 32 | % Input Checking 33 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 34 | if K~=1 35 | error('X must be a column vector'); 36 | end 37 | 38 | if nargin==4 39 | if length(mu)~=1 && ~all(size(mu)==[T K]) 40 | error('mu must be either a scalar or the same size as X'); 41 | end 42 | if any(sigma2<=0) 43 | error('sigma2 must contain only positive elements') 44 | end 45 | if length(sigma2)==1 46 | sigma2=sigma2*ones(T,K); 47 | elseif size(sigma2,1)~=T || size(sigma2,2)~=1 48 | error('sigma2 must be a scalar or a vector with the same dimensions as X'); 49 | end 50 | if length(nu)>1 || nu<=2 51 | error('nu must be a scalar greater than 2'); 52 | end 53 | x=x-mu; 54 | else 55 | error('Only 4 inputs supported'); 56 | end 57 | 58 | 59 | constant = exp(gammaln( 0.5 * (nu + 1)) - gammaln(0.5 * nu)); 60 | y = constant ./ sqrt(pi * (nu - 2) * sigma2) .* (1 + (x-mu) .^ 2.0 / (sigma2 * (nu - 2))) .^ (-(nu + 1) / 2); 61 | -------------------------------------------------------------------------------- /distributions/stdtrnd.m: -------------------------------------------------------------------------------- 1 | function r=stdtrnd(v,varargin) 2 | % Generate random variables from a Standardized T distribution with V degrees of freedom 3 | % 4 | % USAGE: 5 | % R=stdtrnd(V) 6 | % R=stdtrnd(V,S1) 7 | % R=stdtrnd(V,S1,S2,S3,...,SN) 8 | % R=stdtrnd(V,[S1 S2 S3 ... SN]) 9 | % 10 | % INPUTS: 11 | % V - Degree of freedom parameter. Either scalar or matrix. 12 | % Sx - [OPTIONAL] Size of output. 13 | % R will be: 14 | % 1 by 1 if V is scalar and no S are entered 15 | % size(V) if V is non-scalar and no S are entered 16 | % S1 by S1 if V is scalar and only S1 is entered 17 | % [S1 S2 ... SN] otherwise 18 | % If V is non-scalar and S are provided, size(V) must equal [S1 S2 ... SN] 19 | % 20 | % OUTPUTS: 21 | % R - Standardized T distributed random variables 22 | % 23 | % COMMENTS: 24 | % V>2 25 | % Uses TRND 26 | % 27 | % REFERENCES: 28 | % [1] Cassella and Berger (1990) 'Statistical Interence' 29 | % 30 | % See also STDTPDF, STDTCDF, STDTINV, STDTLL, TINV 31 | 32 | % Copyright: Kevin Sheppard 33 | % kevin.sheppard@economics.ox.ac.uk 34 | % Revision: 3 Date: 9/1/2005 35 | 36 | %v must either be scalar or the same size as that in varargin if present 37 | 38 | if nargin<1 39 | error('At least one input required.') 40 | end 41 | 42 | [err, errtext, sizeOut, v] = iscompatible(1,v,varargin{:}); 43 | 44 | if err 45 | error(errtext) 46 | end 47 | 48 | r=trnd(v,sizeOut); 49 | stdev=sqrt(v./(v-2)); 50 | stdev(v<=2)=NaN; 51 | r=r./stdev; -------------------------------------------------------------------------------- /docs/MATLAB_Function_Reference_2012_final.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/docs/MATLAB_Function_Reference_2012_final.pdf -------------------------------------------------------------------------------- /docs/chapters/kerneldensity.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/docs/chapters/kerneldensity.pdf -------------------------------------------------------------------------------- /docs/chapters/tsresidualplot.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/docs/chapters/tsresidualplot.pdf -------------------------------------------------------------------------------- /docs/icon.lyx: -------------------------------------------------------------------------------- 1 | #LyX 2.0 created this file. For more info see http://www.lyx.org/ 2 | \lyxformat 413 3 | \begin_document 4 | \begin_header 5 | \textclass article 6 | \begin_preamble 7 | \usepackage{scalefnt} 8 | \end_preamble 9 | \use_default_options true 10 | \maintain_unincluded_children false 11 | \language english 12 | \language_package default 13 | \inputencoding auto 14 | \fontencoding global 15 | \font_roman default 16 | \font_sans default 17 | \font_typewriter default 18 | \font_default_family default 19 | \use_non_tex_fonts false 20 | \font_sc false 21 | \font_osf false 22 | \font_sf_scale 100 23 | \font_tt_scale 100 24 | 25 | \graphics default 26 | \default_output_format default 27 | \output_sync 0 28 | \bibtex_command default 29 | \index_command default 30 | \paperfontsize default 31 | \spacing single 32 | \use_hyperref false 33 | \papersize default 34 | \use_geometry false 35 | \use_amsmath 1 36 | \use_esint 1 37 | \use_mhchem 1 38 | \use_mathdots 1 39 | \cite_engine basic 40 | \use_bibtopic false 41 | \use_indices false 42 | \paperorientation portrait 43 | \suppress_date false 44 | \use_refstyle 1 45 | \index Index 46 | \shortcut idx 47 | \color #008000 48 | \end_index 49 | \secnumdepth 3 50 | \tocdepth 3 51 | \paragraph_separation indent 52 | \paragraph_indentation default 53 | \quotes_language english 54 | \papercolumns 1 55 | \papersides 1 56 | \paperpagestyle default 57 | \tracking_changes false 58 | \output_changes false 59 | \html_math_output 0 60 | \html_css_as_file 0 61 | \html_be_strict false 62 | \end_header 63 | 64 | \begin_body 65 | 66 | \begin_layout Standard 67 | \begin_inset ERT 68 | status open 69 | 70 | \begin_layout Plain Layout 71 | 72 | 73 | \backslash 74 | definecolor{oxblue}{RGB}{0,33,71} 75 | \end_layout 76 | 77 | \begin_layout Plain Layout 78 | 79 | 80 | \backslash 81 | pagecolor{oxblue} 82 | \end_layout 83 | 84 | \end_inset 85 | 86 | 87 | \end_layout 88 | 89 | \begin_layout Standard 90 | \begin_inset ERT 91 | status open 92 | 93 | \begin_layout Plain Layout 94 | 95 | 96 | \backslash 97 | scalefont{2} 98 | \end_layout 99 | 100 | \end_inset 101 | 102 | 103 | \end_layout 104 | 105 | \begin_layout Standard 106 | 107 | \color white 108 | \begin_inset Formula $\sigma_{t}^{2}$ 109 | \end_inset 110 | 111 | 112 | \end_layout 113 | 114 | \end_body 115 | \end_document 116 | -------------------------------------------------------------------------------- /duplication/chi2cdf.m: -------------------------------------------------------------------------------- 1 | function p=chi2cdf(x,v) 2 | % Cumulative Distribution Function (CDF) of the Chi-square distribution 3 | % Work-a-round for the Stat's Toolbox chi2cdf 4 | % 5 | % USAGE: 6 | % P = chi2cdf(X,V) 7 | % 8 | % INPUTS: 9 | % X - Chi-square random variables 10 | % V - Degree of freedom parameters, either scalar or size(X) 11 | % 12 | % OUTPUTS: 13 | % P - Cumulative distribution evaluated at X 14 | % 15 | % COMMENTS: 16 | % V>0 17 | % 18 | % REFERENCES: 19 | % 20 | 21 | % Copyright: 22 | % Kevin Sheppard 23 | % kevin.sheppard@economics.ox.ac.uk 24 | % Revision: 3 Date: 8/1/2005 25 | 26 | if nargin~=2 27 | error('2 inputs required') 28 | end 29 | 30 | [err, errtext, sizeOut, v] = iscompatible(1,v,size(x)); 31 | if err 32 | error(errtext) 33 | end 34 | 35 | %Compute the st 36 | p=repmat(NaN,sizeOut); 37 | pl = v>0; 38 | temp=gammainc(x(pl)/2,v(pl)*0.5); 39 | p(pl)=temp; 40 | -------------------------------------------------------------------------------- /duplication/kurtosis.m: -------------------------------------------------------------------------------- 1 | function k=kurtosis(x, flag, dim) 2 | % Estimate the 4th standardized moment from a vector or matix of data. 3 | % 4 | % K=kurtosis(X,FLAG,DIM) 5 | % 6 | % INPUTS 7 | % X - Data to be used in skewness calculation 8 | % FLAG - Not implemented 9 | % DIM - Dimension to compute the kurtosis on if x is not a vector 10 | 11 | % Author: Kevin Sheppard 12 | % kevin.sheppard@economics.ox.ac.uk 13 | % Revision: 3 Date: 2/25/2006 14 | 15 | if nargin==1 16 | dim=1; 17 | end 18 | 19 | ncm1 = mean(x,dim); 20 | ncm2 = mean(x.^2,dim); 21 | ncm3 = mean(x.^3,dim); 22 | ncm4 = mean(x.^4,dim); 23 | 24 | cm2 = ncm2-ncm1.^2; 25 | cm4 = ncm4 - 4*ncm3.*ncm1 + 6*ncm1.^2.*ncm2 - 4.*ncm1.^4 + ncm1.^4; 26 | 27 | k = cm4./cm2.^2; 28 | -------------------------------------------------------------------------------- /duplication/normcdf.m: -------------------------------------------------------------------------------- 1 | function p = normcdf(x,mu,sigma) 2 | % Cumulative Distribution Function (CDF) of the Normal Distribution (Gaussian) 3 | % 4 | % USAGE: 5 | % P = normcdf(X,MU,SIGMA) 6 | % 7 | % INPUTS: 8 | % X - Normally distributed random variables 9 | % MU - Mean parameter 10 | % SIGMA - Standard deviation parameter 11 | % 12 | % OUTPUTS: 13 | % P - Cumulative distribution evaluated at x 14 | % 15 | % COMMENTS: 16 | % SIGMA>0 17 | % 18 | % Uses ERFC 19 | % 20 | % See also NORMPDF, NORMINV, NORMRND, NORMLOGLIK 21 | 22 | %%%%%%%%%%%%%%%%% 23 | % Error Checking 24 | %%%%%%%%%%%%%%%%% 25 | if nargin==1 26 | mu=0; 27 | sigma=1; 28 | elseif nargin==2 29 | sigma=1; 30 | elseif nargin<1 || nargin>3 31 | error('Requires one to three input arguments.') 32 | end 33 | 34 | [err, errtext, sizeOut, mu, sigma] = iscompatible(2,mu,sigma,size(x)); 35 | 36 | if err 37 | error(errtext); 38 | end 39 | %%%%%%%%%%%%%%%%% 40 | % Error Checking 41 | %%%%%%%%%%%%%%%%% 42 | 43 | 44 | % Initialize P to zero. 45 | e = (x-mu)./sigma; 46 | % Find any nan values 47 | good = sigma>0; 48 | p=repmat(NaN,size(x)); 49 | p(good)=1-erfc(e(good)./sqrt(2))/2; -------------------------------------------------------------------------------- /duplication/norminv.m: -------------------------------------------------------------------------------- 1 | function x = norminv(p,mu,sigma) 2 | % Inverse Cumulative Distribution Function (CDF) of the Normal Distribution (Gaussian) 3 | % 4 | % USAGE: 5 | % X = normcdf(P,MU,SIGMA) 6 | % 7 | % INPUTS: 8 | % P - Cumulative distribution values 9 | % MU - Mean parameter 10 | % SIGMA - Standard deviation parameter 11 | % 12 | % OUTPUTS: 13 | % X - Normally distributed random variables 14 | % 15 | % COMMENTS: 16 | % SIGMA>0 17 | % 18 | % Uses ERFINV 19 | % 20 | % See also NORMPDF, NORMINV, NORMRND, NORMLOGLIK 21 | 22 | %%%%%%%%%%%%%%%%% 23 | % Error Checking 24 | %%%%%%%%%%%%%%%%% 25 | if nargin==1 26 | mu=0; 27 | sigma=1; 28 | elseif nargin==2 29 | sigma=1; 30 | elseif nargin<1 || nargin>3 31 | error('Requires one to three input arguments.') 32 | end 33 | 34 | [err, errtext, sizeOut, mu, sigma] = iscompatible(2,mu,sigma,size(p)); 35 | 36 | if err 37 | error(errtext); 38 | end 39 | %%%%%%%%%%%%%%%%% 40 | % Error Checking 41 | %%%%%%%%%%%%%%%%% 42 | 43 | % Find any nan values 44 | good = sigma>0 & p>=0 & p<=1; 45 | x=repmat(NaN,size(p)); 46 | x(p==.5)=0; 47 | x(good & p>.5) = erfinv(2*(p(good & p>.5)-0.5))*sqrt(2); 48 | x(good & p<.5) = -erfinv(2*(-p(good & p<.5)+0.5))*sqrt(2); 49 | x=x.*sigma+mu; -------------------------------------------------------------------------------- /duplication/normpdf.m: -------------------------------------------------------------------------------- 1 | function y = normpdf(x,mu,sigma) 2 | % Probability Density Function (PDF) of the Normal Distribution (Gaussian) 3 | % 4 | % USAGE: 5 | % Y = normpdf(X,MU,SIGMA) 6 | % 7 | % INPUTS: 8 | % X - Normally distributed random variables 9 | % MU - Mean parameter 10 | % SIGMA - Standard deviation parameter 11 | % 12 | % OUTPUTS: 13 | % Y - Probability density evaluated at x 14 | % 15 | % COMMENTS: 16 | % SIGMA>0 17 | % 18 | % This is a clean room implementation that mimics the core function of 19 | % MATLAB's normpdf. 20 | % 21 | % 22 | % 23 | % See also NORMPDF, NORMINV, NORMRND, NORMLOGLIK 24 | 25 | %%%%%%%%%%%%%%%%% 26 | % Error Checking 27 | %%%%%%%%%%%%%%%%% 28 | if nargin==1 29 | mu=0; 30 | sigma=1; 31 | elseif nargin==2 32 | sigma=1; 33 | elseif nargin<1 || nargin>3 34 | error('Requires one to three input arguments.') 35 | end 36 | 37 | [err, errtext, sizeOut, mu, sigma] = iscompatible(2,mu,sigma,size(x)); 38 | 39 | if err 40 | error(errtext); 41 | end 42 | %%%%%%%%%%%%%%%%% 43 | % Error Checking 44 | %%%%%%%%%%%%%%%%% 45 | 46 | 47 | % Initialize y to nan. 48 | % Find any nan values 49 | good = sigma>0; 50 | y=repmat(NaN,size(x)); 51 | y(good)=(1./(sqrt(2*pi)*sigma)).*exp(-(x(good)-mu(good)).^2./(2*sigma(good).^2)); 52 | -------------------------------------------------------------------------------- /duplication/skewness.m: -------------------------------------------------------------------------------- 1 | function sk=skewness(x, flag, dim) 2 | % Computes the standardized 3rd moment 3 | % 4 | % USAGE 5 | % SK=skewness(X,FLAG,DIM) 6 | % 7 | % INPUTS 8 | % X - Data to be used in skewness calculation 9 | % FLAG - Not implemented 10 | % DIM - Dimension to compute the skewness on if x is not a vector 11 | 12 | % Author: Kevin Sheppard 13 | % kevin.sheppard@economics.ox.ac.uk 14 | % Revision: 3 Date: 2/25/2006 15 | 16 | if nargin==1 17 | dim=1; 18 | end 19 | 20 | ncm1 = mean(x,dim); 21 | ncm2 = mean(x.^2,dim); 22 | ncm3 = mean(x.^3,dim); 23 | 24 | cm2 = ncm2-ncm1.^2; 25 | cm3 = ncm3 - 3*ncm1.*ncm2 + 2.*ncm1.^3; 26 | 27 | sk = cm3./cm2.^(1.5); 28 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/icon.png -------------------------------------------------------------------------------- /mex_source/igarch_core.c: -------------------------------------------------------------------------------- 1 | /* Change this to reflect the apropriate header file */ 2 | #include 3 | #include "mex.h" 4 | #include "matrix.h" 5 | 6 | /* 7 | * igarch_core.c - 8 | * This is a helper function and is part of the UCSD_GARCH toolbox 9 | * You can compile it and should work on any platform. 10 | * 11 | * Copyright: Kevin Sheppard 12 | * kevin.sheppard@economics.ox.ac.uk 13 | * Revision: 3 Date: 9/1/2005 14 | */ 15 | void igarch_core(double *fepsilon, double *parameters, double *backCast, int p, int q, int m, mwSize T, int igarchType, int constant, double *ht) { 16 | mwIndex i, j; 17 | 18 | /* Initialize the final parameter */ 19 | double finalParameter = 1; 20 | for (i = 0; i < p + q -1; i++) { 21 | finalParameter -= parameters[constant+i]; 22 | } 23 | 24 | for (j=0; j1) 61 | mexErrMsgTxt("One output only."); 62 | 63 | /* Get the scalar inputs */ 64 | p = (int)mxGetScalar(prhs[3]); 65 | q = (int)mxGetScalar(prhs[4]); 66 | m = (int)mxGetScalar(prhs[5]); 67 | T = (mwSize)mxGetScalar(prhs[6]); 68 | igarchType = (int)mxGetScalar(prhs[7]); 69 | constant = (int)mxGetScalar(prhs[8]); 70 | 71 | /* Create a pointer to the input matrices . */ 72 | fepsilon = mxGetPr(prhs[0]); 73 | parameters = mxGetPr(prhs[1]); 74 | backCast = mxGetPr(prhs[2]); 75 | 76 | /* Set the output pointer to the output matrix. */ 77 | plhs[0] = mxCreateDoubleMatrix(T, 1, mxREAL); 78 | 79 | /* Create a C pointer to a copy of the output matrix. */ 80 | ht = mxGetPr(plhs[0]); 81 | 82 | /* Call the C subroutine. */ 83 | igarch_core(fepsilon, parameters, backCast, p, q, m, T, igarchType, constant, ht); 84 | } -------------------------------------------------------------------------------- /mex_source/tarch_core.c: -------------------------------------------------------------------------------- 1 | /* Change this to reflect the apropriate header file */ 2 | #include 3 | #include "mex.h" 4 | #include "matrix.h" 5 | 6 | /* 7 | * tarch_core.c - 8 | * This is a helper function and is part of the UCSD_GARCH toolbox 9 | * You can compile it and should work on any platform. 10 | * 11 | * Copyright: Kevin Sheppard 12 | * kevin.sheppard@economics.ox.ac.uk 13 | * Revision: 3 Date: 9/1/2005 14 | */ 15 | void tarch_core(double *fdata, double *fIdata, double *parameters, double *back_cast, int p, int o, int q, int m, mwSize T, int tarch_type, double *ht) 16 | { 17 | mwIndex i, j; 18 | 19 | for (j=0; j1) 59 | mexErrMsgTxt("One output only."); 60 | 61 | /* Get the scalar inputs */ 62 | p = (int)mxGetScalar(prhs[4]); 63 | o = (int)mxGetScalar(prhs[5]); 64 | q = (int)mxGetScalar(prhs[6]); 65 | m = (int)mxGetScalar(prhs[7]); 66 | T = (mwSize)mxGetScalar(prhs[8]); 67 | tarch_type = (int)mxGetScalar(prhs[9]); 68 | 69 | /* Create a pointer to the input matrices . */ 70 | fdata = mxGetPr(prhs[0]); 71 | fIdata = mxGetPr(prhs[1]); 72 | parameters = mxGetPr(prhs[2]); 73 | back_cast = mxGetPr(prhs[3]); 74 | 75 | 76 | /* Set the output pointer to the output matrix. */ 77 | plhs[0] = mxCreateDoubleMatrix(T,1, mxREAL); 78 | 79 | /* Create a C pointer to a copy of the output matrix. */ 80 | ht = mxGetPr(plhs[0]); 81 | 82 | /* Call the C subroutine. */ 83 | tarch_core(fdata, fIdata, parameters, back_cast, p, o, q, m, T, tarch_type, ht); 84 | 85 | } -------------------------------------------------------------------------------- /multivariate/bekk_constraint.m: -------------------------------------------------------------------------------- 1 | function [c,ceq] = bekk_constraint(parameters,data,dataAsym,p,o,q,backCast,backCastAsym,type) %#ok<*INUSL> 2 | % Non-linear constraint for estimation of BEKK(p,o,q) multivariate volatility models 3 | % 4 | % USAGE: 5 | % [C,CEQ] = bekk_constraint(PARAMETERS,DATA,DATAASYM,P,O,Q,BACKCAST,BACKCASTASYM,TYPE) 6 | % 7 | % INPUTS: 8 | % See bekk_likelihood 9 | % 10 | % OUTPUTS: 11 | % C - Vector of inequality constraints 12 | % CEQ - Empty 13 | % 14 | % COMMENTS: 15 | % 16 | % EXAMPLES: 17 | % 18 | % See also BEKK, BEKK_LIKELIHOOD 19 | 20 | % Copyright: Kevin Sheppard 21 | % kevin.sheppard@economics.ox.ac.uk 22 | % Revision: 1 Date: 3/27/2012 23 | 24 | ceq = []; 25 | k = size(data,2); 26 | [~,A,G,B] = bekk_parameter_transform(parameters,p,o,q,k,type); 27 | 28 | switch type 29 | case 1 30 | c = sum(A(1,1,:).^2,3) + sum(B(1,1,:).^2,3) + 0.5*sum(G(1,1,:).^2,3) - 1; 31 | case 2 32 | c = diag(sum(A.^2,3) + sum(B.^2,3) + 0.5*sum(G.^2,3) - 1); 33 | case 3 34 | m = zeros(k*k); 35 | for i=1:p 36 | m = m + kron(A(:,:,i),A(:,:,i)); 37 | end 38 | for i=1:o 39 | m = m + 0.5*kron(G(:,:,i),G(:,:,i)); 40 | end 41 | for i=1:q 42 | m = m + kron(B(:,:,i),B(:,:,i)); 43 | end 44 | c = abs(eig(m)) - .99998; 45 | end 46 | -------------------------------------------------------------------------------- /multivariate/bekk_likelihood.m: -------------------------------------------------------------------------------- 1 | function [ll,lls,Ht] = bekk_likelihood(parameters,data,dataAsym,p,o,q,backCast,backCastAsym,type) 2 | % Likelihood for BEKK(p,q) multivarate volatility model estimation 3 | % 4 | % USAGE: 5 | % [LL,LLS,HT] = bekk_likelihood(PARAMETERS,DATA,P,O,Q,BACKCAST,TYPE) 6 | % 7 | % INPUTS: 8 | % PARAMETERS - Vector of parameters required to compute the (negative) of the log-likelihood 9 | % DATA - K by K by T array of data 10 | % DATAASYM - K by K by T array of asymmetric data 11 | % P - Positive, scalar integer representing the number of symmetric innovations 12 | % O - Non-negative, scalar integer representing the number of asymmetric innovations 13 | % Q - Non-negative, scalar integer representing the number of conditional covariance lags 14 | % BACKCAST - K by K matrix to use for back casting 15 | % TYPE - Number indicating type: 16 | % 1 - Scalar 17 | % 2 - Diagonal 18 | % 3 - Full 19 | % 20 | % OUTPUTS: 21 | % LL - The log likelihood evaluated at the PARAMETERS 22 | % LLS - A T by 1 vector of log-likelihoods 23 | % HT - A [K K T] dimension matrix of conditional covariances 24 | % 25 | % COMMENTS: 26 | % 27 | % See also BEKK 28 | 29 | % Copyright: Kevin Sheppard 30 | % kevin.sheppard@economics.ox.ac.uk 31 | % Revision: 1 Date: 3/27/2012 32 | 33 | % Get the parameters together 34 | T = size(data,3); 35 | k = size(data,2); 36 | 37 | [C,A,G,B] = bekk_parameter_transform(parameters,p,o,q,k,type); 38 | 39 | Ht = zeros(k,k,T); 40 | lls = zeros(T,1); 41 | logLikConst = k*log(2*pi); 42 | 43 | for i=1:T 44 | Ht(:,:,i) = C; 45 | for j=1:p 46 | if (i-j)<=0 47 | Ht(:,:,i) = Ht(:,:,i) + A(:,:,j)'*backCast*A(:,:,j); 48 | else 49 | Ht(:,:,i) = Ht(:,:,i) + A(:,:,j)'*data(:,:,i-j)*A(:,:,j); 50 | end 51 | end 52 | for j=1:o 53 | if (i-j)<=0 54 | Ht(:,:,i) = Ht(:,:,i) + G(:,:,j)'*backCastAsym*G(:,:,j); 55 | else 56 | Ht(:,:,i) = Ht(:,:,i) + G(:,:,j)'*dataAsym(:,:,i-j)*G(:,:,j); 57 | end 58 | end 59 | for j=1:q 60 | if (i-j)<=0 61 | Ht(:,:,i) = Ht(:,:,i) + B(:,:,j)'*backCast*B(:,:,j); 62 | else 63 | Ht(:,:,i) = Ht(:,:,i) + B(:,:,j)'*Ht(:,:,i-j)*B(:,:,j); 64 | end 65 | end 66 | lls(i) = 0.5*(logLikConst + log(det(Ht(:,:,i))) + sum(diag(Ht(:,:,i)^(-1)*data(:,:,i)))); 67 | end 68 | ll = sum(lls); 69 | 70 | if isnan(ll) || isinf(ll) || ~isreal(ll) 71 | ll = 1e7; 72 | end -------------------------------------------------------------------------------- /multivariate/bekk_parameter_transform.m: -------------------------------------------------------------------------------- 1 | function [C,A,G,B] = bekk_parameter_transform(parameters,p,o,q,k,type) 2 | % Parameter transformation for BEKK(p,o,q) multivariate volatility model simulation and estimation 3 | % 4 | % USAGE: 5 | % [C,A,G,B] = bekk_parameter_transform(PARAMETERS,P,O,Q,K,TYPE) 6 | % 7 | % INPUTS: 8 | % PARAMETERS - Vector of parameters governing the dynamics. See BEKK or BEKK_SIMULATE 9 | % P - Positive, scalar integer representing the number of symmetric innovations 10 | % O - Non-negative, scalar integer representing the number of asymmetric innovations 11 | % Q - Non-negative, scalar integer representing the number of conditional covariance lags 12 | % K - Number of assets 13 | % TYPE - Integer indicating type 14 | % 1: Scalar 15 | % 2: Diagonal 16 | % 3: Full 17 | % 18 | % OUTPUTS: 19 | % C - K by K covariance model intercept 20 | % A - K by K by P matrix of symmetric innovation parameters 21 | % G - K by K by O matrix of asymmetric innovation parameters 22 | % B - K by K by Q matrix of smoothing parameters 23 | % 24 | % COMMENTS: 25 | % 26 | % See also BEKK, BEKK_SIMULATE, BEKK_LIKELIHOOD 27 | 28 | if type==1 29 | numParams = 1; 30 | elseif type==2 31 | numParams = k; 32 | else 33 | numParams = k*k; 34 | end 35 | 36 | k2 = k*(k+1)/2; 37 | C = parameters(1:k2); 38 | C = vec2chol(C); 39 | C = C*C'; 40 | offset = k2; 41 | [V,D] = eig(C); 42 | D = diag(D); 43 | if (min(D))<(2*eps*max(D)) 44 | D((D/max(D))2 71 | ht = zeros(k,k,t); 72 | for i=1:t 73 | h12 = sqrt(htMat(i,:)); 74 | ht(:,:,i) = R .* (h12'*h12); 75 | end 76 | end 77 | -------------------------------------------------------------------------------- /multivariate/ccc_mvgarch_likelihood.m: -------------------------------------------------------------------------------- 1 | function [ll, lls] = ccc_mvgarch_likelihood(parameters,data,htMat) 2 | % Log likelihood for CCC_MVGARCH inference. This function is only used for computing scores. 3 | % 4 | % USAGE: 5 | % [LL, LLS] = ccc_mvgarch_likelihood(PARAMETERS,DATA,HTMAT) 6 | % 7 | % INPUTS: 8 | % PARAMETERS - A vector of constant correlation parameters, K*(K-1)/2 by 1 where 9 | % R = corr_ivech(PARAMETERS) 10 | % DATA - K x K x T 3D array of positive semi-definite matrices. 11 | % HTMAT - T by K matrix of fit conditional variances. 12 | % 13 | % OUTPUTS: 14 | % LL - Minus 1 times the log likelihood 15 | % LLS - Time series of log likelihoods (Also multiplied by -1) 16 | % 17 | % COMMENTS: 18 | % See also CCC_MVGARCH 19 | 20 | % Copyright: Kevin Sheppard 21 | % kevin.sheppard@economics.ox.ac.uk 22 | % Revision: 4 Date: 10/28/2009 23 | 24 | [k, nothing, t] = size(data); 25 | % Construct the correlation matrix 26 | R = corr_ivech(parameters); 27 | % Compute the likelihood 28 | Rinv = inv(R); 29 | LogDetR = log(det(R)); 30 | llconst = k*log(2*pi); 31 | lls = zeros(t,1); 32 | for i=1:t 33 | stdResid = data(:,:,i)./sqrt(htMat(i,:)'*htMat(i,:)); 34 | lls(i) = 0.5 * (llconst + sum(log(htMat(i,:))) + LogDetR + trace(Rinv*stdResid)); 35 | end 36 | ll = sum(lls); 37 | -------------------------------------------------------------------------------- /multivariate/dcc_fit_variance.m: -------------------------------------------------------------------------------- 1 | function [H,univariate] = dcc_fit_variance(data,p,o,q,gjrType,startingVals) 2 | % Fits TARCH models for use in DCC and related estimators 3 | % 4 | % USAGE: 5 | % [H,UNIVARIATE] = dcc_fit_variance(DATA,P,O,Q,GJRTYPE) 6 | % 7 | % INPUTS: 8 | % DATA - A column of mean zero data 9 | % P - K by 1 vector of positive, scalar integers representing the number of symmetric innovations 10 | % O - K by 1 vector of non-negative scalar integers representing the number of asymmetric innovations (0 11 | % for symmetric processes) 12 | % Q - K by 1 vector of non-negative, scalar integers representing the number of lags of conditional 13 | % variance (0 for ARCH) 14 | % GJRTYPE - K by 1 vector of model types: 15 | % 1 - Model evolves in absolute values 16 | % 2 - Model evolves in squares [DEFAULT] 17 | % STARTINGVALS - [OPTIONAL] K+sum(P)+sum(O)+sum(Q) vector of starting values 18 | % 19 | % OUTPUTS: 20 | % H - T by K matrix of conditional variances 21 | % UNIVARIATE - A cell array of structures used to reconstruct the variance 22 | % 23 | % COMMENTS: 24 | % 25 | % See also TARCH, DCC, CCC_MVGARCH 26 | 27 | % Copyright: Kevin Sheppard 28 | % kevin.sheppard@economics.ox.ac.uk 29 | % Revision: 1 Date: 17/4/2012 30 | 31 | 32 | if size(startingVals,2)>size(startingVals,1) 33 | startingVals = startingVals'; 34 | end 35 | 36 | [T,k] = size(data); 37 | H = zeros(T,k); 38 | univariate = cell(k,1); 39 | univariteOptions = optimset('fminunc'); 40 | univariteOptions.Display = 'none'; 41 | univariteOptions.LargeScale = 'off'; 42 | offset = 0; 43 | 44 | for i=1:k 45 | if ~isempty(startingVals) 46 | count = 1+p(i)+o(i)+q(i); 47 | volStartingVals = startingVals(offset + (1:count)); 48 | offset = offset + count; 49 | else 50 | volStartingVals = []; 51 | end 52 | [parameters, ~, ht, ~, ~, scores, diagnostics] = tarch(data(:,i),p(i),o(i),q(i), [], gjrType(i), volStartingVals, univariteOptions); 53 | % Store output for later use 54 | univariate{i}.p = p(i); 55 | univariate{i}.o = o(i); 56 | univariate{i}.q = q(i); 57 | univariate{i}.fdata = diagnostics.fdata; 58 | univariate{i}.fIdata = diagnostics.fIdata; 59 | univariate{i}.back_cast = diagnostics.back_cast; 60 | univariate{i}.m = diagnostics.m; 61 | univariate{i}.T = diagnostics.T; 62 | univariate{i}.tarch_type = gjrType(i); 63 | univariate{i}.parameters = parameters; 64 | univariate{i}.ht = ht; 65 | univariate{i}.A = diagnostics.A; 66 | univariate{i}.scores = scores; 67 | H(:,i) = ht; 68 | end 69 | -------------------------------------------------------------------------------- /multivariate/dcc_inference_objective.m: -------------------------------------------------------------------------------- 1 | function [obj,objs] = dcc_inference_objective(parameters,data,dataAsym,m,l,n,univariate) %#ok 2 | % Objective function used by DCC, CCC and related multivariate volatility models to perform 3 | % inference. It is not used (and cannot be used) to estimate parameters. 4 | % 5 | % USAGE: 6 | % [OBJ,OBJS] = dcc_inference_objective(PARAMETERS,DATA,DATAASYM,M,L,N,UNIVARIAT) 7 | % 8 | % INPUTS: 9 | % PARAMETERS - Vector of ADCC parameters including possibly volatility and intercepts 10 | % DATA - A T by K matrix of zero mean residuals -OR- 11 | % K by K by T array of covariance estimators (e.g. realized covariance) 12 | % DATAASYM - [OPTIONAL] K by K by T array of asymmetric covariance estimators only needed if 13 | % DATA is 3-dimensional and O>0 or L>0 14 | % M - Order of symmetric innovations in DCC model 15 | % L - Order of asymmetric innovations in ADCC model 16 | % N - Order of lagged correlation in DCC model 17 | % UNIVARIATE - Cell array of structures containing information needed to compute volatilities. 18 | % 19 | % OUTPUTS: 20 | % OBJ - "As if" objective for estimating correlation intercept parameters 21 | % OBJS - T by 1 vector of "as if" objectives for estimating correlation intercept parameters 22 | % 23 | % COMMENTS: 24 | % 25 | % See also DCC, CCC_MVGARCH 26 | 27 | % Copyright: Kevin Sheppard 28 | % kevin.sheppard@economics.ox.ac.uk 29 | % Revision: 1 Date: 4/13/2012 30 | 31 | 32 | [k,~,T] = size(data); 33 | % Parse parameters 34 | count = 0; 35 | for i=1:k 36 | u = univariate{i}; 37 | count = count + u.p+u.o+u.q+1; 38 | end 39 | garchParameters = parameters(1:count); 40 | offset = count; 41 | % R is next 42 | count = k*(k-1)/2; 43 | R = corr_ivech(parameters(offset + (1:count))); 44 | offset = offset + count; 45 | if l>0 46 | count = k*(k+1)/2; 47 | N = ivech(parameters(offset+(1:count))); 48 | end 49 | 50 | H = dcc_reconstruct_variance(garchParameters,univariate); 51 | stdData = zeros(k,k,T); 52 | stdDataAsym = zeros(k,k,T); 53 | for t=1:T 54 | h = sqrt(H(t,:)); 55 | stdData(:,:,t) = data(:,:,t)./(h'*h); 56 | stdDataAsym(:,:,t) = dataAsym(:,:,t)./(h'*h); 57 | end 58 | 59 | scales = diag(mean(stdData,3)); 60 | objs = zeros(T,1); 61 | for j=1:k-1 % Cols 62 | for i=j+1:k % Rows 63 | scale = sqrt(scales(i)*scales(j)); 64 | errors = squeeze(stdData(i,j,:))/scale - R(i,j); 65 | objs = objs + 0.5*(errors.^2); 66 | end 67 | end 68 | 69 | if l>0 70 | for j=1:k 71 | for i= j:k 72 | errors = squeeze(stdDataAsym(i,j,:)) - N(i,j); 73 | objs = objs + 0.5*(errors.^2); 74 | end 75 | end 76 | end 77 | 78 | obj = sum(objs); 79 | 80 | -------------------------------------------------------------------------------- /multivariate/dcc_reconstruct_variance.m: -------------------------------------------------------------------------------- 1 | function H = dcc_reconstruct_variance(garchParameters,univariate) 2 | % Computes the variance according to TARCH models for use in DCC and related estimators 3 | % 4 | % USAGE: 5 | % [H] = dcc_reconstruct_variance(GARCHPARAMETERS,UNIVARIATE) 6 | % 7 | % INPUTS: 8 | % PARAMETERS - A vector of parameters with K+sum(P)+sum(O)+sum(Q) elemments in the order 9 | % [vol1 vol2 ... volK] 10 | % UNIVARIATE - A cell array of structures used to reconstruct the variance 11 | % 12 | % OUTPUTS: 13 | % H - T by K matrix of conditional variances 14 | % 15 | % COMMENTS: 16 | % 17 | % See also TARCH, DCC, CCC_MVGARCH 18 | 19 | % Copyright: Kevin Sheppard 20 | % kevin.sheppard@economics.ox.ac.uk 21 | % Revision: 1 Date: 17/4/2012 22 | 23 | k = length(univariate); 24 | T = univariate{1}.T-univariate{1}.m; 25 | H = zeros(T,k); 26 | 27 | offset = 0; 28 | for i=1:k 29 | u = univariate{i}; 30 | count = u.p+u.o+u.q+1; 31 | volParameters = garchParameters(offset + (1:count)); 32 | offset = offset+count; 33 | ht = tarch_core(u.fdata,u.fIdata,volParameters,u.back_cast,u.p,u.o,u.q,u.m,u.T,u.tarch_type); 34 | H(:,i) = ht(u.m+1:u.T); 35 | end -------------------------------------------------------------------------------- /multivariate/ogarch_likelihood.m: -------------------------------------------------------------------------------- 1 | function [ll,lls] = ogarch_likelihood(parameters,data,p,q,gjrType,backCast) 2 | % Targetted log-likelihood for use in estimation of volatility models in OGARCH models 3 | % 4 | % USAGE: 5 | % [LL,LLS] = ogarch_likelihood(PARAMETERS,DATA,P,Q,GJRTYPE,BACKCAST) 6 | % 7 | % INPUTS: 8 | % PARAMETERS - P + Q by 1 vector of parameters 9 | % DATA - A T by K matrix of zero mean residuals 10 | % P - Positive, scalar integer representing the number of symmetric innovations 11 | % Q - Non-negative, scalar integer representing the number of conditional covariance lags 12 | % GJRTYPE - Scalar, either 1 (TARCH/AVGARCH) or 2 (GJRGARCH/GARCH/ARCH) 13 | % BACKCAST - Value to use for back cating 14 | % 15 | % OUTPUTS: 16 | % LL - The log likelihood computed at PARAMETERS 17 | % 18 | % COMMENTS: 19 | % Uses 1-sum(PARAMETERS) as the intercept, which is an identifying assumption in OGARCH models 20 | 21 | % Copyright: Kevin Sheppard 22 | % kevin.sheppard@economics.ox.ac.uk 23 | % Revision: 1 Date: 4/15/2012 24 | 25 | volParameters = [1-sum(parameters) parameters]; 26 | volParameters(volParameters<0) = 0; 27 | v = tarch_core_simple(data,volParameters,backCast,0,p,0,q,gjrType); 28 | lls = 0.5 * (log(2*pi) + log(v) + data.^2./v); 29 | ll = sum(lls); -------------------------------------------------------------------------------- /multivariate/rarch_constraint.m: -------------------------------------------------------------------------------- 1 | function [c,ceq] = rarch_constraint(parameters,data,p,q,C,backCast,type,isJoint,isCChol) %#ok<*INUSL> 2 | % Non-linear constraint for estimation of RARCH(p,q) multivariate volatility models 3 | % 4 | % USAGE: 5 | % [C,CEQ] = rarch_constraint(PARAMETERS,DATA,P,Q,C,BACKCAST,TYPE,ISJOINT) 6 | % 7 | % INPUTS: 8 | % See rarch_likelihood 9 | % 10 | % OUTPUTS: 11 | % C - Vector of inequality constraints 12 | % CEQ - Empty 13 | % 14 | % COMMENTS: 15 | % 16 | % See also RARCH, RARCH_LIKELIHOOD 17 | 18 | % Copyright: Kevin Sheppard 19 | % kevin.sheppard@economics.ox.ac.uk 20 | % Revision: 1 Date: 3/27/2012 21 | 22 | ceq = []; 23 | k = size(data,1); 24 | [~,A,B] = rarch_parameter_transform(parameters,p,q,k,C,type,isJoint,isCChol); 25 | constraint = diag(sum(A.^2,3)+sum(B.^2,3) - .99998); 26 | switch type 27 | case 1 28 | c = constraint(1); 29 | case 2 30 | theta = parameters(length(parameters)).^2; 31 | c = diag(sum(A.^2,3)) - theta; 32 | case 3 33 | c = constraint; 34 | end 35 | -------------------------------------------------------------------------------- /multivariate/rarch_likelihood.m: -------------------------------------------------------------------------------- 1 | function [ll, lls, Ht] = rarch_likelihood(parameters,data,p,q,C,backCast,type,isJoint,isCChol) 2 | % Likelihood for RARCH(p,q) multivariate volatility model of Noureldin, Shephard and Sheppard 3 | % 4 | % USAGE: 5 | % [LL,LLS,HT] = rarch_likelihood(PARAMETERS,DATA,P,Q,C,BACKCAST,TYPE,ISJOINT) 6 | % 7 | % INPUTS: 8 | % PARAMETERS - Vector of parameters required to compute the (negative) of the log-likelihood 9 | % DATA - K by K by T array of data 10 | % P - Positive, scalar integer representing the number of symmetric innovations 11 | % Q - Non-negative, scalar integer representing the number of conditional covariance lags 12 | % C - Unconditional covariance of the data 13 | % BACKCAST - K by K matrix to use for back casting 14 | % TYPE - Number indicating type: 15 | % 1 - Scalar 16 | % 2 - Common Persistence 17 | % 3 - Diagonal 18 | % ISJOINT - Boolean indicating wether the estimation is joint or not 19 | % 20 | % OUTPUTS: 21 | % LL - The log likelihood evaluated at the PARAMETERS 22 | % LLS - A T by 1 vector of log-likelihoods 23 | % HT - A [K K T] dimension matrix of conditional covariances 24 | % 25 | % COMMENTS: 26 | % When ISJOINT==1, the first K*(K+1)/2 of the parameters are chol2vec(chol(C)'). 27 | % 28 | % See also RARCH 29 | 30 | % Copyright: Kevin Sheppard 31 | % kevin.sheppard@economics.ox.ac.uk 32 | % Revision: 1 Date: 3/27/2012 33 | 34 | % Get the parameters together 35 | T = size(data,3); 36 | k = size(data,2); 37 | 38 | [C,A,B] = rarch_parameter_transform(parameters,p,q,k,C,type,isJoint,isCChol); 39 | % Fix B in case of CP 40 | B(B<0)= 0; 41 | 42 | Gt = zeros(k,k,T); 43 | e = zeros(k,k,T); 44 | lls = zeros(T,1); 45 | C12 = C^(0.5); 46 | Cm12 = C^(-0.5); 47 | intercept = eye(k) - sum(A.^2,3) - sum(B.^2,3); 48 | dint = diag(intercept); 49 | dint(dint<.000001)=.000001; 50 | intercept = diag(dint); 51 | logLikConst = k*log(2*pi); 52 | 53 | for i=1:T 54 | e(:,:,i) = Cm12 * data(:,:,i) * Cm12; 55 | Gt(:,:,i+1) = intercept; 56 | for j=1:p 57 | if (i-j)<=0 58 | Gt(:,:,i) = Gt(:,:,i) + A(:,:,j)*backCast*A(:,:,j); 59 | else 60 | Gt(:,:,i) = Gt(:,:,i) + A(:,:,j)*e(:,:,i-j)*A(:,:,j); 61 | end 62 | end 63 | for j=1:q 64 | if (i-j)<=0 65 | Gt(:,:,i) = Gt(:,:,i) + B(:,:,j)*backCast*B(:,:,j); 66 | else 67 | Gt(:,:,i) = Gt(:,:,i) + B(:,:,j)*Gt(:,:,i-j)*B(:,:,j); 68 | end 69 | end 70 | V = C12*Gt(:,:,i)*C12; 71 | lls(i) = 0.5*(logLikConst + log(det(V)) + sum(diag(V^(-1)*data(:,:,i)))); 72 | end 73 | ll = sum(lls); 74 | 75 | if isnan(ll) || isinf(ll) || ~isreal(ll) 76 | ll = 1e7; 77 | end 78 | 79 | if nargout>2 80 | Ht = zeros(k,k,T); 81 | for i=1:T 82 | Ht(:,:,i) = C12*Gt(:,:,i)*C12; 83 | end 84 | end -------------------------------------------------------------------------------- /multivariate/rarch_parameter_transform.m: -------------------------------------------------------------------------------- 1 | function [C,A,B] = rarch_parameter_transform(parameters,p,q,k,C,type,isJoint,isCChol) 2 | % Parameter transformation for RARCH(p,q) multivariate volatility model simulation and estimation 3 | % 4 | % USAGE: 5 | % [C,A,B] = rarch_parameter_transform(PARAMETERS,P,Q,K,C,TYPE,ISJOINT) 6 | % 7 | % INPUTS: 8 | % PARAMETERS - Vector of parameters governing the dynamics. See RARCH or RARCH_SIMULATE 9 | % P - Positive, scalar integer representing the number of symmetric innovations 10 | % Q - Non-negative, scalar integer representing the number of conditional covariance 11 | % lags. When using 'CP' model, 0<=q<=1 12 | % K - Number of assets 13 | % C - Unconditional covariance of data. Ignored if ISJOINT==1 14 | % TYPE - Integer indicating type 15 | % 1: Scalar 16 | % 2: CP 17 | % 3: Diagonal 18 | % ISJOINT - Boolean indicating whether PARAMETER contains only the dynamics (ISJOINT==false) or 19 | % both the Cholesky of the unconditional and the dynamic parameters 20 | % OUTPUTS: 21 | % C - K by K unconditional covariance matrix 22 | % A - K by K by P matrix of innovation parameters 23 | % B - K by K by Q matrix of smoothing parameters 24 | % 25 | % COMMENTS: 26 | % When ISJOINT==1, the first K*(K+1)/2 of the parameters are chol2vec(chol(C)'). 27 | % 28 | % See also RARCH, RARCH_SIMULATE, RARCH_LIKELIHOOD 29 | 30 | % Scalar defaults 31 | numA = 1; 32 | numB = 1; 33 | if type>=2 % Common Persistence 34 | numA = k; 35 | end 36 | if type==3 % Diagonal 37 | numB = k; 38 | end 39 | 40 | parameterCount = 0; 41 | if isJoint 42 | k2 = k*(k+1)/2; 43 | C = parameters(1:k2); 44 | if isCChol 45 | C = vec2chol(C); 46 | C = C*C'; 47 | % Ensure C is PSD 48 | [V,D] = eig(C); 49 | D = diag(D); 50 | if (min(D))<(2*eps*max(D)) 51 | D((D/max(D))0 83 | theta = B(1,1,1).^2; 84 | B = theta - diag(sum(A.^2,3)); 85 | B(B<0)=0; 86 | B = diag(sqrt(B)); 87 | end 88 | -------------------------------------------------------------------------------- /multivariate/rcc_constraint.m: -------------------------------------------------------------------------------- 1 | function [c,ceq] = rcc_constraint(parameters,data,m,n,R,backCast,stage,type,composite,isJoint,isInference,rScale,univariate) %#ok 2 | % Non-linear constraint for estimation of RARCH(p,q) multivariate volatility models 3 | % 4 | % USAGE: 5 | % [C,CEQ] = rarch_constraint(PARAMETERS,DATA,P,Q,C,BACKCAST,TYPE,ISJOINT) 6 | % 7 | % INPUTS: 8 | % See rarch_likelihood 9 | % 10 | % OUTPUTS: 11 | % C - Vector of inequality constraints 12 | % CEQ - Empty 13 | % 14 | % COMMENTS: 15 | % 16 | % See also RARCH, RARCH_LIKELIHOOD 17 | 18 | % Copyright: Kevin Sheppard 19 | % kevin.sheppard@economics.ox.ac.uk 20 | % Revision: 1 Date: 3/27/2012 21 | 22 | ceq = []; 23 | k = size(data,1); 24 | if stage==3 25 | tempParameters = parameters; 26 | else 27 | tempParameters = parameters(k*(k-1)/2:length(parameters)); 28 | end 29 | [~,A,B] = rarch_parameter_transform(tempParameters,m,n,k,[],type,false,false); 30 | constraint = diag(sum(A.^2,3)+sum(B.^2,3) - .99998); 31 | switch type 32 | case 1 33 | c = constraint(1); 34 | case 2 35 | theta = parameters(length(parameters)).^2; 36 | c = diag(sum(A.^2,3)) - theta; 37 | case 3 38 | c = constraint; 39 | end 40 | -------------------------------------------------------------------------------- /multivariate/riskmetrics.m: -------------------------------------------------------------------------------- 1 | function Ht = riskmetrics(data,lambda,backCast) 2 | % Computes the Riskmetrics or other EWMA covariance 3 | % 4 | % USAGE: 5 | % [HT] = riskmetrics(DATA,LAMBDA,BACKCAST) 6 | % 7 | % INPUTS: 8 | % DATA - A T by K matrix of zero mean residuals -OR- 9 | % K by K by T array of covariance estimators (e.g. realized covariance) 10 | % LAMBDA - EWMA smoothing parameter 0=1 55 | error('LAMBDA must be between 0 and 1.') 56 | end 57 | 58 | if isempty(backCast) 59 | endPoint = max(min(floor(log(.01)/log(lambda)),T),k); 60 | weights = (1-lambda).*lambda.^(0:endPoint-1); 61 | weights = weights/sum(weights); 62 | backCast = zeros(k); 63 | for i=1:endPoint 64 | backCast = backCast + weights(i)*data(:,:,i); 65 | end 66 | 67 | end 68 | 69 | backCast = (backCast+backCast)/2; 70 | if min(eig(backCast))<0 71 | error('BACKCAST must be positive semidefinite if provided.') 72 | end 73 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 74 | % Input Checking 75 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 76 | 77 | Ht = zeros(k,k,T); 78 | Ht(:,:,1) = backCast; 79 | for i=2:T 80 | Ht(:,:,i) = (1-lambda)*data(:,:,i-1) + lambda * Ht(:,:,i-1); 81 | end -------------------------------------------------------------------------------- /multivariate/scalar_vt_vech_itransform.m: -------------------------------------------------------------------------------- 1 | function parameters=scalar_vt_vech_itransform(tparameters,p,o,q,kappa) 2 | % SCALAR_VT_VECH(P,Q) inverse parameter transformation. Used to map parameters 3 | % from the real line to those appropriate for a scalar MVGARCH process. 4 | % Used in the estimation of SCALAR_VT_VECH. 5 | % 6 | % USAGE: 7 | % [PARAMETERS]=scalar_vt_vech_itransform(TPARAMETERS,P,O,Q,KAPPA) 8 | % 9 | % INPUTS: 10 | % TPARAMETERS - Column vector of transformed parameters (-inf,inf) 11 | % P - Positive, scalar integer representing the number of symmetric innovations 12 | % Q - Non-negative, scalar integer representing the number of lags of conditional variance 13 | % 14 | % OUTPUTS: 15 | % PARAMETERS - A 1+p+q column vector of parameters corresponding to 16 | % [alpha(1),...,alpha(p), beta1 ... beta(q)]' 17 | % 18 | % COMMENTS: 19 | % Output parameters will satisfy: 20 | % (1) alpha(i) >= 0 for i = 1,2,...,p 21 | % (2) beta(i) >= 0 for i = 1,2,...,q 22 | % (3) sum(alpha) + sum(beta) < 1 23 | % 24 | % See also SCALAR_VT_VECH 25 | 26 | % Copyright: Kevin Sheppard 27 | % kevin.sheppard@economics.ox.ac.uk 28 | % Revision: 3 Date: 9/1/2005 29 | 30 | %Upper bound to keep it a bit away from 1 31 | UB=.999998; 32 | %Make sure there are not inf causing values 33 | tparameters(tparameters>50)=50; 34 | %Map them to [0,1] 35 | parameters=exp(tparameters)./(1+exp(tparameters)); 36 | %Normalize them, starting with the second 37 | scale=UB; 38 | for i=1:p 39 | parameters(i)=parameters(i)*scale; 40 | scale=scale-parameters(i); 41 | end 42 | for i=p+1:p+o 43 | parameters(i)=parameters(i)*scale*kappa; 44 | scale=scale-parameters(i)/kappa; 45 | end 46 | for i=p+o+1:p+o+q 47 | parameters(i)=parameters(i)*scale; 48 | scale=scale-parameters(i); 49 | end 50 | -------------------------------------------------------------------------------- /multivariate/scalar_vt_vech_transform.m: -------------------------------------------------------------------------------- 1 | function tparameters=scalar_vt_vech_transform(parameters,p,o,q,kappa) 2 | % SCALAR_VT_VECH(P,Q) parameter transformation. Used to map parameters 3 | % from a scalar MVGARCH process to the real line. Used in the estimation of SCALAR_VT_VECH. 4 | % 5 | % USAGE: 6 | % [TPARAMETERS]=scalar_vt_vech_transform(PARAMETERS,P,O,Q,KAPPA) 7 | % 8 | % INPUTS: 9 | % PARAMETERS - Column parameter vector 10 | % P - Positive, scalar integer representing the number of symmetric innovations 11 | % Q - Non-negative, scalar integer representing the number of lags of conditional variance 12 | % 13 | % OUTPUTS: 14 | % TPARAMETERS - A 1+p+q column vector of transformed parameters corresponding to 15 | % [alpha(1),...,alpha(p), beta1 ... beta(q)]' 16 | % 17 | % COMMENTS: 18 | % Input parameters must satisfy: 19 | % (1) alpha(i) >= 0 for i = 1,2,...,p 20 | % (2) beta(i) >= 0 for i = 1,2,...,q 21 | % (3) sum(alpha) + sum(beta) < 1 22 | % 23 | % See also SCALAR_VT_VECH 24 | 25 | % Copyright: Kevin Sheppard 26 | % kevin.sheppard@economics.ox.ac.uk 27 | % Revision: 3 Date: 9/1/2005 28 | 29 | 30 | if size(parameters,2)>size(parameters,1) 31 | parameters = parameters'; 32 | end 33 | %Upper bound to keep it a bit away from 1 34 | UB=.999998; 35 | 36 | alpha=parameters(1:p); 37 | gamma = parameters(p+1:p+o); 38 | beta=parameters(p+o+1:p+o+q); 39 | %Check that the parameters satisfy the necessary constraints 40 | if any(alpha<0) || any(beta<0) || any(gamma<0) || (sum(alpha)+sum(gamma)/kappa+sum(beta))>=UB 41 | error('These do not conform to the necessary set of restrictions to be transformed.') 42 | end 43 | 44 | %Alpha, beta cannot be exactly zero or there will be problems with log() 45 | alpha(alpha<1e-8)=1e-8; 46 | gamma(gamma<1e-8)=1e-8; 47 | beta(beta<1e-8)=1e-8; 48 | %Up the upper bound a small amount to make sure it is satisfied 49 | UB=UB+1e-8*(p+o+q); 50 | 51 | %Set the scale 52 | scale=UB; 53 | %Initialize the transformed parameters 54 | parameters=[alpha;gamma;beta]; 55 | tparameters=[alpha;gamma;beta]; 56 | for i=1:(p) 57 | %Scale the parameters 58 | tparameters(i)=tparameters(i)/scale; 59 | %Use an inverse logistic 60 | tparameters(i)=log(tparameters(i)/(1-tparameters(i))); 61 | %Update the scale 62 | scale=scale-parameters(i); 63 | end 64 | for i=p+1:p+o 65 | %Scale the parameters 66 | tparameters(i)=tparameters(i)/scale/kappa; 67 | %Use an inverse logistic 68 | tparameters(i)=log(tparameters(i)/(1-tparameters(i))); 69 | %Update the scale 70 | scale=scale-parameters(i)/kappa; 71 | end 72 | 73 | for i=p+o+1:p+o+q 74 | %Scale the parameters 75 | tparameters(i)=tparameters(i)/scale; 76 | %Use an inverse logistic 77 | tparameters(i)=log(tparameters(i)/(1-tparameters(i))); 78 | %Update the scale 79 | scale=scale-parameters(i); 80 | end -------------------------------------------------------------------------------- /project_icon_v2.pdn: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/project_icon_v2.pdn -------------------------------------------------------------------------------- /realized/ES_20090817.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/ES_20090817.mat -------------------------------------------------------------------------------- /realized/Since the changed in QRV - 2.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/Since the changed in QRV - 2.docx -------------------------------------------------------------------------------- /realized/Since the changed in QRV.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/Since the changed in QRV.docx -------------------------------------------------------------------------------- /realized/ToDo.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/ToDo.docx -------------------------------------------------------------------------------- /realized/realized_quantile_scales.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/realized_quantile_scales.mat -------------------------------------------------------------------------------- /realized/realized_range_simulation.m: -------------------------------------------------------------------------------- 1 | % This m-file produces the scales used in realized_range. It can be run with more simulations to 2 | % increase the precision of the estimated scales used. If you do this you will have to copy and 3 | % paste the results into the function since it uses a lookup table and interpolation. 4 | 5 | % Clear 6 | clear all 7 | % Number of simulations 8 | BB = 1000000; 9 | 10 | % Number of prices to use in each interval. All integer factors of 23400. The asymptotic value is 11 | % 4*log(2) 12 | 13 | m1 = factor(23400); 14 | m1 = [1 m1]; 15 | ms = m1'; 16 | for i=2:length(m1); 17 | temp = nchoosek(1:length(m1),i); 18 | ms = [ms; unique(prod(m1(temp),2))]; %#ok 19 | end 20 | ms = unique(ms); 21 | maxM = max(ms); 22 | 23 | % Turn the number of prices per window in to a step size 24 | gap = maxM./ms; 25 | ms = ms+1; 26 | % Initialize a place to hold results 27 | M = length(ms); 28 | MC = zeros(BB,M); 29 | % BB simultions 30 | tic 31 | for j = 1:BB 32 | % Resample a single BM 1, 2, ..., 23400 times. 33 | x = [0;cumsum(randn(maxM,1)/sqrt(maxM))]; 34 | for i=1:M 35 | x2 = x(1:gap(i):(maxM+1)); 36 | MC(j,i) = (max(x2)-min(x2))^2; 37 | end 38 | % Display the count and the expected time remaining. 39 | if mod(j,10000)==0 40 | t=toc; 41 | str = [num2str(j) ' iterations complete. The elapsed time is ' num2str(t) '. The expected time remaining is ' num2str(BB*t/j) ]; 42 | disp(str) 43 | end 44 | end 45 | 46 | 47 | % Some smoothing using a concave regression 48 | y = mean(MC); 49 | y(1) = 1; 50 | orig_mean_MC=y; 51 | n = length(y); 52 | x = eye(n); 53 | A1 = [eye(n-1) zeros(n-1,1)] + [zeros(n-1,1) -eye(n-1)]; 54 | A2 = [eye(n-2) zeros(n-2,2)] + [zeros(n-2,1) -2*eye(n-2) zeros(n-2,1)] + [zeros(n-2,2) eye(n-2)]; 55 | b = zeros(2*n-3,1); 56 | concave_mean_MC=lsqlin(x,y,[A1;A2],b); 57 | % Save the results. 58 | %save realized_range_simulation_results orig_mean_MC concave_mean_MC ms 59 | 60 | -------------------------------------------------------------------------------- /realized/realized_range_simulation_results.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/realized_range_simulation_results.mat -------------------------------------------------------------------------------- /realized/realized_threshold_multipower_variation.m: -------------------------------------------------------------------------------- 1 | function [rv,rvSS]=realized_threshold_multipower_variation(price,time,timeType,samplingType,samplingInterval,gamma,thresholdScale,thresholdType,subsamples) 2 | 3 | 4 | c = thresholdScale; 5 | 6 | 7 | logPrice =log(price); 8 | % Filter prices and compute the RV 9 | filteredLogPrice = realized_price_filter(logPrice,time,timeType,samplingType,samplingInterval); 10 | 11 | 12 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 13 | filteredLogPrice = log(price); 14 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 15 | 16 | 17 | 18 | 19 | 20 | returns = diff(filteredLogPrice); 21 | 22 | L = 25; 23 | V = inf*ones(size(returns)); 24 | K = -L:L; 25 | K = 1/sqrt(2*pi)*exp(-(K/L).^2/2); 26 | K(L+(-1:1)) = 0; 27 | m = size(returns,1); 28 | returns2 = returns.^2; 29 | 30 | finished = false; 31 | while ~finished 32 | ind = returns2<(c^2.*V); 33 | Vold = V; 34 | for i=1:m 35 | pl = i-L:i+L; 36 | valid = pl>1 & pl<=m; 37 | tempInd = ind(pl(valid)); 38 | w = K(valid); 39 | V(i) = w*(returns2(pl(valid)).*tempInd)/(w*tempInd); 40 | end 41 | if all(V==Vold) 42 | finished = true; 43 | end 44 | end 45 | 46 | expectedValue = 1./(2*normcdf(-c)*sqrt(pi))*(2/c^2) * gamma(3/2).*gammainc(c^2/2,3/2,'upper') * c^2 *V; 47 | 48 | 49 | rv = returns(ind)'*returns(ind) + sum(expectedValue(~ind)); -------------------------------------------------------------------------------- /realized/seconds2unit.m: -------------------------------------------------------------------------------- 1 | function unit = seconds2unit(seconds,seconds0,seconds1) 2 | % Convert seconds past midnight to unit times 3 | % 4 | % USAGE: 5 | % [UNIT] = seconds2unit(SECONDS,SECONDS0,SECONDS1) 6 | % 7 | % INPUTS: 8 | % SECONDS - m by 1 column vector of times expressed as seconds past midnight 9 | % (e.g. 1:00:00 is 3600, 12:00:15 is 43215) where m>=2 10 | % SECONDS0 - Base time, maps to 0 un the unit interval 11 | % SECONDS1 - End time, maps to 1 un the unit interval 12 | % 13 | % OUTPUTS: 14 | % UNIT - m by 1 column vector of times measured as fraction of time 15 | % between min(SECONDS) and max(SECONDS) 16 | % 17 | % COMMENTS: 18 | % This is a helper function for REALIZED_KERNEL 19 | % 20 | % See also WALL2UNIT, WALL2SECONDS, SECONDS2WALL, REALIZED_KERNEL, REALIZED_VARIANCE 21 | 22 | % Copyright: Kevin Sheppard 23 | % kevin.sheppard@economics.ox.ac.uk 24 | % Revision: 1 Date: 5/1/2008 25 | 26 | 27 | 28 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 29 | % Input Checking 30 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 31 | if nargin~=3 32 | error('Three inputs required.') 33 | end 34 | if any(seconds<0) 35 | error('SECONDS must be non-negative'); 36 | end 37 | if seconds0<0 38 | error('SECONDS0 must be non-negative'); 39 | end 40 | if seconds1<0 41 | error('SECONDS1 must be non-negative'); 42 | end 43 | 44 | if (seconds1-seconds0)size(seconds,1) 49 | seconds=seconds'; 50 | end 51 | 52 | seconds = double(seconds); 53 | seconds0 = double(seconds0); 54 | seconds1 = double(seconds1); 55 | 56 | if size(seconds,2)>1 57 | error('SECONDS must be an m by 1 column vector'); 58 | end 59 | if length(seconds)<2 60 | error('SECONDS must contain at least 2 elements'); 61 | end 62 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 63 | % Input Checking 64 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 65 | unit=(seconds-seconds0)/(seconds1 - seconds0); -------------------------------------------------------------------------------- /realized/seconds2wall.m: -------------------------------------------------------------------------------- 1 | function wall = seconds2wall(seconds) 2 | % Convert seconds past midnight to wall times 3 | % 4 | % USAGE: 5 | % [WALL] = wall2seconds(SECONDS) 6 | % 7 | % INPUTS: 8 | % SECONDS - m by 1 column vector of times measured as seconds past midnight 9 | % 10 | % OUTPUTS: 11 | % WALL - m by 1 column vector of wall times (e.g. 93047, 134529, etc.) 12 | % 13 | % COMMENTS: 14 | % This is a helper function for REALIZED_KERNEL 15 | % 16 | % See also WALL2SECONDS, REALIZED_KERNEL, REALIZED_VARIANCE 17 | 18 | % Copyright: Kevin Sheppard 19 | % kevin.sheppard@economics.ox.ac.uk 20 | % Revision: 1 Date: 5/1/2008 21 | 22 | 23 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 24 | % Input Checking 25 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 26 | if nargin~=1 27 | error('One inputs required.') 28 | end 29 | if any(seconds>=(24*3600)) || any(seconds<0) 30 | error('SECONDS does not contain valid numerical times. Numerical times must satisft 0<=SECONDS<86400'); 31 | end 32 | seconds = double(seconds); 33 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 34 | % Input Checking 35 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 36 | 37 | % Parse and recombine 38 | hr = floor(seconds/3600); 39 | mm = floor((seconds - hr*3600)/60); 40 | ss = rem(seconds,60); 41 | wall = hr*10000 + mm*100 + ss; 42 | 43 | -------------------------------------------------------------------------------- /realized/unit2seconds.m: -------------------------------------------------------------------------------- 1 | function seconds = unit2seconds(unit, seconds0, seconds1) 2 | % Convert unit times to seconds past midnight 3 | % 4 | % USAGE: 5 | % [SECONDS] = seconds2unit(UNIT,SECONDS0,SECONDS1) 6 | % 7 | % INPUTS: 8 | % UNIT - m by 1 column vector of times measured as fraction of time 9 | % between min(SECONDS) and max(SECONDS) 10 | % SECONDS0 - Base time, maps to 0 un the unit interval 11 | % SECONDS1 - End time, maps to 1 un the unit interval 12 | % 13 | % OUTPUTS: 14 | % SECONDS - m by 1 column vector of times expressed as seconds past midnight 15 | % (e.g. 1:00:00 is 3600, 12:00:15 is 43215) where m>=2 16 | % 17 | % COMMENTS: 18 | % This is a helper function for REALIZED_KERNEL 19 | % 20 | % See also SECONDS2UNIT, WALL2UNIT, WALL2SECONDS, SECONDS2WALL, REALIZED_KERNEL, REALIZED_VARIANCE 21 | 22 | % Copyright: Kevin Sheppard 23 | % kevin.sheppard@economics.ox.ac.uk 24 | % Revision: 1 Date: 5/1/2008 25 | 26 | 27 | 28 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 29 | % Input Checking 30 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 31 | if nargin~=3 32 | error('Three inputs required.') 33 | end 34 | if seconds0<0 35 | error('SECONDS0 must be non-negative'); 36 | end 37 | if seconds1<0 38 | error('SECONDS1 must be non-negative'); 39 | end 40 | 41 | if (seconds1-seconds0)size(unit,1) 47 | unit=unit'; 48 | end 49 | 50 | unit = double(unit); 51 | seconds0 = double(seconds0); 52 | seconds1 = double(seconds1); 53 | 54 | if size(unit,2)>1 55 | error('SECONDS must be an m by 1 column vector'); 56 | end 57 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 58 | % Input Checking 59 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 60 | 61 | 62 | 63 | seconds=seconds0+(seconds1-seconds0)*unit; 64 | -------------------------------------------------------------------------------- /realized/unit2wall.m: -------------------------------------------------------------------------------- 1 | function wall = unit2wall(unit, wall0, wall1) 2 | % Convert unit times to wall times 3 | % 4 | % USAGE: 5 | % [WALL] = wall2unit(UNIT,WALL0,WALL1) 6 | % 7 | % INPUTS: 8 | % UNIT - m by 1 column vector of times measured as fraction of time 9 | % between min(WALL0) and max(WALL1) 10 | % WALL0 - Base time, maps to 0 in the unit interval 11 | % WALL1 - End time, maps to 1 in the unit interval 12 | % 13 | % OUTPUTS: 14 | % WALL - m by 1 vector of times measures in 24-hour wall time, such as 15 | % 103421 for 10:34:21 AM or 145311 for 2:53:11 PM 16 | % 17 | % COMMENTS: 18 | % This is a helper function for REALIZED_KERNEL 19 | % 20 | % See also WALL2UNIT, WALL2SECONDS, SECONDS2WALL, REALIZED_KERNEL, REALIZED_VARIANCE 21 | 22 | % Copyright: Kevin Sheppard 23 | % kevin.sheppard@economics.ox.ac.uk 24 | % Revision: 1 Date: 5/1/2008 25 | 26 | 27 | 28 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 29 | % Input Checking 30 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 31 | if nargin~=3 32 | error('Three inputs required.') 33 | end 34 | 35 | if size(unit,2)>size(unit,1) 36 | unit=unit'; 37 | end 38 | 39 | if size(unit,2)>1 40 | error('UNIT must be an m by 1 column vector'); 41 | end 42 | if length(unit)<2 43 | error('UNIT must contain at least 2 elements'); 44 | end 45 | 46 | unit = double(unit); 47 | wall0 = double(wall0); 48 | wall1 = double(wall1); 49 | 50 | if wall0<0 || wall0>=240000 || rem(wall0,100)>=60 || ((rem(wall0,10000)-rem(wall0,100))/100)>=60 51 | error('WALL0 must be a valid numerical time'); 52 | end 53 | 54 | if wall1<0 || wall1>=240000 || rem(wall1,100)>=60 || ((rem(wall1,10000)-rem(wall1,100))/100)>=60 55 | error('WALL1 must be a valid numerical time'); 56 | end 57 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 58 | % Input Checking 59 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 60 | 61 | 62 | wall0=wall2seconds(wall0); 63 | wall1=wall2seconds(wall1); 64 | 65 | seconds=wall0+(wall1-wall0)*unit; 66 | wall = round(100000*seconds2wall(seconds))/100000; -------------------------------------------------------------------------------- /realized/wall2seconds.m: -------------------------------------------------------------------------------- 1 | function seconds = wall2seconds(wall) 2 | % Convert wall times to seconds past midnight 3 | % 4 | % USAGE: 5 | % [SECONDS] = wall2seconds(WALL) 6 | % 7 | % INPUTS: 8 | % WALL - m by 1 column vector of wall times (e.g. 93047, 134529, etc.) 9 | % 10 | % OUTPUTS: 11 | % SECONDS - m by 1 column vector of times measured as seconds past midnight 12 | % 13 | % COMMENTS: 14 | % This is a helper function for REALIZED_KERNEL 15 | % 16 | % See also SECONDS2WALL, REALIZED_KERNEL, REALIZED_VARIANCE 17 | 18 | % Copyright: Kevin Sheppard 19 | % kevin.sheppard@economics.ox.ac.uk 20 | % Revision: 1 Date: 5/1/2008 21 | 22 | 23 | 24 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 25 | % Input Checking 26 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 27 | if nargin~=1 28 | error('One inputs required.') 29 | end 30 | if any(wall>=240000) || any(wall<0) 31 | error('WALL does not contain valid wall times. Wall times should be of the form HHMMSS (e.g. 101534).'); 32 | end 33 | % Inserted to protect against inputing integer times 34 | wall = double(wall); 35 | 36 | hr=floor(wall/10000); 37 | mm=floor(wall/100)-hr*100; 38 | ss=rem(wall,100); 39 | 40 | if any(mm>60) || any(ss>60) 41 | error('WALL does not contain valid wall times. Wall times should be of the form HHMMSS (e.g. 101534).'); 42 | end 43 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 44 | % Input Checking 45 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 46 | 47 | 48 | seconds = 3600 * hr + 60 * mm + ss; 49 | 50 | -------------------------------------------------------------------------------- /realized/wall2unit.m: -------------------------------------------------------------------------------- 1 | function unit = wall2unit(wall,wall0,wall1) 2 | % Convert wall times to unit times 3 | % 4 | % USAGE: 5 | % [UNIT] = wall2unit(WALL,WALL0,WALL1) 6 | % 7 | % INPUTS: 8 | % WALL - m by 1 column vector of wall times (e.g. 93047, 134529, etc.) 9 | % where m>=2 10 | % WALL0 - Base time, maps to 0 in the unit interval 11 | % WALL1 - End time, maps to 1 in the unit interval 12 | % 13 | % OUTPUTS: 14 | % UNIT - m by 1 column vector of times measured as fraction of time 15 | % between min(WALL) and max(WALL) 16 | % 17 | % COMMENTS: 18 | % This is a helper function for REALIZED_KERNEL 19 | % 20 | % See also WALL2SECONDS, SECONDS2WALL, REALIZED_KERNEL, REALIZED_VARIANCE 21 | 22 | % Copyright: Kevin Sheppard 23 | % kevin.sheppard@economics.ox.ac.uk 24 | % Revision: 1 Date: 5/1/2008 25 | 26 | 27 | 28 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 29 | % Input Checking 30 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 31 | if nargin~=3 32 | error('Three inputs required.') 33 | end 34 | if any(wall>=240000) || any(wall<0) 35 | error('WALL does not contain valid numerical times. Numerical times should be of the form HHMMSS (e.g. 101534).'); 36 | end 37 | 38 | if size(wall,2)>size(wall,1) 39 | wall=wall'; 40 | end 41 | 42 | if size(wall,2)>1 43 | error('WALL must be an m by 1 column vector'); 44 | end 45 | 46 | if length(wall)<2 47 | error('WALL must contain at least 2 elements'); 48 | end 49 | 50 | % Inserted to protect against inputing integer times 51 | wall = double(wall); 52 | 53 | hr=floor(wall/10000); 54 | mm=floor(wall/100)-hr*100; 55 | ss=rem(wall,100); 56 | 57 | if any(mm>60) || any(ss>60) 58 | error('WALL does not contain valid numerical times. Numerical times should be 24-hour and of the form HHMMSS (e.g. 101534, 221313).'); 59 | end 60 | 61 | if wall0<0 || wall0>=240000 || rem(wall0,100)>=60 || ((rem(wall0,10000)-rem(wall0,100))/100)>=60 62 | error('WALL0 must be a valid numerical time'); 63 | end 64 | 65 | if wall1<0 || wall1>=240000 || rem(wall1,100)>=60 || ((rem(wall1,10000)-rem(wall1,100))/100)>=60 66 | error('WALL1 must be a valid numerical time'); 67 | end 68 | 69 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 70 | % Input Checking 71 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% 72 | 73 | wall0=wall2seconds(wall0); 74 | wall1=wall2seconds(wall1); 75 | seconds = wall2seconds(wall); 76 | unit=(seconds-wall0)/(wall1 - wall0); 77 | 78 | -------------------------------------------------------------------------------- /sandbox/heavy_test.m: -------------------------------------------------------------------------------- 1 | clear all 2 | clc 3 | close all 4 | parameters = [.3 .05 .2 .4 .7 .55]; 5 | p = [0 1;0 1]; 6 | q = eye(2); 7 | m = [1 390]; 8 | T = 1000; 9 | [data,htOrig] = heavy_simulate(T,2,parameters,p,q,m); 10 | parametersOrig=parameters; 11 | data2 = data; 12 | data2(:,1) = data2(:,1).^2; 13 | backCast = mean(data2); 14 | lb = min(data2)'/10000; 15 | ub = max(data2)'*100000; 16 | %[ll,lls,h] = heavy_likelihood(parameters,data2,p,q,backCast,lb,ub); 17 | 18 | options = optimset('fminunc'); 19 | options.Display = 'iter'; 20 | 21 | sv = parameters; 22 | sv(1:2) = log(sv(1:2)); 23 | %out = fminunc(@heavy_likelihood,sv,options,data2,p,q,backCast,lb,ub); 24 | 25 | [parameters, ll, ht, VCV, scores] = heavy(data,p,q,'None'); 26 | plot([ht(:,1),htOrig(:,1)]) 27 | 28 | 29 | [parameters, ll, ht, VCV, scores] = heavy(data,p,q,'None',parametersOrig'); 30 | -------------------------------------------------------------------------------- /sandbox/sarima.m: -------------------------------------------------------------------------------- 1 | function sarima(y,c,p,q,d,seasonal,x,startingVals,options,holdBack,sigma2) 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sandbox/sarimax_errors.m: -------------------------------------------------------------------------------- 1 | function e = sarimax_errors(parameters,p,q,constant,seasonal,y,x,sigma) 2 | % PURPOSE: 3 | % Likelihood function for armaxfilter 4 | % 5 | % USAGE: 6 | % [LLF, LIKELIHOODS, ERRORS] = armaxfilter_likelihood(PARAMETERS,P,Q,CONSTANT,Y,X,M) 7 | % [LLF, LIKELIHOODS, ERRORS] = armaxfilter_likelihood(PARAMETERS,P,Q,CONSTANT,Y,X,M) 8 | % 9 | % INPUTS: 10 | % PARAMETERS - A vector of GARCH process aprams of the form [constant, arch, garch] 11 | % P - Vector containing lag indices of the AR component 12 | % Q - Vector containing lag indices of the MA component 13 | % CONSTANT - Value indicating whether the model contains a constant (1) or not (0) 14 | % Y - 15 | % X - 16 | % M - Index to first element to use in the recursive residual calculation 17 | % SIGMA - T by 1 vector 18 | % 19 | % OUTPUTS: 20 | % LLF - Minus 1 times the log likelihood 21 | % LIKELIHOODS - Time series of likelihoods 22 | % ERRORS - Time series of model errors 23 | % 24 | % COMMENTS: 25 | % 26 | % See also armaerrors 27 | 28 | % Author: Kevin Sheppard 29 | % kevin.sheppard@economics.ox.ac.uk 30 | % Revision: 3 Date: 4/1/2004 31 | 32 | m = size(x,2); 33 | [armaParameters, p, q] = sarma2arma(parameters(m+1:length(parameters)), p, q, seasonal); 34 | parameters = [parameters(1:m);armaParameters]; 35 | e = armaxerrors(parameters,p,q,constant,y,x,m,sigma); 36 | -------------------------------------------------------------------------------- /sandbox/sarimax_likelihood.m: -------------------------------------------------------------------------------- 1 | function [LLF, likelihoods, errors] = sarimax_likelihood(parameters,p,q,constant,seasonal,y,x,sigma) 2 | % PURPOSE: 3 | % Likelihood function for armaxfilter 4 | % 5 | % USAGE: 6 | % [LLF, LIKELIHOODS, ERRORS] = armaxfilter_likelihood(PARAMETERS,P,Q,CONSTANT,Y,X,M) 7 | % [LLF, LIKELIHOODS, ERRORS] = armaxfilter_likelihood(PARAMETERS,P,Q,CONSTANT,Y,X,M) 8 | % 9 | % INPUTS: 10 | % PARAMETERS - A vector of GARCH process aprams of the form [constant, arch, garch] 11 | % P - Vector containing lag indices of the AR component 12 | % Q - Vector containing lag indices of the MA component 13 | % CONSTANT - Value indicating whether the model contains a constant (1) or not (0) 14 | % Y - 15 | % X - 16 | % M - Index to first element to use in the recursive residual calculation 17 | % SIGMA - T by 1 vector 18 | % 19 | % OUTPUTS: 20 | % LLF - Minus 1 times the log likelihood 21 | % LIKELIHOODS - Time series of likelihoods 22 | % ERRORS - Time series of model errors 23 | % 24 | % COMMENTS: 25 | % 26 | % See also armaerrors 27 | 28 | % Author: Kevin Sheppard 29 | % kevin.sheppard@economics.ox.ac.uk 30 | % Revision: 3 Date: 4/1/2004 31 | 32 | m = size(x,2); 33 | [armaParameters, p, q] = sarma2arma(parameters(m+1:length(parameters)), p, q, seasonal); 34 | parameters = [parameters(1:m);armaParameters]; 35 | 36 | e = armaxerrors(parameters,p,q,constant,y,x,m,ones(size(y))); 37 | T = length(e); 38 | 39 | % Do not divide e by sigma since this is done in armaxerrors 40 | likelihoods = 0.5*(2*log(sigma) + (e./sigma).^2 + log(2*pi)); 41 | 42 | if isempty(p) 43 | p = 0; 44 | end 45 | if isempty(q) 46 | q = 0; 47 | end 48 | if max(q)>max(p) % prepend y and x, if needed 49 | t = (max(q)-max(p))+1:T; 50 | else 51 | t = 1:T; 52 | end 53 | 54 | likelihoods = likelihoods(t); 55 | errors=e(t); 56 | LLF = sum(likelihoods); 57 | 58 | if isnan(LLF) 59 | LLF=1e7; 60 | end 61 | -------------------------------------------------------------------------------- /sandbox/sarma2arma.m: -------------------------------------------------------------------------------- 1 | function [parameters, arP, maQ] = sarma2arma(parameters, p, q, seasonal) 2 | % Parameter order: c, p, Sp(1),Sp(2),...,Sp(K),q, Sq(1),Sq(2),...,Sq(K) 3 | 4 | Sp = seasonal(:,1); 5 | Sq = seasonal(:,3); 6 | S = seasonal(:,4); 7 | 8 | arParamters = parameters(1:length(p)+sum(Sp)); 9 | [arParameters,arP]=convertSARtoAR(arParamters, p, Sp, S); 10 | maParamters = parameters(length(p)+sum(Sp)+1:length(p)+sum(Sp)+length(q)+sum(Sq)); 11 | [maParameters,maQ]=convertSARtoAR(maParamters, q, Sq, S); 12 | parameters = [arParameters maParameters]'; 13 | 14 | function [parameters, lags]=convertSARtoAR(parameters,p,Sp,S) 15 | offset = 0; 16 | if isempty(p) 17 | poly = 1; 18 | else 19 | lagPoly = zeros(1,max(p)+1); 20 | lagPoly(1) = 1; 21 | lagPoly(p+1) = -parameters(offset+1:offset+length(p)); 22 | offset = offset + length(p); 23 | poly = lagPoly; 24 | end 25 | for i=1:length(S) 26 | p = Sp(i); 27 | sLag = S(i); 28 | if p>0 29 | lagPoly = zeros(1,1+sLag*p); 30 | lagPoly(1) = 1; 31 | lagPoly(sLag+1:sLag:(sLag*p+1)) = -parameters(offset+1:offset+p); 32 | offset = offset + p; 33 | poly = conv(poly, lagPoly); 34 | end 35 | end 36 | poly = poly(2:length(poly)); 37 | lags = find(poly~=0); 38 | parameters = -poly(lags); 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /sandbox/sdiff.m: -------------------------------------------------------------------------------- 1 | function [y,lags,scales] = sdiff(x, d, S) 2 | 3 | poly = 1; 4 | for i=1:length(d) 5 | for j=1:d(i) 6 | poly = conv(poly,[1 zeros(1,S(i)-1) -1]); 7 | end 8 | end 9 | lags = find(poly~=0); 10 | n = length(lags); 11 | lags = lags(2:n); 12 | scales = poly(lags); 13 | lags = lags - 1; 14 | y = []; 15 | 16 | if ~isempty(x) 17 | ml = max(lags); 18 | T = length(x); 19 | if (ml+1)<=T 20 | y = x(ml+1:T); 21 | for j=2:length(lags) 22 | y = y + scales(j) * x(ml+1-lags(j):T-lags(j)); 23 | end 24 | end 25 | end -------------------------------------------------------------------------------- /tests/jarquebera.m: -------------------------------------------------------------------------------- 1 | function [statistic,pval,H] = jarquebera(data, K, alpha) 2 | % Computes the Jarque-Bera test for normality using the skewness and kurtosis to determine if a 3 | % distribution is normal. 4 | % 5 | % USAGE: 6 | % [STATISTIC] = jarquebera(DATA) 7 | % [STATISTIC,PVAL,H] = jarquebera(DATA,K,ALPHA) 8 | % 9 | % INPUTS: 10 | % DATA - A set of data to be tested for deviations from normality 11 | % K - [OPTIONAL] The number of dependant variables if any used in constructing the errors 12 | % (if omitted K=2) 13 | % ALPHA - [OPTIONAL] The level of the test used for the null of normality. Default is .05 14 | % 15 | % OUTPUTS: 16 | % STATISTIC - A scalar representing the statistic 17 | % PVAL - A scalar pval of the null 18 | % H - A hypothesis dummy (0 for fail to reject the null of normality, 1 otherwise) 19 | % 20 | % COMMENTS: 21 | % The data entered can be mean 0 or not. In either case the sample mean is subtracted and the 22 | % data are standardized by the sample standard deviation before computing the statistic . 23 | % 24 | % EXAMPLES: 25 | % J-B test on normal data 26 | % x = randn(100,1); 27 | % [statistic, pval] = jarquebera(x); 28 | % J-B test on regression errors where there were 4 regressors (4 mean parameters + 1 variance) 29 | % x = randn(100,1); 30 | % [statistic, pval] = jarquebera(x, 5) 31 | 32 | 33 | % Author: Kevin Sheppard 34 | % kevin.sheppard@economics.ox.ac.uk 35 | % Revision: 3 Date: 2/1/2008 36 | 37 | 38 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 39 | % Input Checking 40 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 41 | switch nargin 42 | case 1 43 | K=2; 44 | alpha=.05; 45 | case 2 46 | alpha=.05; 47 | case 3 48 | otherwise 49 | error('1 to 3 input arguments required') 50 | end 51 | 52 | 53 | [T,C]=size(data); 54 | if ~any([T C]==1) 55 | error('DATA must be a vector') 56 | end 57 | 58 | if ~isscalar(alpha) || any(alpha>1) || any(alpha<0) 59 | error('ALPHA must be a scalar value between 1 and 0') 60 | end 61 | 62 | 63 | if ~isscalar(K) || any(K<0) || K~=floor(K) 64 | error('K must be an integer scalar value greater than or equal to 0.') 65 | end 66 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 67 | % Input Checking 68 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 69 | z = data - mean(data); 70 | z = z/std(z); 71 | statistic = (T-K)*(mean(z.^3)^2/6+(mean(z.^4)-3)^2/24); 72 | pval = 1-chi2cdf(statistic,2); 73 | H= pval < alpha; -------------------------------------------------------------------------------- /tests/ljungbox.m: -------------------------------------------------------------------------------- 1 | function [q, pval] = ljungbox(data, lags) 2 | % Ljung-Box tests for the presence of serial correlation in up to q lags. Returns LAGS Ljung-Box 3 | % statistics tests, one for tests for each lag between 1 and LAGS. Under the null of no serial 4 | % correlation and assuming homoskedasticity, the Ljung-Box test statistic is asymptotically 5 | % distributed X2(q) 6 | % 7 | % USAGE: 8 | % [Q,PVAL] = ljungbox(DATA,LAGS) 9 | % 10 | % INPUTS: 11 | % DATA - A T by 1 vector of data 12 | % LAGS - The maximum number of lags to compute the LB. The statistic and pval will be 13 | % returned for all sets of lags up to and including LAGS 14 | % 15 | % OUTPUTS: 16 | % Q - A LAGS by 1 vector of Q statistics 17 | % PVAL - A LAGS by 1 set of appropriate pvals 18 | % 19 | % COMMENTS: 20 | % This test statistic is common but often inappropriate since it assumes homoskedasticity. For a 21 | % heteroskedasticity consistent serial correlation test, see lmtest1 22 | % 23 | % SEE ALSO: 24 | % LMTEST1, SACF, SPACF 25 | 26 | % Copyright: Kevin Sheppard 27 | % kevin.sheppard@economics.ox.ac.uk 28 | % Revision: 3 Date: 1/1/2007 29 | 30 | 31 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 32 | % Input Checking 33 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 34 | if nargin~=2 35 | error('2 inputs required.') 36 | end 37 | T=length(data); 38 | if T<=lags 39 | error('At least LAGS observations requires') 40 | end 41 | if size(data,1)~=T, 42 | data=data'; 43 | end 44 | if size(data,2)~=1 45 | error('DATA must be a column vector') 46 | end 47 | if ~isscalar(lags) && lags>0 && floor(lags)==lags 48 | error('LAGS must be a positive integer') 49 | end 50 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 51 | % Input Checking 52 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 53 | 54 | ac = sacf(data,lags,0,0); 55 | 56 | q = zeros(lags,1); 57 | T = length(data); 58 | for L=1:lags 59 | q(L)=T*(T+2)*sum(ac(1:L).^2./(T-(1:L)')); 60 | end 61 | pval = 1 - chi2cdf(q,(1:lags)'); -------------------------------------------------------------------------------- /tests/lmtest1.m: -------------------------------------------------------------------------------- 1 | function [lm, pval] = lmtest1(data,q,robust) 2 | % LM tests for the presence of serial correlation in q lags, with or without heteroskedasticity. 3 | % Returns Q LM tests, one for tests for each lag between 1 and Q. Under the null of no serial 4 | % correlation, the LM-test is asymptotically distributed X2(q) 5 | % 6 | % USAGE: 7 | % [LM,PVAL] = lmtest1(DATA,Q) 8 | % [LM,PVAL] = lmtest1(DATA,Q,ROBUST) 9 | % 10 | % INPUTS: 11 | % DATA - A T by 1 vector of data 12 | % Q - The maximum number of lags to regress on. The statistic and pval will be returned 13 | % for all sets of lags up to and including q 14 | % ROBUST - [OPTIONAL] Logical variable (0 (non-robust) or 1 (robust)) to indicate whether 15 | % heteroskedasticity robust standard errors should be used. Default is to use robust 16 | % standard errors (ROBUST=1). 17 | % 18 | % OUTPUTS: 19 | % LM - A Qx1 vector of statistics 20 | % PVAL - A Qx1 set of appropriate pvals 21 | % 22 | % 23 | % COMMENTS: 24 | % The variance estimator is computed under the alternative (to increase the power of the test). As a 25 | % result, this test is an LR-class test. It is otherwise identical to the usual LM test for serial 26 | % correlation. 27 | % 28 | % SEE ALSO: 29 | % LJUNGBOX 30 | 31 | % Copyright: Kevin Sheppard 32 | % kevin.sheppard@economics.ox.ac.uk 33 | % Revision: 3 Date: 1/1/2007 34 | 35 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 36 | % Input Checking 37 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 38 | if nargin>3 || nargin<2 39 | error('2 or 3 inputs required.') 40 | elseif nargin==2 41 | robust = true; 42 | end 43 | T=length(data); 44 | if T0 && floor(q)==q 54 | error('Q must be a positive integer') 55 | end 56 | if nargin==3 57 | if ~ismember(robust,[0,1]) 58 | error('ROBUST must be either 0 or 1') 59 | end 60 | end 61 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 62 | % Input Checking 63 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 64 | 65 | lm=zeros(q,1); 66 | for Q=1:q 67 | data=data-mean(data); 68 | [y,x]=newlagmatrix(data,Q,0); 69 | e = y; 70 | s = x(:,1:Q).*repmat(e,1,Q); 71 | sbar = mean(s); 72 | % Transformation to LR-like test 73 | if robust 74 | s = bsxfun(@minus, s, sbar); 75 | S=s'*s/T; 76 | else 77 | e = e - mean(e); 78 | S=(e'*e/T)*(x'*x)/T; 79 | end 80 | lm(Q)=T*sbar*S^(-1)*sbar'; 81 | end 82 | pval=1-chi2cdf(lm,(1:q)'); -------------------------------------------------------------------------------- /timeseries/armaxerrors.m: -------------------------------------------------------------------------------- 1 | function errors = armaxerrors(parameters,p,q,constant,y,x,m,sigma) 2 | % PURPOSE: 3 | % Compute errors from an ARMAX model for use in a least squares optimizer 4 | % 5 | % USAGE: 6 | % [ERRORS] = armaxfilter_likelihood(PARAMETERS,P,Q,CONSTANT,Y,X,M,SIGMA) 7 | % 8 | % INPUTS: 9 | % PARAMETERS - A vector of GARCH process aprams of the form [constant, arch, garch] 10 | % P - Vector containing lag indices of the AR component 11 | % Q - Vector containing lag indices of the MA component 12 | % CONSTANT - Value indicating whether the model contains a constant (1) or not (0) 13 | % Y - Data augments with max(max(Q)-max(P),0) zeros 14 | % X - Regressors augmented with max(max(Q)-max(P),0) zeros 15 | % M - Index to first element to use in the recursive residual calculation 16 | % SIGMA - Vector of conditional standard deviations with the same dimension as Y for use in 17 | % GLS estimation 18 | % 19 | % OUTPUTS: 20 | % ERRORS - Vector of errors with the same size as Y. First M elements are 0. 21 | % 22 | % COMMENTS: 23 | % 24 | % See also ARMAXFILTER_LIKELIHOOD 25 | 26 | % Author: Kevin Sheppard 27 | % kevin.sheppard@economics.ox.ac.uk 28 | % Revision: 3 Date: 10/19/2009 29 | 30 | 31 | np = length(p); 32 | nq = length(q); 33 | T = length(y); 34 | errors = zeros(T,1); 35 | k = size(x,2); 36 | 37 | for t=m+1:T 38 | errors(t) = y(t); 39 | if constant 40 | errors(t) = errors(t) - parameters(1); 41 | end 42 | for i=1:np 43 | errors(t) = errors(t) - parameters(constant+i)*y(t-p(i)); 44 | end 45 | for i=1:k 46 | errors(t) = errors(t) - parameters(constant+np+i)*x(t,i); 47 | end 48 | for i=1:nq 49 | errors(t) = errors(t) - parameters(constant+np+k+i)*errors(t-q(i)); 50 | end 51 | errors(t) = errors(t); 52 | end 53 | errors = errors./sigma; 54 | -------------------------------------------------------------------------------- /timeseries/armaxfilter_core.m: -------------------------------------------------------------------------------- 1 | function [errors,E]=armaxfilter_core(regressand,regressors, arxparameters, maparameters, q, K, tau, maxq, maxe) 2 | % M-file version of the inner loop in conputing the forward recursion for 3 | % MA, MAX, ARMA and ARMAX estimation 4 | % 5 | % USAGE: 6 | % [E,E2]=armaxfilter_core(REGRESSAND,REGRESSORS,ARXPARAMETERS,MAPARAMETERS,Q,TAU,MAXQ,MAXE) 7 | % 8 | % INPUTS: 9 | % See armaxlikelihood 10 | % 11 | % OUTPUTS: 12 | % See armaxlikelihood 13 | % 14 | % COMMENTS: 15 | % Helper function part of UCSD_GARCH toolbox. Used if you do not use the MEX file. 16 | % You should use the MEX file. 17 | % 18 | % Author: Kevin Sheppard 19 | % kevin.sheppard@economics.ox.ac.uk 20 | % Revision: 3 Date: 1/1/2007 21 | 22 | errors=zeros(tau,1); 23 | nq = size(q,1); 24 | for t=(1+maxq):tau; 25 | errors(t)=regressand(t); 26 | for i=1:K 27 | errors(t) = errors(t) - arxparameters(i)*regressors(t,i); 28 | end 29 | for i=1:nq 30 | errors(t)= errors(t) - maparameters(i)*errors(t-q(i)); 31 | end 32 | if abs(errors(t))>(100000*maxe) 33 | errors(t)=maxe*sign(errors(t)); 34 | end 35 | end 36 | E=errors(maxq+1:tau)'*errors(maxq+1:tau); 37 | -------------------------------------------------------------------------------- /timeseries/armaxfilter_likelihood.m: -------------------------------------------------------------------------------- 1 | function [LLF, likelihoods, errors] = armaxfilter_likelihood(parameters,p,q,constant,y,x,m,sigma) 2 | % PURPOSE: 3 | % Likelihood function for armaxfilter 4 | % 5 | % USAGE: 6 | % [LLF, LIKELIHOODS, ERRORS] = armaxfilter_likelihood(PARAMETERS,P,Q,CONSTANT,Y,X,M) 7 | % [LLF, LIKELIHOODS, ERRORS] = armaxfilter_likelihood(PARAMETERS,P,Q,CONSTANT,Y,X,M,SIGMA) 8 | % 9 | % INPUTS: 10 | % PARAMETERS - A vector of ARMAX process params of the form [constant, AR, eXog, MA] 11 | % P - Vector containing lag indices of the AR component 12 | % Q - Vector containing lag indices of the MA component 13 | % CONSTANT - Value indicating whether the model contains a constant (1) or not (0) 14 | % Y - Dependent variable 15 | % X - Regressors, excluding the constant 16 | % M - Index to first element to use in the recursive residual calculation 17 | % SIGMA - T by 1 vector of conditional standard deviations 18 | % 19 | % OUTPUTS: 20 | % LLF - Minus 1 times the log likelihood 21 | % LIKELIHOODS - Time series of likelihoods 22 | % ERRORS - Time series of model errors 23 | % 24 | % COMMENTS: 25 | % 26 | % See also ARMAXERRORS 27 | 28 | % Author: Kevin Sheppard 29 | % kevin.sheppard@economics.ox.ac.uk 30 | % Revision: 3 Date: 4/1/2004 31 | 32 | e = armaxerrors(parameters,p,q,constant,y,x,m,ones(size(y))); 33 | T = length(e); 34 | 35 | if isempty(p) 36 | p = 0; 37 | end 38 | if isempty(q) 39 | q = 0; 40 | end 41 | if max(q)>max(p) % prepend y and x, if needed 42 | t = (max(q)-max(p))+1:T; 43 | else 44 | t = 1:T; 45 | end 46 | 47 | stde = e./sigma; 48 | sigma2 = stde(t)'*stde(t)/length(t); 49 | 50 | % Do not divide e by sigma since this is done in armaxerrors 51 | likelihoods = 0.5*(2*log(sigma) + log(sigma2) + stde.^2./sigma2 + log(2*pi)); 52 | 53 | likelihoods = likelihoods(t); 54 | errors=e(t); 55 | LLF = sum(likelihoods); 56 | 57 | if isnan(LLF) 58 | LLF=1e7; 59 | end 60 | -------------------------------------------------------------------------------- /timeseries/augdf_cvsim_tieup.m: -------------------------------------------------------------------------------- 1 | clear all 2 | load augdfcv1 3 | clear tstats_case2 tstats_case4 4 | temp=tstats_case1; 5 | clear tstats_case1 6 | load augdfcv2 7 | clear tstats_case2 tstats_case4 8 | tstats_case1=[temp;tstats_case1]; 9 | clear temp 10 | tstats_case1 = sort(tstats_case1); 11 | Cvs=[.001 .005 .01:.01:.99 .995 .999]; 12 | augdf_case1_cv=tstats_case1(floor(Cvs*(2*B)),:); 13 | clear tstats_case1 14 | save augdf_case1_cv augdf_case1_cv Cvs Ts 15 | 16 | 17 | 18 | clear all 19 | load augdfcv1 20 | clear tstats_case1 tstats_case4 21 | temp=tstats_case2; 22 | clear tstats_case2 23 | load augdfcv2 24 | clear tstats_case1 tstats_case4 25 | tstats_case2=[temp;tstats_case2]; 26 | clear temp 27 | tstats_case2 =sort(tstats_case2); 28 | Cvs=[.001 .005 .01:.01:.99 .995 .999]; 29 | augdf_case2_cv=tstats_case2(floor(Cvs*2*B),:); 30 | clear tstats_case2 31 | save augdf_case2_cv augdf_case2_cv Cvs Ts 32 | 33 | 34 | 35 | clear all 36 | load augdfcv1 37 | clear tstats_case1 tstats_case2 38 | temp=tstats_case4; 39 | clear tstats_case4 40 | load augdfcv2 41 | clear tstats_case1 tstats_case2 42 | tstats_case4=[temp;tstats_case4]; 43 | clear temp 44 | tstats_case4 =sort(tstats_case4); 45 | Cvs=[.001 .005 .01:.01:.99 .995 .999]; 46 | augdf_case4_cv=tstats_case4(floor(Cvs*2*B),:); 47 | clear tstats_case4 48 | save augdf_case4_cv augdf_case4_cv Cvs Ts 49 | 50 | -------------------------------------------------------------------------------- /timeseries/convert_ma_roots.m: -------------------------------------------------------------------------------- 1 | function parameters = convert_ma_roots(parameters, q) 2 | % Checks an MA parameterization for invertability and inverts it if possible 3 | % 4 | % 5 | % 6 | % COMMENTS: 7 | % It is not always possible to invert irregular MAs since the indices of the non-zero coefficients 8 | % in the invertable MA may differ. If this is the case PARAMETERS will be equal to the input. 9 | 10 | MAparameters = zeros(1,max(q)); 11 | MAparameters(q) = parameters; 12 | lambda = roots([1 MAparameters]); 13 | lambda(abs(lambda)>1) = 1./lambda(abs(lambda)>1); 14 | parameters = poly(lambda); 15 | parameters(abs(parameters)<1e-10) = 0; 16 | 17 | if length(q)1e-10); 20 | newq = newq(2:length(newq))-1; 21 | if length(q)~=length(newq) || any(q~=newq) 22 | warning('MFEToolbox:Invertability',['The irregular MA cannot be inverted without changing the lag indices. \nThe require lag indices are:' num2str(newq)]) 23 | parameters = MAparameters(q); 24 | else 25 | parameters = parameters(q+1); 26 | end 27 | else 28 | parameters = parameters(q+1); 29 | end 30 | 31 | if size(parameters,2)>size(parameters,1) 32 | parameters = parameters'; 33 | end -------------------------------------------------------------------------------- /timeseries/hp_filter.m: -------------------------------------------------------------------------------- 1 | function [trend,cyclic] = hp_filter(y,lambda) 2 | % Hodrick-Prescott filtering of multiple time series 3 | % 4 | % USAGE: 5 | % [TREND,CYCLIC] = hp_filter(Y,LAMBDA) 6 | % 7 | % INPUTS: 8 | % Y - A T by K matrix of data to be filtered. 9 | % LAMBDA - Positive, scalar integer containing the smoothing parameter of the HP filter. 10 | % 11 | % OUTPUTS: 12 | % TREND - A T by K matrix containing the filtered trend 13 | % CYCLIC - A T by K matrix containing the filtered cyclic component 14 | % 15 | % COMMENTS: 16 | % The cyclic component is simply the original data minus the trend, CYCLIC = Y - TREND. 1600 is 17 | % the recommended value of LAMBDA for Quarterly Data while 14400 is the recommended value of LAMBDA 18 | % for monthly data. 19 | % 20 | % EXAMPLES: 21 | % Load US GDP data 22 | % load GDP 23 | % Standard HP Filter with lambda = 1600 24 | % [trend, cyclic] = hp_filter(log(GDP),1600) 25 | % 26 | % See also BKFILTER, BEVERIDGENELSON 27 | 28 | % Copyright: Kevin Sheppard 29 | % kevin.sheppard@economics.ox.ac.uk 30 | % Revision: 1 Date: 19/10/2009 31 | 32 | 33 | 34 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 35 | % Input Checking 36 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 37 | if ndims(y)>2 || size(y,1)<1 38 | error('Y must be a T by K matrix with T>=4'); 39 | end 40 | if ~isscalar(lambda) || lambda<0 41 | error('LAMBDA must be a positive scalar.'); 42 | end 43 | lambdaUpperBound = 1e10; 44 | if lambda>lambdaUpperBound 45 | warning('MFEToolbox:Stability',['HP_FILTER may not be accurate for very large values of LAMBDA. Values above ' num2str(lambdaUpperBound) ' force a pure linear trend.']) 46 | end 47 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 48 | % Input Checking 49 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 50 | 51 | T=size(y,1); 52 | if lambda 73 | end 74 | rowOneWeights = [1+lambda -2*lambda lambda]; 75 | rowTwoWeights = [-2*lambda 1+5*lambda -4*lambda lambda]; 76 | Gamma(1,1:3) = rowOneWeights; 77 | Gamma(2,1:4) = rowTwoWeights; 78 | Gamma(T,T-2:T) = fliplr(rowOneWeights); 79 | Gamma(T-1,T-3:T) = fliplr(rowTwoWeights); 80 | end 81 | trend = Gamma\y; 82 | cyclic = y-trend; 83 | else 84 | x = [ones(T,1) (1:T)']; 85 | trend = x*(x\y); 86 | cyclic = y - trend; 87 | end 88 | -------------------------------------------------------------------------------- /timeseries/inverse_ar_roots.m: -------------------------------------------------------------------------------- 1 | function [rho, stationary]=inverse_ar_roots(phi) 2 | % Computes the inverted roots of the characteristic equation of an AR(P) 3 | % 4 | % USAGE: 5 | % [RHO, STATIONARY] = inverse_ar_roots(PARAMETERS) 6 | % 7 | % INPUTS: 8 | % PARAMETERS - A column vector containing the AR parameters in the order 9 | % y(t) = mu + phi(1) y(t-1) + phi(2)y(t-2) + ... + phi(P) y(t-P) + e(t) 10 | % 11 | % OUTPUTS: 12 | % RHO - A max(P) by 1 vector containing the inverted roots of the characteristic equation 13 | % corresponding to the AR model input 14 | % STATIONARY - Logical indicating whether the AR process is stationary 15 | % 16 | % COMMENTS: 17 | % Process is stationary if min(abs(rho)) > 1 18 | % 19 | % See also ARMAROOTS, ACF 20 | 21 | % Copyright: Kevin Sheppard 22 | % kevin.sheppard@economics.ox.ac.uk 23 | % Revision: 3 Date: 1/1/2007 24 | 25 | %Make sure phi is a row vector; 26 | 27 | p=length(phi); 28 | %Make sure phi is a row vector 29 | if size(phi,1)>=size(phi,2) && min(size(phi))==1 30 | phi=phi'; 31 | else 32 | error('Phi should be a column vector.') 33 | end 34 | rho=roots([-fliplr(phi) 1]); 35 | stationary=min(abs(rho))>1; -------------------------------------------------------------------------------- /timeseries/pacf.m: -------------------------------------------------------------------------------- 1 | function [pautocorr] = pacf(phi,theta,N) 2 | % Computes the theoretical partial autocorrelations an ARMA(p,q) process 3 | % 4 | % USAGE: 5 | % [PAUTOCORR] = pacf(PHI,THETA,N) 6 | % 7 | % INPUTS: 8 | % PHI - Autoregressive parameters, in the order t-1,t-2,... 9 | % THETA - Moving average parameters, in the order t-1,t-2,... 10 | % N - Number of autocorrelations to be computed 11 | % 12 | % OUTPUTS: 13 | % PAUTOCORR - N+1 by 1 vector of partial autocorrelations. 14 | % 15 | % COMMENTS: 16 | % Note: The ARMA model is parameterized: 17 | % y(t)= phi(1)y(t-1) + phi(2)y(t-2) + ... + phi(p)y(t-p) 18 | % +theta(1)e(t-1) + theta(2)e(t-2) + ... + theta(q)e(t-q) + e(t) 19 | % 20 | % To compute the autocorrelations for an ARMA that does not include all lags 1 to P, insert 0 for 21 | % any excluded lag. For example, if the model was y(t) = phi(2)y(t-1) + e(t), PHI = [0 phi(2)] 22 | 23 | % Copyright: Kevin Sheppard 24 | % kevin.sheppard@economics.ox.ac.uk 25 | % Revision: 3 Date: 1/1/2007 26 | 27 | 28 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 29 | % Input Checking 30 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 31 | if nargin~=3 32 | error('3 inputs required.') 33 | end 34 | if ~isscalar(N) && N>0 && floor(N)==N 35 | error('N must be a positive integer') 36 | end 37 | p=length(phi); 38 | if min(size(phi))>1 39 | error('phi must be a vector'); 40 | end 41 | if size(phi,1)~=p 42 | phi=phi'; 43 | end 44 | q=length(theta); 45 | if min(size(theta))>1 46 | error('theta must be a vector'); 47 | end 48 | if size(theta,1)~=q 49 | theta=theta'; 50 | end 51 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 52 | % Input Checking 53 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 54 | 55 | 56 | ac = acf(phi,theta,N+1); 57 | ac = ac(2:N+1); 58 | 59 | N=N; 60 | pac = zeros(N,1); 61 | % Begin the recursion by computing the first partial autocorrelation, which 62 | % is simply the first autocorrelation 63 | pac(1) = ac(1); 64 | % This code uses a partitioned inverse to compute the PACF 65 | if N>=2 66 | % The the second, here we will use regression formulas 67 | XpX = toeplitz([1 ac(1)]); 68 | XpXinv = XpX^(-1); 69 | Xpy = ac(1:2); 70 | temp = XpXinv * Xpy; 71 | pac(2) = temp(2); 72 | % Now to compute the remaining using the partitioned inverse 73 | for i=3:N 74 | Ainv = XpXinv; 75 | B = ac(i-1:-1:1); 76 | C = B'; 77 | D = 1; 78 | SDinv = Ainv + Ainv*B*(D-C*Ainv*B)^(-1)*C*Ainv; 79 | 80 | XpXinv = [SDinv -SDinv*B*D^(-1); 81 | -D^(-1)*C*SDinv D^(-1)+D^(-1)*C*SDinv*B*D^(-1)]; 82 | XpXinv = (XpXinv+XpXinv')/2; 83 | Xpy = ac(1:i); 84 | temp = XpXinv * Xpy; 85 | pac(i) = temp(i); 86 | end 87 | end 88 | 89 | pautocorr = [ 1;pac]; 90 | pautocorr(abs(pautocorr)<100*eps)=0; -------------------------------------------------------------------------------- /timeseries/vectorarvcv.m: -------------------------------------------------------------------------------- 1 | function VCV = vectorarvcv(X,errors,het,uncorr) 2 | % Estimate the variance-covariance matrix for parameters estimated using vectorar under one of these 3 | % conditions 4 | % * Conditionally Homoskedastic and Uncorrelated 5 | % * Conditionally Homoskedastic but Correlated 6 | % * Heteroskedastic but Conditionally Uncorrelated 7 | % * Heteroskedastic and Correlated 8 | % 9 | % USAGE: 10 | % [VCV] = vectorarvar(X,ERRORS,HET,UNCORR) 11 | % 12 | % INPUTS: 13 | % X - A T by # parameters matrix of regressors for each Y 14 | % ERRORS - K by T vector of errors 15 | % HET - A scalar integer indicating the type of covariance estimator 16 | % 0 - Homoskedastic 17 | % 1 - Heteroskedastic [DEFULAT] 18 | % HET - A scalar integer indicating the assumed structure of the error covariance matrix 19 | % 0 - Correlated errors [DEFULAT] 20 | % 1 - Uncorrelated errors 21 | % 22 | % OUTPUTS: 23 | % VCV - A K*((# lags) + CONSTANT) by K*((# lags) + CONSTANT) matrix of estimated parameter 24 | % covariances computed using HET and UNCORR 25 | % 26 | % COMMENTS: 27 | % Helper function for VECTORAR 28 | % 29 | % See also VECTORAR, GRANGERCAUSE 30 | 31 | % Copyright: Kevin Sheppard 32 | % kevin.sheppard@economics.ox.ac.uk 33 | % Revision: 3.0 Date: 1/1/2007 34 | 35 | 36 | T = size(X,1); 37 | s2=errors'*errors/T; 38 | Np = size(X,2); 39 | XpXi = ((X'*X)/T)^(-1); 40 | K=size(errors,2); 41 | X2=repmat(X,1,K); 42 | e2=reshape(repmat(errors,Np,1),T,K*Np); 43 | s=X2.*e2; 44 | 45 | if het==1 && uncorr==0 46 | % This is the White Cov Matrix 47 | Ainv = kron(eye(K),XpXi); 48 | B=(s'*s)/T; 49 | VCV=Ainv*B*Ainv/T; 50 | elseif het==1 && uncorr==1 51 | Ainv = kron(eye(K),XpXi); 52 | B=zeros(Np*K); 53 | for i=1:K 54 | sel=(i-1)*Np+1:i*Np; 55 | temp = s(:,sel); 56 | B(sel,sel)=temp'*temp/T; 57 | end 58 | VCV=Ainv*B*Ainv/T; 59 | elseif het==0 && uncorr==0 60 | % Homoskedastic, correlated is also fairly easy 61 | VCV=kron(s2,XpXi)/T; 62 | elseif het==0 && uncorr==1 63 | % Hom uncorrelated 64 | VCV=kron(diag(diag(s2)),XpXi)/T; 65 | end 66 | % White uncorr is also easy, since it comes from B 67 | -------------------------------------------------------------------------------- /timeseries/weights_to_frequency_response.m: -------------------------------------------------------------------------------- 1 | function fr = weights_to_frequency_response(a,w,n) 2 | % Computes the frequency response on [0,0.5] for a transformation of the form 3 | % 4 | % A'y = W'x 5 | % 6 | % where A is a K by 1 vector and W is an M by 1 vector. 7 | % 8 | % USAGE: 9 | % [fr] = weights_to_frequency_response(A,W,N) 10 | % 11 | % INPUTS: 12 | % A - K by 1 vector of output weights 13 | % W - M by 1 vector of input weights 14 | % N - Number of points to use when computing the frequency response (e.g. linspace(0,0.5,N)) 15 | % 16 | % OUTPUTS: 17 | % FR - N by 1 vector containing the gain 18 | % 19 | % COMMENTS: 20 | % 21 | % EXAMPLES: 22 | % Centered MA(3) 23 | % fr = weights_to_frequency_response([0 1 0]',[1/3 1/3 1/3]) 24 | 25 | % Copyright: Kevin Sheppard 26 | % kevin.sheppard@economics.ox.ac.uk 27 | % Revision: 4 Date: 11/1/2009 28 | 29 | if nargin==2 30 | n = 100; 31 | end 32 | 33 | f = linspace(0,0.5,n); 34 | if size(w,2)>size(w,1) 35 | w=w'; 36 | end 37 | if size(a,2)>size(a,1) 38 | a=a'; 39 | end 40 | m = length(w); 41 | k = length(a); 42 | fr = zeros(size(f)); 43 | for j=1:length(f) 44 | fr(j) = (w'*exp(-1i*(1:m)'*2*pi*f(j)))/(a'*exp(-1i*(1:k)'*2*pi*f(j))); 45 | end 46 | fr = abs(fr); 47 | -------------------------------------------------------------------------------- /univariate/agarch_core.m: -------------------------------------------------------------------------------- 1 | function ht=agarch_core(data,parameters,back_cast,p,q,m,T,model_type) 2 | % Conditional variance computation for a AGARCH(P,Q) process. 3 | % 4 | % USAGE: 5 | % [HT] = agarch_core(DATA,PARAMETERS,BACK_CAST,P,Q,M,T,MODEL_TYPE) 6 | % 7 | % INPUTS: 8 | % DATA - A column of mean zero data audmented with M backcasts 9 | % PARAMETERS - 2+P+Q by 1 vector of parameters 10 | % BACK_CAST - Value to be used for initializing the recursion 11 | % P - Positive, scalar integer representing the number of 12 | % symmetric innovations 13 | % Q - Non-negative, scalar integer representing the number 14 | % of lags of conditional variance (0 for ARCH) 15 | % M - Number of backcasts needed 16 | % T - Length of DATA, including any appended back casts 17 | % MODEL_TYPE - The type of variance process, either 18 | % 1 - AGARCH 19 | % 2 - NAGARCH 20 | % 21 | % OUTPUTS: 22 | % HT - Vector of conditonal varainces, T by 1 23 | % 24 | % COMMENTS: 25 | % The conditional variance, h(t), of a AGARCH(P,Q) process is given by: 26 | % 27 | % h(t) = omega 28 | % + alpha(1)*(r_{t-1}-gamma)^2 + ... + alpha(p)*(r_{t-p}-gamma)^2 29 | % + beta(1)*h(t-1) +...+ beta(q)*h(t-q) 30 | % 31 | % The conditional variance, h(t), of a NAGARCH(P,Q) process is given by: 32 | % 33 | % h(t) = omega 34 | % + alpha(1)*(r_{t-1}-gamma*sqrt(h(t-1)))^2 + ... + alpha(p)*(r_{t-p}-gamma*sqrt(h(t-p)))^2 35 | % + beta(1)*h(t-1) +...+ beta(q)*h(t-q) 36 | % 37 | % See also AGARCH 38 | % 39 | % You should use the MEX files (or compile if not using Win32 Matlab) 40 | % as they provide speed ups of approx 10 times relative to the m file 41 | 42 | % Copyright: Kevin Sheppard 43 | % kevin.sheppard@economics.ox.ac.uk 44 | % Revision: 1 Date: 7/12/2009 45 | 46 | 47 | %Initialize ht 48 | ht=zeros(size(data)); 49 | %Set the back casts 50 | ht(1:m)=back_cast; 51 | gamma = parameters(2+p); 52 | shock = zeros(m,1); 53 | 54 | if model_type == 1 55 | for i = 1:m 56 | shock(i) = back_cast + gamma^2; 57 | end 58 | for i=m+1:T 59 | ht(i) = parameters(1); 60 | for j=1:p 61 | ht(i) = ht(i) + parameters(j+1)*shock(i-j); 62 | end 63 | for j=1:q 64 | ht(i) = ht(i)+ parameters(j+2+p)*ht(i-j); 65 | end 66 | shock(i) = (data(i)-gamma)^2; 67 | end 68 | else 69 | for i = 1:m 70 | shock(i) = back_cast * (1+ gamma^2); 71 | end 72 | for i=m+1:T 73 | ht(i) = parameters(1); 74 | for j=1:p 75 | ht(i) = ht(i) + parameters(j+1)*shock(i-j); 76 | end 77 | for j=1:q 78 | ht(i) = ht(i)+ parameters(j+2+p)*ht(i-j); 79 | end 80 | shock(i) = (data(i)-gamma*sqrt(ht(i)))^2; 81 | end 82 | end 83 | -------------------------------------------------------------------------------- /univariate/aparch_core.m: -------------------------------------------------------------------------------- 1 | function ht=aparch_core(data_aug,abs_data_aug,parameters,p,o,q,m,T,back_cast,LB,UB) 2 | % Conditional variance computation for a APARCH(P,O,Q) process. 3 | % 4 | % USAGE: 5 | % [HT] = aparch_core(DATA_AUG,ABS_DATA_AUG,PARAMETERS,P,O,Q,M,T) 6 | % 7 | % INPUTS: 8 | % DATA_AUG - Vector of mean zero residuals augmented with zeros 9 | % ABS_DATA_AUG - Absolute value of augmented data 10 | % PARAMETERS - 1+P+O+Q by 1 vector of parameters 11 | % P - Positive, scalar integer representing the number of 12 | % symmetric innovations 13 | % O - Non-negative scalar integer representing the number 14 | % of asymmetric innovations (0 for symmetric processes) 15 | % Q - Non-negative, scalar integer representing the number 16 | % of lags of conditional variance (0 for ARCH) 17 | % M - Number of back casts needed 18 | % T - Length of FDATA, including any appended back casts 19 | % 20 | % OUTPUTS: 21 | % HT - Vector of conditonal varainces, T by 1 22 | % 23 | % COMMENTS: 24 | % The conditional variance, h(t), of a APARCH(P,O,Q) process is modeled 25 | % as follows: 26 | % 27 | % 28 | % See also APARCH 29 | % 30 | % You should use the MEX files (or compile if not using Win32 Matlab) 31 | % as they provide speed ups of approx 10 times relative to the m file 32 | 33 | % Copyright: Kevin Sheppard 34 | % kevin.sheppard@economics.ox.ac.uk 35 | % Revision: 3 Date: 9/1/2005 36 | 37 | %Initialize ht 38 | htdelta=zeros(size(data_aug)); 39 | ht=zeros(size(data_aug)); 40 | delta = parameters(1+p+o+q+1); 41 | 42 | %Set the back casts 43 | htdelta(1:m)=back_cast; 44 | ht(1:m)=data_aug(m+1:T)'*data_aug(m+1:T)/(T-m); 45 | %Recursion Loop 46 | deltainv=2/delta; 47 | 48 | omega = parameters(1); 49 | alpha = parameters(2:p+1); 50 | gamma = parameters(p+2:p+o+1); 51 | beta = parameters(p+o+2:p+o+q+1); 52 | for i=m+1:T 53 | htdelta(i) = omega; 54 | for j=1:p 55 | if o>=j 56 | htdelta(i) = htdelta(i) + alpha(j)*(abs_data_aug(i-j)+gamma(j)*data_aug(i-j))^delta; 57 | else 58 | htdelta(i) = htdelta(i) + alpha(j)*(abs_data_aug(i-j))^delta; 59 | end 60 | end 61 | for j=1:q 62 | htdelta(i) = htdelta(i) + beta(j)*htdelta(i-j); 63 | end 64 | % Check that HT is between its LB and UB 65 | htTemp = htdelta(i)^deltainv; 66 | if htTempUB 70 | htdelta(i)=UB^delta; 71 | htTemp = htdelta(i)^deltainv; 72 | end 73 | ht(i)=htTemp; 74 | end -------------------------------------------------------------------------------- /univariate/aparch_loglikelihood.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashtage/mfe-toolbox/9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/univariate/aparch_loglikelihood.m -------------------------------------------------------------------------------- /univariate/egarch_core.m: -------------------------------------------------------------------------------- 1 | function ht=egarch_core(data,parameters,back_cast,upper,p,o,q,m,T) 2 | % Conditional variance computation for a EGARCH(P,O,Q) process. 3 | % 4 | % USAGE: 5 | % [HT] = egarch_core(DATA,PARAMETERS,BACK_CAST,UPPER,P,O,Q,M,T) 6 | % 7 | % INPUTS: 8 | % DATA - A column of mean zero data 9 | % PARAMETERS - 1+P+O+Q by 1 vector of parameters 10 | % BACK_CAST - Value to be used for initializing the recursion 11 | % UPPER - Upper bound for ht, larger values will be set to this 12 | % P - Positive, scalar integer representing the number of 13 | % symmetric innovations 14 | % O - Non-negative scalar integer representing the number 15 | % of asymmetric innovations (0 for symmetric processes) 16 | % Q - Non-negative, scalar integer representing the number 17 | % of lags of conditional variance (0 for ARCH) 18 | % M - Number of back casts needed 19 | % T - Length of FDATA, including any appended back casts 20 | % 21 | % OUTPUTS: 22 | % HT - Vector of conditonal varainces, T by 1 23 | % 24 | % COMMENTS: 25 | % The conditional variance, h(t), of an EGARCH(P,O,Q) process is modeled 26 | % as follows: 27 | % 28 | % ln(h(t)) = omega 29 | % + alpha(1)*(abs(e_{t-1})-C) + ... + alpha(p)*(abs(e_{t-p})-C)+... 30 | % + gamma(1)*e_{t-1} +...+ e_{t-o} +... 31 | % beta(1)*ln(h(t-1)) +...+ beta(q)*ln(h(t-q)) 32 | % 33 | % See also EGARCH 34 | % 35 | % You should use the MEX files (or compile if not using Win32 Matlab) 36 | % as they provide speed ups of approx 100 times relative to the m file 37 | 38 | % Copyright: Kevin Sheppard 39 | % kevin.sheppard@economics.ox.ac.uk 40 | % Revision: 3 Date: 9/1/2005 41 | 42 | 43 | 44 | ht=zeros(size(data)); 45 | eht=zeros(size(data)); 46 | ht(1:m)=back_cast; 47 | eht(1:m)=exp(back_cast); 48 | data2=data; 49 | absdata2=data; 50 | subconst=0.797884560802865; 51 | for i=1:m; 52 | vol=sqrt(eht(i)); 53 | data2(i)=data(i)/vol; 54 | absdata2(i)=abs(data2(i))-subconst; 55 | end 56 | 57 | eLB=eht(1)/10000; 58 | hLB=ht(1)-log(10000); 59 | 60 | for i=m+1:T 61 | ht(i) = parameters(1); 62 | for j=1:p 63 | ht(i) = ht(i) + parameters(j+1)*absdata2(i-j); 64 | end 65 | for j=1:o 66 | ht(i) = ht(i) + parameters(j+p+1)*data2(i-j) ; 67 | end 68 | for j=1:q 69 | ht(i) = ht(i) + parameters(j+p+o+1)*ht(i-j) ; 70 | end 71 | %ht(i) = parameters'*[1 ; absdata2(i-1:-1:i-p) ; data2(i-1:-1:i-o) ; ht(i-1:-1:i-q)]; 72 | eht(i)=exp(ht(i)); 73 | if eht(i)< eLB; 74 | eht(i) = eLB; 75 | ht(i) = hLB; 76 | end 77 | if eht(i)>upper; 78 | if ~isinf(eht(i)) 79 | eht(i)= upper+ht(i); 80 | else 81 | eht(i)=upper+800; 82 | end 83 | %Keep ht(i) from diverging 84 | ht(i) = log(eht(i)) ; 85 | end 86 | vol=sqrt(eht(i)); 87 | data2(i)=data(i)/vol; 88 | absdata2(i)=abs(data2(i))-subconst; 89 | end 90 | ht=eht; -------------------------------------------------------------------------------- /univariate/egarch_itransform.m: -------------------------------------------------------------------------------- 1 | function parameters=egarch_itransform(parameters,p,o,q,error_type) 2 | % EGARCH(P,O,Q) parameter transformation. Used to map parameters from a EGARCH 3 | % process to the real line. Used in the estimation of EGARCH. 4 | % 5 | % USAGE: 6 | % [PARAMETERS]=egarch_itransform(PARAMETERS,P,O,Q,ERROR_TYPE) 7 | % 8 | % INPUTS: 9 | % PARAMETERS - Column parameter vector 10 | % P - Positive, scalar integer representing the number of 11 | % symmetric innovations 12 | % O - Non-negative scalar integer representing the number 13 | % of asymmetric innovations (0 for symmetric processes) 14 | % Q - Non-negative, scalar integer representing the number 15 | % of lags of conditional variance (0 for ARCH) 16 | % ERROR_TYPE - One of: 17 | % 1 - Gaussian Innovations 18 | % 2 - T-distributed errors 19 | % 3 - Generalized Error Distribution 20 | % 4 - Skewed T distribution 21 | % 22 | % OUTPUTS: 23 | % PARAMETERS - A 1+p+o+q column vector of parameters corresponding to 24 | % [omega,alpha(1),...,alpha(p),gamma(1),...,gamma(o), beta1 ... beta(q) [nu lambda]]' 25 | % 26 | % COMMENTS: 27 | % Output parameters will satisfy: 28 | % (1) nu>2 of Students T and 1 2.01 35 | %if GED, 1.012.01, -.99100 45 | nu=100; 46 | end 47 | nu=exp(nu)/(1+exp(nu)); 48 | nu=49*nu+1.01; 49 | parameters(p+o+q+2)=nu; 50 | end 51 | 52 | if error_type==4 53 | lambda=parameters(p+o+q+3); 54 | lambda=exp(lambda)/(1+exp(lambda)); 55 | lambda=1.98*lambda-.99; 56 | parameters(p+o+q+3)=lambda; 57 | end 58 | -------------------------------------------------------------------------------- /univariate/egarch_nlcon.m: -------------------------------------------------------------------------------- 1 | function [c,ceq]=egarch_nlcon(parameters, data, p, o, q, error_type, back_cast, T, estim_flag) 2 | % EGARCH(P,O,Q) nonlinear parameter restriction. Used in estimation of 3 | % EGARCH models. 4 | % 5 | % USAGE: 6 | % [C,CEQ]=egarch_nlcon(PARAMETERS,DATA,P,O,Q,ERROR_TYPE,BACK_CAST,T,ESTIM_FLAG) 7 | % 8 | % INPUTS: 9 | % See EGARCH_LIKELIHOOD 10 | % 11 | % OUTPUTS: 12 | % C - Vector of nonlinear inequality constraints. Based on the roots 13 | % of a polynomial in beta 14 | % CEQ - Empty matrix 15 | % 16 | % COMMENTS: 17 | % 18 | % See also EGARCH 19 | 20 | beta=parameters(p+o+2:p+o+q+1); 21 | %zn=fliplr(-beta'); 22 | %Find any zeros 23 | %if any(abs(zn)<1e-08); 24 | % zn(abs(zn)<1e-08)=sign(zn(abs(zn)<1e-08))*1e-08; 25 | %end 26 | %r=roots([zn 1]); 27 | %c=1./abs(r)-.9998; 28 | c=abs(roots([1;-beta]))-.99998; 29 | ceq=[]; -------------------------------------------------------------------------------- /univariate/egarch_transform.m: -------------------------------------------------------------------------------- 1 | function parameters=egarch_transform(parameters,p,o,q,error_type) 2 | % EGARCH(P,O,Q) parameter transformation. Used to map parameters from a EGARCH 3 | % process to the real line. Used in the estimation of EGARCH. 4 | % 5 | % USAGE: 6 | % [TRANS_PARAMETERS,NU,LAMBDA]=egarch_transform(PARAMETERS,P,O,Q,ERROR_TYPE); 7 | % 8 | % INPUTS: 9 | % PARAMETERS - Column parameter vector 10 | % P - Positive, scalar integer representing the number of 11 | % symmetric innovations 12 | % O - Non-negative scalar integer representing the number 13 | % of asymmetric innovations (0 for symmetric processes) 14 | % Q - Non-negative, scalar integer representing the number 15 | % of lags of conditional variance (0 for ARCH) 16 | % ERROR_TYPE - One of: 17 | % 1 - Gaussian Innovations 18 | % 2 - T-distributed errors 19 | % 3 - Generalized Error Distribution 20 | % 4 - Skewed T distribution 21 | % 22 | % OUTPUTS: 23 | % TRANS_PARAMETERS - A 1+p+o+q column vector of parameters corresponding to 24 | % [omega,alpha(1),...,alpha(p),gamma(1),...,gamma(o), beta1 ... beta(q)]' 25 | % NU - Distribution kurtosis parameter, empty if not applicable 26 | % LAMBDA - Distribution asymmetry parameter, empty if not applicable 27 | % 28 | % COMMENTS: 29 | % Input parameters must satisfy: 30 | % (1) nu>2 of Students T and 12.01 in the case of a T, 1.01 0 27 | % (2) 0<= d <= 1 28 | % (3) 0 <= phi <= (1-d)/2 29 | % (3) 0 <= beta <= d + phi 30 | % (5) nu>2 of Students T and nu>1 for GED 31 | % (6) -.99100 51 | nu=100; 52 | end 53 | nu=exp(nu)/(1+exp(nu)); 54 | nu=49*nu+1.01; 55 | else 56 | nu = []; 57 | end 58 | %If skewt, use a logistic to map to -.99,.99 59 | if errorType==4 60 | lambda=parameters(p+q+4); 61 | lambda=exp(lambda)/(1+exp(lambda)); 62 | lambda=1.98*lambda-.99; 63 | else 64 | lambda = []; 65 | end 66 | 67 | 68 | 69 | 70 | 71 | % 00 74 | omega = exp(parameters(1)); 75 | % Find d 76 | if p 77 | d = parameters(3); 78 | else 79 | d = parameters(2); 80 | end 81 | % 0 0 27 | % (2) 0<= d <= 1 28 | % (3) 0 <= phi <= (1-d)/2 29 | % (3) 0 <= beta <= d + phi 30 | % (5) nu>2 of Students T and nu>1 for GED 31 | % (6) -.992.01 in the case of a T, 1.010 67 | omegaTrans = log(parameters(1)); 68 | % Find d 69 | if p 70 | d = parameters(3); 71 | else 72 | d = parameters(2); 73 | end 74 | % 00 47 | h(:,t) = h(:,t) + A(:,:,j)*data(:,t-j); 48 | else 49 | h(:,t) = h(:,t) + A(:,:,j)*backCast'; 50 | end 51 | end 52 | for j=1:qMax 53 | if (t-j)>0 54 | h(:,t) = h(:,t) + B(:,:,j)*h(:,t-j); 55 | else 56 | h(:,t) = h(:,t) + B(:,:,j)*backCast'; 57 | end 58 | end 59 | for j=1:K 60 | if h(j,t)ub(j) 63 | h(j,t) = ub(j) + log(h(j,t)-ub(j)); 64 | end 65 | end 66 | lls(t) = 0.5*(likConst + sum(log(h(:,t))) + sum(data(:,t)./h(:,t))); 67 | end 68 | ll = sum(lls); 69 | 70 | if isnan(ll) || isinf(ll) || ~isreal(ll) 71 | ll = 1e7; 72 | end 73 | 74 | if nargout>2 75 | h = h'; 76 | end -------------------------------------------------------------------------------- /univariate/heavy_parameter_transform.m: -------------------------------------------------------------------------------- 1 | function [O,A,B] = heavy_parameter_transform(parameters,p,q,K) 2 | % Parameter transformation for the HEAVY volatility model of Shephard and Sheppard. 3 | % 4 | % USAGE: 5 | % [DATA,HT] = heavy_transform(PARAMETERS,P,Q,K) 6 | % 7 | % INPUTS: 8 | % PARAMETERS - A vector with K+sum(sum(P))+sum(sum(Q)) elements. See COMMENTS. 9 | % P - A K by K matrix containing the lag length of model innovations. Position (i,j) 10 | % indicates the number of lags of series j in the model for series i 11 | % Q - A K by K matrix containing the lag length of conditional variances. Position (i,j) 12 | % indicates the number of lags of series j in the model for series i 13 | % K - Number of series to simulate 14 | % 15 | % OUTPUTS: 16 | % O - A K by 1 matrix of intercepts 17 | % A - A K by K by max(max(P)) array of innovation parameters 18 | % B - A K by K by max(max(Q)) array of smoothing parameters 19 | % 20 | % COMMENTS: 21 | % Dynamics are given by: 22 | % h(t,:)' = O + A(:,:,1)*f(data(t-1,:))' + ... + A(:,:,maxP)*f(data(t-maxP,:))' + ... 23 | % + B(:,:,1)*h(t-1,:)' + ... + B(:,:,maxQ)*h(t-maxQ,:)' 24 | % 25 | % PARAMETERS are ordered: 26 | % [O' A(1,1,1:p(1,1)) A(1,2,1:p(1,2)) ... A(1,K,1:p(1,K)) A(2,1,1:p(2,1)) ... A(2,K,1:p(2,K)) 27 | % ... A(K,1,1:p(K,1)) ... A(K,K,1:p(K,K)) ... B(1,1,1:q(1,1)) ... B(1,K,1:q(1,K)) 28 | % ... B(K,1,1:q(K,1)) ... B(K,K,1:q(K,K)) ] 29 | % 30 | % EXAMPLES: 31 | % 32 | % See also HEAVY 33 | 34 | % Copyright: Kevin Sheppard 35 | % kevin.sheppard@economics.ox.ac.uk 36 | % Revision: 1 Date: 4/2/2012 37 | 38 | 39 | O = zeros(K,1); 40 | O(:) = parameters(1:K); 41 | offset = K; 42 | A = zeros(K,K,max(max(p))); 43 | B = zeros(K,K,max(max(q))); 44 | for i=1:K 45 | for j=1:K 46 | A(i,j,1:p(i,j)) = parameters(offset+(1:p(i,j))); 47 | offset = offset + p(i,j); 48 | end 49 | end 50 | for i=1:K 51 | for j=1:K 52 | B(i,j,1:q(i,j)) = parameters(offset+(1:q(i,j))); 53 | offset = offset + q(i,j); 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /univariate/igarch_core.m: -------------------------------------------------------------------------------- 1 | function ht=igarch_core(fepsilon,parameters,backCast,p,q,m,T,igarchType,constant) 2 | % Conditional variance computation for a IGARCH(P,Q) process. 3 | % 4 | % USAGE: 5 | % [HT] = igarch_core(FEPSILON,PARAMETERS,BACKCAST,P,Q,M,T,IGARCHTYPE,CONSTANT) 6 | % 7 | % INPUTS: 8 | % FEPSILON - Either abs(EPSILON) or EPSILON.^2, depending on IGARCHTYPE 9 | % PARAMETERS - CONSTANT+P+Q by 1 vector of parameters 10 | % BACKCAST - Value to be used for initializing the recursion 11 | % P - Positive, scalar integer representing the number of 12 | % symmetric innovations 13 | % Q - Non-negative, scalar integer representing the number 14 | % of lags of conditional variance (0 for ARCH) 15 | % M - Number of back casts needed 16 | % T - Length of FDATA, including any appended back casts 17 | % IGARCHTYPE - The type of variance process, either 18 | % 1 - Model evolves in absolute values 19 | % 2 - Model evolves in squares 20 | % CONSTANT - 1 if model includes a constant, 0 otherwise. 21 | % 22 | % OUTPUTS: 23 | % HT - Vector of conditonal varainces, T by 1 24 | % 25 | % COMMENTS: 26 | % The conditional variance, h(t), of an IGARCH(P,Q) process is modeled 27 | % as follows: 28 | % 29 | % g(h(t)) = omega 30 | % + alpha(1)*f(r_{t-1}) + ... + alpha(p)*f(r_{t-p})+... 31 | % beta(1)*g(h(t-1)) +...+ beta(q)*g(h(t-q)) 32 | % 33 | % where f(x) = abs(x) if IGARCHTYPE=1 34 | % g(x) = sqrt(x) if IGARCHTYPE=1 35 | % f(x) = x^2 if IGARCHTYPE=2 36 | % g(x) = x if IGARCHTYPE=2 37 | % and 38 | % 39 | % sum(alpha)+sum(beta) = 1 40 | % 41 | % See also IGARCH 42 | % 43 | % You should use the MEX files (or compile if not using Win64 Matlab) 44 | % as they provide speed ups of approx 10 times relative to the m file 45 | 46 | % Copyright: Kevin Sheppard 47 | % kevin.sheppard@economics.ox.ac.uk 48 | % Revision: 1 Date: 7/12/2009 49 | 50 | %Initialize ht 51 | ht=zeros(size(fepsilon)); 52 | %Set the back casts 53 | ht(1:m)=backCast; 54 | % Compute final beta, needed since the number of ARCH + GARCH coefficients 55 | % is 1 less than in a usual GARCH 56 | archParameters = parameters(constant+1:constant+p+q-1); 57 | finalParameter = 1 - sum(archParameters); 58 | for i=m+1:T 59 | if constant 60 | ht(i) = parameters(1); 61 | end 62 | for j=1:p 63 | ht(i) = ht(i) + parameters(j+constant)*fepsilon(i-j); 64 | end 65 | for j=1:(q-1) 66 | ht(i) = ht(i) + parameters(j+p+constant)*ht(i-j) ; 67 | end 68 | % This line is needed since the number of ARCH + GARCH coefficients is 69 | % 1 less than in a usual GARCH 70 | ht(i) = ht(i) + finalParameter*ht(i-q) ; 71 | end 72 | 73 | %Return squared ht if the recursion was for a IGARCH/absolute value process 74 | if igarchType==1 75 | ht=ht.^2; 76 | end -------------------------------------------------------------------------------- /univariate/tarch_core.m: -------------------------------------------------------------------------------- 1 | function ht=tarch_core(fdata,fIdata,parameters,back_cast,p,o,q,m,T,tarch_type) 2 | % Conditional variance computation for a TARCH(P,O,Q) process. 3 | % 4 | % USAGE: 5 | % [HT] = tarch_core(FDATA,FIDATA,PARAMETERS,BACK_CAST,P,O,Q,M,T,TARCH_TYPE) 6 | % 7 | % INPUTS: 8 | % FDATA - A column of mean zero data transformed according to F (see COMMENTS) 9 | % FIDATA - FDATA * DATA<0 10 | % PARAMETERS - 1+P+O+Q by 1 vector of parameters 11 | % BACK_CAST - Value to be used for initializing the recursion 12 | % P - Positive, scalar integer representing the number of 13 | % symmetric innovations 14 | % O - Non-negative scalar integer representing the number 15 | % of asymmetric innovations (0 for symmetric processes) 16 | % Q - Non-negative, scalar integer representing the number 17 | % of lags of conditional variance (0 for ARCH) 18 | % M - Number of back casts needed 19 | % T - Length of FDATA, including any appended back casts 20 | % TARCH_TYPE - The type of variance process, either 21 | % 1 - Model evolves in absolute values 22 | % 2 - Model evolves in squares 23 | % 24 | % OUTPUTS: 25 | % HT - Vector of conditonal varainces, T by 1 26 | % 27 | % COMMENTS: 28 | % The conditional variance, h(t), of a TARCH(P,O,Q) process is modeled 29 | % as follows: 30 | % 31 | % g(h(t)) = omega 32 | % + alpha(1)*f(r_{t-1}) + ... + alpha(p)*f(r_{t-p})+... 33 | % + gamma(1)*I(t-1)*f(r_{t-1}) +...+ gamma(o)*I(t-o)*f(r_{t-o})+... 34 | % beta(1)*g(h(t-1)) +...+ beta(q)*g(h(t-q)) 35 | % 36 | % where f(x) = abs(x) if tarch_type=1 37 | % g(x) = sqrt(x) if tarch_type=1 38 | % f(x) = x^2 if tarch_type=2 39 | % g(x) = x if tarch_type=2 40 | % 41 | % See also TARCH 42 | % 43 | % You should use the MEX files (or compile if not using Win32 Matlab) 44 | % as they provide speed ups of approx 10 times relative to the m file 45 | 46 | % Copyright: Kevin Sheppard 47 | % kevin.sheppard@economics.ox.ac.uk 48 | % Revision: 3 Date: 9/1/2005 49 | 50 | %Initialize ht 51 | ht=zeros(size(fdata)); 52 | %Set the back casts 53 | ht(1:m)=back_cast; 54 | 55 | %Recursion Loop 56 | for i=m+1:T 57 | ht(i) = parameters(1); 58 | for j=1:p 59 | ht(i) = ht(i) + parameters(j+1)*fdata(i-j); 60 | end 61 | for j=1:o 62 | ht(i) = ht(i) + parameters(j+p+1)*fIdata(i-j) ; 63 | end 64 | for j=1:q 65 | ht(i) = ht(i) + parameters(j+p+o+1)*ht(i-j) ; 66 | end 67 | end 68 | 69 | 70 | %Return squared ht if the recursion was for a TARCH/absolute value process 71 | if tarch_type==1 72 | ht=ht.^2; 73 | end 74 | -------------------------------------------------------------------------------- /univariate/tarch_core_simple.m: -------------------------------------------------------------------------------- 1 | function ht=tarch_core_simple(data,parameters,backCast,backCastAsym,p,o,q,tarch_type) 2 | % Simple (but clow) implementation of conditional variance computation for a TARCH(P,O,Q) process. 3 | % 4 | % USAGE: 5 | % [HT] = tarch_core(DATA,PARAMETERS,BACKCAST,BACKCASTASYM,P,O,Q,TARCH_TYPE) 6 | % 7 | % INPUTS: 8 | % DATA - A column of mean zero data 9 | % PARAMETERS - 1+P+O+Q by 1 vector of parameters 10 | % BACKCAST - Value to be used for initializing the recursion 11 | % BACKCASTASYM - Value to be used for initializing the asymmetric term in the recursion 12 | % P - Positive, scalar integer representing the number of symmetric innovations 13 | % O - Non-negative scalar integer representing the number of asymmetric innovations 14 | % Q - Non-negative, scalar integer representing the number of lags of conditional variance 15 | % TARCH_TYPE - The type of variance process, either 16 | % 1 - Model evolves in absolute values 17 | % 2 - Model evolves in squares 18 | % 19 | % OUTPUTS: 20 | % HT - Vector of conditonal varainces, T by 1 21 | % 22 | % COMMENTS: 23 | % The conditional variance, h(t), of a TARCH(P,O,Q) process is modeled 24 | % as follows: 25 | % 26 | % g(h(t)) = omega 27 | % + alpha(1)*f(r_{t-1}) + ... + alpha(p)*f(r_{t-p})+... 28 | % + gamma(1)*I(t-1)*f(r_{t-1}) +...+ gamma(o)*I(t-o)*f(r_{t-o})+... 29 | % beta(1)*g(h(t-1)) +...+ beta(q)*g(h(t-q)) 30 | % 31 | % where f(x) = abs(x) if tarch_type=1 32 | % g(x) = sqrt(x) if tarch_type=1 33 | % f(x) = x^2 if tarch_type=2 34 | % g(x) = x if tarch_type=2 35 | % 36 | % See also TARCH, TARCH_CORE 37 | 38 | % Copyright: Kevin Sheppard 39 | % kevin.sheppard@economics.ox.ac.uk 40 | % Revision: 4 Date: 4/12/2012 41 | 42 | %Initialize ht 43 | T = length(data); 44 | ht = zeros(T,1); 45 | if tarch_type==1 46 | fdata = abs(data); 47 | else 48 | fdata = data.^2; 49 | end 50 | fIdata = fdata.*(data<0); 51 | 52 | %Recursion Loop 53 | for i=1:T 54 | ht(i) = parameters(1); 55 | for j=1:p 56 | if (i-j)>0 57 | ht(i) = ht(i) + parameters(j+1)*fdata(i-j); 58 | else 59 | ht(i) = ht(i) + parameters(j+1)*backCast; 60 | end 61 | end 62 | for j=1:o 63 | if (i-j)>0 64 | ht(i) = ht(i) + parameters(j+p+1)*fIdata(i-j); 65 | else 66 | ht(i) = ht(i) + parameters(j+p+1)*backCastAsym; 67 | end 68 | end 69 | for j=1:q 70 | if (i-j)>0 71 | ht(i) = ht(i) + parameters(j+p+o+1)*ht(i-j) ; 72 | else 73 | ht(i) = ht(i) + parameters(j+p+o+1)*backCast ; 74 | end 75 | end 76 | end 77 | 78 | % Return squared ht if the recursion was for a TARCH/absolute value process 79 | if tarch_type==1 80 | ht=ht.^2; 81 | end -------------------------------------------------------------------------------- /utility/c2mdate.m: -------------------------------------------------------------------------------- 1 | function mldate = c2mdate(crspdate) 2 | % C2MDATE provides a simple method to convert between CRSP dates provided by WRDS and MATLAB dates. 3 | % 4 | % USAGE: 5 | % [MLDATE] = c2mdate(CRSPDATE) 6 | % 7 | % INPUTS: 8 | % CRSPDATE - A scalar or vector of CRSP dates. 9 | % 10 | % OUTPUTS: 11 | % MLDATE - A vector with the same size as CRSPDATE consisting of MATLAB dates. 12 | % 13 | % EXAMPLE: 14 | % crspdate = [19951028 20090706 20120401]' 15 | % mldate = c2mdate(crspdate); 16 | % datestr(mldate) 17 | % 28-Oct-1995 18 | % 06-Jul-2009 19 | % 01-Apr-2012 20 | % 21 | % COMMENTS: 22 | % This is provided to make it easy to move between CRSP and MATLAB dates. 23 | % 24 | % See also X2MDATE 25 | 26 | % Copyright: Kevin Sheppard 27 | % kevin.sheppard@economics.ox.ac.uk 28 | % Revision: 2 Date: 10/17/2009 29 | 30 | 31 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 32 | % Input Validation 33 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 34 | if any(ischar(crspdate)) 35 | error('CRSPDATE must be numeric') 36 | end 37 | 38 | if ndims(crspdate)~=2 && min(size(crspdate))~=1 39 | error('CRSPDATE must be a T by 1 or 1 by T vector'); 40 | end 41 | 42 | if nargin~=1 43 | error('1 inputs only'); 44 | end 45 | 46 | if any(crspdate<18000000) 47 | error('CRSPDATE appears to be incorrectly formatted. Only supported format is YYYYMMDD'); 48 | end 49 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 50 | % Input Validation 51 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 52 | 53 | yr = floor(crspdate/10000); 54 | mo = floor(mod(crspdate,10000)/100); 55 | dd = mod(crspdate,100); 56 | 57 | mldate = datenum(yr,mo,dd); 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /utility/chol2vec.m: -------------------------------------------------------------------------------- 1 | function stackedData = chol2vec(matrixData) 2 | % Transform a lower triangular matrix its half-vec representation for use in covariance applications 3 | % 4 | % USAGE: 5 | % STACKEDDATA = chol2vec(MATRIXDATA) 6 | % 7 | % INPUTS: 8 | % MATRIXDATA - a K by K lower triangular matrix 9 | % 10 | % OUTPUTS: 11 | % STACKEDDATA - A K(K+1)/2 vector of stacked data 12 | % 13 | % COMMENTS: 14 | % The data is stacked according to 15 | % [ data(1) 0 0 ... ... 0 16 | % data(2) data(K+1) 0 ... ... 0 17 | % data(3) data(K+2) data(K+2) 0 ... 0 18 | % ... .... ... ... ... 0 19 | % data(K) data(2K-1) ... ... data(K(K+1)/2-1) data(K(K+1)/2) ] 20 | % 21 | % See also vec2chol 22 | 23 | % Author: Kevin Sheppard 24 | % kevin.sheppard@economics.ox.ac.uk 25 | % Revision: 3 Date: 2/1/2008 26 | 27 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 28 | % Input Checking 29 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 30 | [k,l] = size(matrixData); 31 | pl = ~tril(true(k)); 32 | if k~=l || any(matrixData(pl)~=0) 33 | error('MATRIXDATA must be a lower triangular matrix'); 34 | end 35 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 36 | % Input Checking 37 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 38 | sel = tril(true(k)); 39 | stackedData = matrixData(sel); 40 | -------------------------------------------------------------------------------- /utility/corr_ivech.m: -------------------------------------------------------------------------------- 1 | function matrixData=corr_ivech(stackedData) 2 | % Transform a vector into a symmetric correlation matrix for use in correlation applications 3 | % 4 | % USAGE: 5 | % MATRIXDATA = corr_ivech(STACKEDDATA) 6 | % 7 | % INPUTS: 8 | % STACKEDDATA: A K(K-1)/2 vector of data to be transformed 9 | % 10 | % OUTPUTS: 11 | % MATRIXDATA - a K by K symmetric matrix 12 | % 13 | % COMMENTS: 14 | % The data is stacked according to 15 | % [ 1 data(1) data(2) ... data(K-1) 16 | % data(1) 1 data(K) ... ... 17 | % data(2) data(K) data(2K-4) ... ... 18 | % ... .... ... ... data(K(K-1)/2) 19 | % data(K-1) data(2K-3) ... ... 1 ] 20 | % 21 | % See also IVECH, CORR_VECH 22 | 23 | % Author: Kevin Sheppard 24 | % kevin.sheppard@economics.ox.ac.uk 25 | % Revision: 3 Date: 2/1/2008 26 | 27 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 28 | % Input Checking 29 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 30 | if size(stackedData,2)>size(stackedData,1) 31 | stackedData=stackedData'; 32 | end 33 | 34 | if size(stackedData,2)~=1 35 | error('STACKED_DATA must be a column vector.') 36 | end 37 | 38 | K2=size(stackedData,1); 39 | K=(-1+sqrt(1+8*K2))/2 + 1; 40 | 41 | if floor(K)~=K 42 | error(['The number of elemeents in STACKED_DATA must be conformable to' ... 43 | 'the inverse vech operation.']) 44 | end 45 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 46 | % Input Checking 47 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 48 | matrixData = zeros(K); 49 | loc = ~triu(true(K)); 50 | matrixData(loc) = stackedData; 51 | matrixData = matrixData + matrixData' + eye(K); -------------------------------------------------------------------------------- /utility/corr_vech.m: -------------------------------------------------------------------------------- 1 | function stackedData = corr_vech(matrixData) 2 | % Transform a correlation matrix into a vector for use in correlation applications 3 | % 4 | % USAGE: 5 | % STACKEDDATA = corr_vech(MATRIXDATA) 6 | % 7 | % INPUTS: 8 | % MATRIXDATA - a K by K symmetric matrix 9 | % 10 | % OUTPUTS: 11 | % STACKEDDATA: A K(K-1)/2 vector of stacked data 12 | % 13 | % COMMENTS: 14 | % The data is stacked according to 15 | % [ 1 data(1) data(2) ... data(K-1) 16 | % data(1) 1 data(K) ... ... 17 | % data(2) data(K) data(2K-4) ... ... 18 | % ... .... ... ... data(K(K-1)/2) 19 | % data(K-1) data(2K-3) ... ... 1 ] 20 | % 21 | % See also VECH, CORR_IVECH 22 | 23 | % Author: Kevin Sheppard 24 | % kevin.sheppard@economics.ox.ac.uk 25 | % Revision: 3 Date: 2/1/2008 26 | 27 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 28 | % Input Checking 29 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 30 | [k,l] = size(matrixData); 31 | if k~=l || any(any(matrixData~=matrixData')) 32 | error('MATRIXDATA must be a symmetric matrix'); 33 | end 34 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 35 | % Input Checking 36 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 37 | sel = ~triu(true(k)); 38 | stackedData = matrixData(sel); 39 | -------------------------------------------------------------------------------- /utility/cov2corr.m: -------------------------------------------------------------------------------- 1 | function [sigma,correl] = cov2corr(cov) 2 | % Convert covariance matrices to correlation matrices. 3 | % 4 | % USAGE: 5 | % [SIGMA,CORREL] = cov2corr(COV) 6 | % 7 | % INPUTS: 8 | % COV - A K by K covariance matrix -OR- 9 | % A K by K by T array of covariance matrices 10 | % 11 | % OUTPUTS: 12 | % SIGMA - A K by 1 vector of standard deviations if COV is K by K -OR- 13 | % A T by K matrix of standard deviations 14 | % CORREL - A K by K matrix of correlations -OR- 15 | % A K by K by T matrix of correlations. 16 | % 17 | % EXAMPLES: 18 | % % DCC(1,1) 19 | % [~,~,Ht] = dcc(data,[],1,0,1) 20 | % [S,Rt] = cov2corr(Rt); 21 | % 22 | % See also DCC 23 | 24 | % Copyright: Kevin Sheppard 25 | % kevin.sheppard@economics.ox.ac.uk 26 | % Revision: 1 Date: 10/23/2012 27 | 28 | if ndims(cov)==2 29 | sigma = sqrt(diag(cov)); 30 | correl = cov ./(sigma*sigma'); 31 | elseif ndims(cov)==3 32 | T = size(cov,3); 33 | K = size(cov,2); 34 | sigma = zeros(T,K); 35 | correl = zeros(K,K,T); 36 | for t=1:T 37 | sigma(t,:) = sqrt(diag(cov(:,:,t)))'; 38 | correl(:,:,t) = cov(:,:,t)./(sigma(t,:)'*sigma(t,:)); 39 | end 40 | end -------------------------------------------------------------------------------- /utility/covnw.m: -------------------------------------------------------------------------------- 1 | function V=covnw(data,nlag,demean) 2 | % Long-run covariance estimation using Newey-West (Bartlett) weights 3 | % 4 | % USAGE: 5 | % [V] = covnw(DATA) 6 | % [V] = covnw(DATA,NLAG,DEMEAN) 7 | % 8 | % INPUTS: 9 | % DATA - T by K vector of dependent data 10 | % NLAG - Non-negative integer containing the lag length to use. If empty or not included, 11 | % NLAG=min(floor(1.2*T^(1/3)),T) is used 12 | % DEMEAN - Logical true or false (0 or 1) indicating whether the mean should be subtracted when 13 | % computing the covariance 14 | % 15 | % OUTPUTS: 16 | % V - A K by K covariance matrix estimated using Newey-West (Bartlett) weights 17 | % 18 | % COMMENTS: 19 | % 20 | % EXAMPLES: 21 | % Simulate an AR(1) 22 | % y = armaxfilter_simulate(1000,0,1,.9); 23 | % Newey-West covariance with automatic BW selection 24 | % lrcov = covnw(y) 25 | % Newey-West covariance with 10 lags 26 | % lrcov = covnw(y, 10) 27 | % Newey-West covariance with 10 lags and no demeaning 28 | % lrcov = covnw(y, 10, 0) 29 | % 30 | % See also COVVAR 31 | 32 | % Copyright: Kevin Sheppard 33 | % kevin.sheppard@economics.ox.ac.uk 34 | % Revision: 3 Date: 5/1/2007 35 | 36 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 37 | % Input Checking 38 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 39 | T=size(data,1); 40 | if nargin==1 41 | nlag=min(floor(1.2*T^(1/3)),T); 42 | demean=true; 43 | elseif nargin==2 44 | demean=true; 45 | end 46 | if isempty(nlag) 47 | nlag=min(floor(1.2*T^(1/3)),T); 48 | end 49 | if isempty(demean) 50 | demean=true; 51 | end 52 | if ~ismember(demean,[0 1]) 53 | error('DEMEAN must be either logical true or false.') 54 | end 55 | if floor(nlag)~=nlag || nlag<0 56 | error('NLAG must be a non-negative integer.') 57 | end 58 | if ndims(data)>2 59 | error('DATA must be a T by K matrix of data.') 60 | end 61 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 62 | % Input Checking 63 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 64 | if demean 65 | data=data-repmat(mean(data),T,1); 66 | end 67 | 68 | % NW weights 69 | w=(nlag+1-(0:nlag))./(nlag+1); 70 | % Start the covariance 71 | V=data'*data/T; 72 | for i=1:nlag 73 | Gammai=(data((i+1):T,:)'*data(1:T-i,:))/T; 74 | GplusGprime=Gammai+Gammai'; 75 | V=V+w(i+1)*GplusGprime; 76 | end 77 | 78 | 79 | -------------------------------------------------------------------------------- /utility/demean.m: -------------------------------------------------------------------------------- 1 | function x = demean(y) 2 | % Demeans an N-dimensional vector 3 | % 4 | % USAGE: 5 | % DEMEANED = vech(DATA) 6 | % 7 | % INPUTS: 8 | % DATA - An N-dimensional matrix 9 | % 10 | % OUTPUTS: 11 | % DEMEANED - A mean 0 matrix with the same size as DATA (column-by-column) 12 | % 13 | % COMMENTS: 14 | % 15 | % See also STANDARDIZE 16 | 17 | % Author: Kevin Sheppard 18 | % kevin.sheppard@economics.ox.ac.uk 19 | % Revision: 3 Date: 1/1/2010 20 | 21 | mu = mean(y,1); 22 | x = bsxfun(@minus,y,mu); 23 | 24 | -------------------------------------------------------------------------------- /utility/dirod.m: -------------------------------------------------------------------------------- 1 | function varargout = dirod(varargin) 2 | % Date sorted folder listing 3 | % 4 | % USAGE: 5 | % dirod 6 | % dirod FILENAMEMASK 7 | % dirod('FILENAMEMASK') 8 | % LIST = dirod('FILENAMEMASK') 9 | % 10 | % INPUTS: 11 | % FILENAMEMASK - A file name mask, e.g. *, *.m or d*.m 12 | % 13 | % OUTPUTS: 14 | % LIST - A directory structure ordered by date 15 | % 16 | % COMMENTS: 17 | % Similar to the windows command dir /od 18 | 19 | % Copyright: Kevin Sheppard 20 | % kevin.sheppard@economics.ox.ac.uk 21 | % Revision: 1 Date: 6/7/2010 22 | 23 | if isempty(varargin) 24 | arg = '*'; 25 | elseif length(varargin)==1 26 | arg = varargin{1}; 27 | else 28 | error('Too many input arguments. 0 or 1 input only'); 29 | end 30 | 31 | dirData = dir(arg); 32 | [~,index]=sort([dirData.datenum]); 33 | dirData = dirData(index); 34 | 35 | fileNameLen = length(dirData(1).name); 36 | for i=2:length(dirData) 37 | fileNameLen = max(fileNameLen,length(dirData(i).name)); 38 | end 39 | 40 | if nargout==0 41 | disp(' '); 42 | for i=1:length(dirData) 43 | disp([dirData(i).name repmat(' ',1,fileNameLen-length(dirData(i).name)+2) dirData(i).date]); 44 | end 45 | disp(' '); 46 | else 47 | varargout{1} = dirData; 48 | end 49 | -------------------------------------------------------------------------------- /utility/gradient_2sided.m: -------------------------------------------------------------------------------- 1 | function [G,Gt] = gradient_2sided(f,x,varargin) 2 | % Computes 2-sided finite difference gradient vector 3 | % 4 | % USAGE: 5 | % [G,GT]=gradient_2sided(FUNC,X,VARARGIN) 6 | % 7 | % INPUTS: 8 | % FUNC - function name, fval = func(x,varargin) 9 | % X - vector of parameters (M x 1) 10 | % VARARGIN - optional arguments passed to the function 11 | % 12 | % OUTPUTS: 13 | % G - finite differnce, 2-sided gradient 14 | % GT - T by M matrix of individual scores. Used in estimating 15 | % covariances 16 | % 17 | % COMMENTS: 18 | % Modification of hessian() from the jpl toolbox 19 | 20 | 21 | % Code originally from COMPECON toolbox [www4.ncsu.edu/~pfackler] 22 | % documentation modified to fit the format of the Ecoometrics Toolbox 23 | % by James P. LeSage, Dept of Economics 24 | % University of Toledo 25 | % 2801 W. Bancroft St, 26 | % Toledo, OH 43606 27 | % jlesage@spatial-econometrics.com 28 | % 29 | % Further modified (to do 2-sided numerical derivs, rather than 1) 30 | % 31 | % Modifications Copyright: Kevin Sheppard 32 | % kevin.sheppard@economics.ox.ac.uk 33 | % Revision: 3 Date: 2/1/2006 34 | 35 | if size(x,2)>size(x,1) 36 | x=x'; 37 | end 38 | 39 | M = size(x,1); 40 | 41 | h = eps.^(1/3)*max(abs(x),1e-2); 42 | xh = x+h; 43 | h = xh-x; 44 | % Compute forward step 45 | ee = diag(h);%sparse(1:M,1:M,h,M,M) 46 | gf = zeros(M,1); 47 | gb = zeros(M,1); 48 | 49 | if nargout==2 50 | [temp1,temp2] = feval(f,x+ee(:,1),varargin{:}); 51 | T=length(temp2); 52 | Gf=zeros(T,M); 53 | Gb=zeros(T,M); 54 | end 55 | 56 | for i=1:M 57 | if nargout<2 58 | gf(i) = feval(f,x+ee(:,i),varargin{:}); 59 | else 60 | [gf(i),Gf(:,i)] = feval(f,x+ee(:,i),varargin{:}); 61 | end 62 | end 63 | 64 | % Compute backward step 65 | for i=1:M 66 | if nargout<2 67 | gb(i) = feval(f,x-ee(:,i),varargin{:}); 68 | else 69 | [gb(i),Gb(:,i)] = feval(f,x-ee(:,i),varargin{:}); 70 | end 71 | end 72 | 73 | G = (gf-gb)./(2*h); 74 | if nargout==2 75 | T=size(Gb,1); 76 | Gt = (Gf-Gb)./repmat(2*h',T,1); 77 | end 78 | -------------------------------------------------------------------------------- /utility/hessian_2sided.m: -------------------------------------------------------------------------------- 1 | function H = hessian_2sided(f,x,varargin) 2 | % Computes 2-sided finite difference Hessian 3 | % 4 | % USAGE: 5 | % H=hessian_2sided(FUNC,X,VARARGIN) 6 | % 7 | % INPUTS: 8 | % FUNC - Function name, fval = func(x,varargin) 9 | % X - Vector of parameters (N x 1) 10 | % VARARGIN - Optional arguments passed to the function 11 | % 12 | % OUTPUTS: 13 | % H - Finite differnce, 2-sided hessian 14 | % 15 | % COMMENTS: 16 | % Modification of hessian() from the jpl toolbox 17 | 18 | 19 | % Code originally from COMPECON toolbox [www4.ncsu.edu/~pfackler] 20 | % documentation modified to fit the format of the Econometrics Toolbox 21 | % by James P. LeSage, Dept of Economics 22 | % University of Toledo 23 | % 2801 W. Bancroft St, 24 | % Toledo, OH 43606 25 | % jlesage@spatial-econometrics.com 26 | % 27 | % Further modified (to do 2-sided numerical derivs, rather than 1) by: 28 | % Modifications Copyright: Kevin Sheppard 29 | % kevin.sheppard@economics.ox.ac.uk 30 | % Revision: 3 Date: 9/1/2005 31 | 32 | n = size(x,1); 33 | 34 | if size(x,2)~=1 35 | error('X must be a column vector.') 36 | end 37 | 38 | try 39 | feval(f,x,varargin{:}); 40 | catch FE 41 | errtxt=['There was an error evaluating the function. Please check the arguements. The specific error was:' FE.message]; 42 | error(errtxt); 43 | end 44 | 45 | 46 | fx = feval(f,x,varargin{:}); 47 | 48 | % Compute the stepsize (h) 49 | h = eps.^(1/3)*max(abs(x),1e-8); 50 | xh = x+h; 51 | h = xh-x; 52 | ee = sparse(1:n,1:n,h,n,n); 53 | 54 | % Compute forward and backward steps 55 | gp = zeros(n,1); 56 | gm = zeros(n,1); 57 | for i=1:n 58 | gp(i) = feval(f,x+ee(:,i),varargin{:}); 59 | gm(i) = feval(f,x-ee(:,i),varargin{:}); 60 | end 61 | 62 | hh=h*h'; 63 | Hm=NaN*ones(n); 64 | Hp=NaN*ones(n); 65 | % Compute "double" forward and backward steps 66 | for i=1:n 67 | for j=i:n 68 | Hp(i,j) = feval(f,x+ee(:,i)+ee(:,j),varargin{:}); 69 | Hp(j,i)=Hp(i,j); 70 | Hm(i,j) = feval(f,x-ee(:,i)-ee(:,j),varargin{:}); 71 | Hm(j,i)=Hm(i,j); 72 | end 73 | end 74 | %Compute the hessian 75 | H = zeros(n); 76 | for i=1:n 77 | for j=i:n 78 | H(i,j) = (Hp(i,j)-gp(i)-gp(j)+fx+fx-gm(i)-gm(j)+Hm(i,j))/hh(i,j)/2; 79 | H(j,i) = H(i,j); 80 | end 81 | end 82 | -------------------------------------------------------------------------------- /utility/hessian_2sided_nrows.m: -------------------------------------------------------------------------------- 1 | function H = hessian_2sided_nrows(f,x,k,varargin) 2 | % Computes the last K rows of a 2-sided finite difference Hessian 3 | % 4 | % USAGE: 5 | % H=hessian_2sided_nrows(FUNC,X,K,VARARGIN) 6 | % 7 | % INPUTS: 8 | % FUNC - Function name, fval = func(x,varargin) 9 | % X - Vector of parameters (N x 1) 10 | % K - Number of rows to compute 11 | % VARARGIN - Optional arguments passed to the function 12 | % 13 | % OUTPUTS: 14 | % H - Finite difference, 2-sided hessian: N x K 15 | % 16 | % COMMENTS: 17 | % Modification of hessian_2sided 18 | % See also HESSIAN_2SIDED 19 | 20 | % Code originally from COMPECON toolbox [www4.ncsu.edu/~pfackler] 21 | % documentation modified to fit the format of the Econometrics Toolbox 22 | % by James P. LeSage, Dept of Economics 23 | % University of Toledo 24 | % 2801 W. Bancroft St, 25 | % Toledo, OH 43606 26 | % jlesage@spatial-econometrics.com 27 | % 28 | % Further modified (to do 2-sided numerical derivs, rather than 1) by: 29 | % Modifications Copyright: Kevin Sheppard 30 | % kevin.sheppard@economics.ox.ac.uk 31 | % Revision: 3 Date: 9/1/2005 32 | 33 | if size(x,2)>size(x,1) 34 | x=x'; 35 | end 36 | if size(x,2)~=1 37 | error('X must be a column vector.') 38 | end 39 | n = size(x,1); 40 | 41 | try 42 | feval(f,x,varargin{:}); 43 | catch FE 44 | errtxt=['There was an error evaluating the function. Please check the arguements. The specific error was:' FE.message]; 45 | error(errtxt); 46 | end 47 | 48 | 49 | fx = feval(f,x,varargin{:}); 50 | 51 | % Compute the stepsize (h) 52 | h = eps.^(1/3)*max(abs(x),1e-2); 53 | xh = x+h; 54 | h = xh-x; 55 | 56 | ee = sparse(1:n,1:n,h,n,n); 57 | 58 | % Compute forward and backward steps 59 | gp = zeros(n,1); 60 | gm = zeros(n,1); 61 | for i=1:n 62 | gp(i) = feval(f,x+ee(:,i),varargin{:}); 63 | gm(i) = feval(f,x-ee(:,i),varargin{:}); 64 | end 65 | 66 | hh=h*h'; 67 | Hm=NaN*ones(n); 68 | Hp=NaN*ones(n); 69 | % Compute "double" forward and backward steps 70 | for i=n-k+1:n 71 | for j=1:n 72 | Hp(i,j) = feval(f,x+ee(:,i)+ee(:,j),varargin{:}); 73 | Hp(j,i)=Hp(i,j); 74 | Hm(i,j) = feval(f,x-ee(:,i)-ee(:,j),varargin{:}); 75 | Hm(j,i)=Hm(i,j); 76 | end 77 | end 78 | %Compute the hessian 79 | H = zeros(n); 80 | for i=(n-k+1):n 81 | for j=1:n 82 | H(i,j) = (Hp(i,j)-gp(i)-gp(j)+fx+fx-gm(i)-gm(j)+Hm(i,j))/hh(i,j)/2; 83 | H(j,i) = H(i,j); 84 | end 85 | end 86 | 87 | %Only the final K rows 88 | H=H((n-k+1):n,:); 89 | -------------------------------------------------------------------------------- /utility/ivech.m: -------------------------------------------------------------------------------- 1 | function matrixData=ivech(stackedData) 2 | % Transform a vector in to a symmetric matrix for use in covariance applications 3 | % 4 | % USAGE: 5 | % MATRIXDATA = ivech(STACKEDDATA) 6 | % 7 | % INPUTS: 8 | % STACKEDDATA: A K(K+1)/2 vector of data to be transformed 9 | % 10 | % OUTPUTS: 11 | % MATRIXDATA - a K by K symmetric matrix of the form 12 | % [ data(1) data(2) data(3) ... data(K) 13 | % data(2) data(K+1) data(K+2) ... ... 14 | % data(3) data(K+2) data(2K) ... ... 15 | % ... .... ... ... data(K(K+1)/2-1) 16 | % data(K) data(2K-1) ... data(K(K+1)/2-1) data(K(K+1)/2) ] 17 | % 18 | % COMMENTS: 19 | % 20 | % See also VECH 21 | 22 | % Author: Kevin Sheppard 23 | % kevin.sheppard@economics.ox.ac.uk 24 | % Revision: 3 Date: 2/1/2008 25 | 26 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 27 | % Input Checking 28 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 29 | if size(stackedData,2)>size(stackedData,1) 30 | stackedData=stackedData'; 31 | end 32 | 33 | if size(stackedData,2)~=1 34 | error('STACKED_DATA must be a column vector.') 35 | end 36 | 37 | K2=size(stackedData,1); 38 | K=(-1+sqrt(1+8*K2))/2; 39 | 40 | if floor(K)~=K 41 | error(['The number of elemeents in STACKED_DATA must be conformable to' ... 42 | 'the inverse vech operation.']) 43 | end 44 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 45 | % Input Checking 46 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 47 | 48 | % Initialize the output data 49 | matrixData=zeros(K); 50 | 51 | % Use a logical trick to inverse the vech 52 | pl=tril(true(K)); 53 | matrixData(pl)=stackedData; 54 | diag_matrixData=diag(diag(matrixData)); 55 | matrixData=matrixData+matrixData'-diag_matrixData; 56 | 57 | -------------------------------------------------------------------------------- /utility/m2cdate.m: -------------------------------------------------------------------------------- 1 | function crspdate = m2cdate(mldate) 2 | % M2CDATE provides a simple method to convert between MATLAB dates and CRSP 3 | % dates provided by WRDS. 4 | % 5 | % USAGE: 6 | % [CRSPDATE] = c2mdate(MLDATE) 7 | % 8 | % INPUTS: 9 | % MLDATE - A vector with the same size as CRSPDATE consisting of MATLAB dates. 10 | % 11 | % OUTPUTS: 12 | % CRSPDATE - A scalar or vector of CRSP dates. 13 | % 14 | % EXAMPLE: 15 | % mldate = [728960 733960 734960]'; 16 | % datestr(mldate) 17 | % 28-Oct-1995 18 | % 06-Jul-2009 19 | % 01-Apr-2012 20 | % crspdate = c2mdate(crspdate); 21 | % 22 | % COMMENTS: 23 | % This is provided to make it easy to move between CRSP and MATLAB dates. 24 | % 25 | % See also C2MDATE 26 | 27 | % Copyright: Kevin Sheppard 28 | % kevin.sheppard@economics.ox.ac.uk 29 | % Revision: 2 Date: 10/17/2009 30 | 31 | 32 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 33 | % Input Validation 34 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 35 | if any(ischar(mldate)) 36 | error('CRSPDATE must be numeric') 37 | end 38 | 39 | if ndims(mldate)~=2 && min(size(mldate))~=1 40 | error('CRSPDATE must be a T by 1 or 1 by T vector'); 41 | end 42 | 43 | if nargin~=1 44 | error('1 inputs only'); 45 | end 46 | 47 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 48 | % Input Validation 49 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 50 | 51 | v=datevec(mldate); 52 | crspdate = 10000*v(:,1) + 100*v(:,2) + v(:,3); 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /utility/mvstandardize.m: -------------------------------------------------------------------------------- 1 | function st=mvstandardize(x,sigma,demean) 2 | % Standardization of a matrix of data where each column returned will be 3 | % mean zero and have variance 1, and will be uncorrelated 4 | % 5 | % USAGE: 6 | % ST = standardize(X) 7 | % ST = standardize(X,SIGMA,DEMEAN) 8 | % 9 | % INPUTS: 10 | % X - A T by K matrix of data to be standardized 11 | % 12 | % OUTPUTS: 13 | % ST - A T by K matrix of standardized data 14 | % SIGMA - [OPTIONAL] Either a K by K covariance matrix or a K by K by T matrix of time-varying 15 | % covariances. If ommitted, the sample covariance is used 16 | % DEMEAN - [OPTIONAL] A logical value indicating whether to demean the data (1) or not (0). 17 | % Default is 1 18 | % 19 | % COMMENTS: 20 | % 21 | % See also deman, standardize 22 | 23 | % Copyright: Kevin Sheppard 24 | % kevin.sheppard@economics.ox.ac.uk 25 | % Revision: 1 Date: 9/1/2005 26 | 27 | switch nargin 28 | case 1 29 | sigma = cov(x); 30 | demean = true; 31 | case 2 32 | demean = true; 33 | case 3 34 | otherwise 35 | end 36 | 37 | if ndims(demean)~=2 || max(size(demean))~=1 38 | error('DEMEAN must be a logical scalar.') 39 | end 40 | [T,K]=size(x); 41 | if ndims(x)>2 42 | error('X must be a T by K matrix with T>K') 43 | end 44 | if ndims(sigma)==2 45 | if any(size(sigma)~=K) || min(eig(sigma<=0)) 46 | error('SIGMA by be a K by K positive definite matrix.') 47 | end 48 | elseif ndims(sigma)==3 49 | if any(size(sigma)~=[K K T]) 50 | error('If SIGMA is a 3-D matrix, it must be K by K by T.'); 51 | end 52 | for i=1:T 53 | if min(eig(sigma(:,:,i))<=0) 54 | error('If SIGMA is K by K by T, each covariance must be positive definite') 55 | end 56 | end 57 | else 58 | error('SIGMA by be either a K by K matrix, or a K by K by T matrix.') 59 | end 60 | 61 | if demean 62 | x=demean(x); 63 | end 64 | 65 | if ndims(sigma)==2 66 | st = x * sigma^(-0.5); 67 | else 68 | st = zeros(T,K); 69 | for i=1:T 70 | st(i,:) = x(i,:) * sigma(:,:,i)^(-0.5); 71 | end 72 | end 73 | -------------------------------------------------------------------------------- /utility/newlagmatrix.m: -------------------------------------------------------------------------------- 1 | function [y,x]=newlagmatrix(x,nlags,c) 2 | % Construction of a matrix of lags (X) and a vector (Y) for use in an 3 | % autoregression 4 | % 5 | % USAGE: 6 | % [Y,X]=newlagmatrix(Y,NLAGS,C) 7 | % 8 | % INPUTS: 9 | % Y - The dependant variable(Tx1) 10 | % NLAGS - The number of lags(scalar) 11 | % C - [OPTIONAL] 1 if you want to include a constant; 0 is default 12 | % 13 | % OUTPUTS: 14 | % Y - (n-p) by 1 vector of contemporaneous values 15 | % X - (n-p) by p (or p+1 if c=1) matrix of lags and possibly constant. The 16 | % matrix is of the form [constant(if included) t-1 t-2 ... t-p] 17 | % 18 | % COMMENTS: 19 | % Original name, 'lagmatrix' conflicts with a Matlab file, so newlagmatrix 20 | % replaces original 21 | 22 | % Author: Kevin Sheppard 23 | % kevin.sheppard@economics.ox.ac.uk 24 | % Revision: 5 Date: 12/1/2005 25 | 26 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 27 | % Input Checking 28 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 29 | switch nargin 30 | case 2 31 | c=0; 32 | case 3 33 | %Nothing 34 | otherwise 35 | error('newlagmatrix requires either 2 or 3 arguments.') 36 | end 37 | 38 | [T,K]=size(x); 39 | if min(T,K)~=1 40 | error('X must be a vector') 41 | end 42 | 43 | if T0 60 | nlags=nlags+1; 61 | newX=[x;zeros(nlags,1)]; 62 | lagmatrix=repmat(newX,nlags,1); 63 | lagmatrix=reshape(lagmatrix(1:size(lagmatrix,1)-nlags),T+nlags-1,nlags); 64 | lagmatrix=lagmatrix(nlags:T,:); 65 | y=lagmatrix(:,1); 66 | x=lagmatrix(:,2:nlags); 67 | if c==1 68 | x=[ones(size(x,1),1) x]; 69 | end 70 | else 71 | if c==1 72 | y=x; 73 | x=ones(T,1); 74 | else 75 | y=x; 76 | x=[]; 77 | end 78 | end 79 | -------------------------------------------------------------------------------- /utility/phi2r.m: -------------------------------------------------------------------------------- 1 | function R = phi2r(phi,transform) 2 | % Transformation of a vector of angles in [0,pi] to a correlation matrix 3 | % 4 | % USAGE: 5 | % [R] = phi2r(PHI) 6 | % 7 | % INPUTS: 8 | % PHI - K(K-1)/2 vector of values in [0,pi] 9 | % 10 | % OUTPUTS: 11 | % R - A K by K correlation matrix 12 | % 13 | % COMMENTS: 14 | % 15 | % See also R2PHI, Z2R, R2Z 16 | 17 | if nargin==2 && transform 18 | phi = 2*pi*exp(phi)./(1+exp(phi)); 19 | end 20 | 21 | m = length(phi); 22 | k = ceil(sqrt(2*m)); 23 | Csel = ~tril(ones(k)); 24 | Ssel = triu(true(k)); 25 | Ssel(1,:) = false; 26 | C = eye(k); 27 | S = zeros(k); 28 | S(1,:) = 1; 29 | c = cos(phi); 30 | s = sin(phi); 31 | C(Csel)=c; 32 | S(Ssel)=s; 33 | 34 | C = C.*cumprod(S); 35 | R = C'*C; 36 | r = sqrt(diag(R)); 37 | R = R./(r*r'); 38 | R = (R+R')/2; 39 | -------------------------------------------------------------------------------- /utility/phi2u.m: -------------------------------------------------------------------------------- 1 | function U = phi2u(phi) 2 | 3 | m = length(phi); 4 | k = ceil(sqrt(2*m)); 5 | U = eye(k); 6 | c = cos(phi); 7 | s = sin(phi); 8 | count = 1; 9 | for i=1:k 10 | for j=i+1:k 11 | R = eye(k); 12 | R(i,i) = c(count); 13 | R(i,j) = -s(count); 14 | R(j,i) = s(count); 15 | R(j,j) = c(count); 16 | U = U*R; 17 | count = count + 1; 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /utility/pltdens.m: -------------------------------------------------------------------------------- 1 | function [h,f,xx] = plotdens(x,h,positive,kernel) 2 | % PURPOSE: Draw a nonparametric density estimate. 3 | %--------------------------------------------------- 4 | % USAGE: [h f y] = pltdens(x,h,p,kernel) 5 | % or pltdens(x) which uses gaussian kernel default 6 | % where: 7 | % x is a vector 8 | % h is the kernel bandwidth 9 | % default=1.06 * std(x) * n^(-1/5); Silverman page 45 10 | % p is 1 if the density is 0 for negative values 11 | % k is the kernel type: 12 | % =1 Gaussian (default) 13 | % =2 Epanechnikov 14 | % =3 Biweight 15 | % =4 Triangular 16 | % A jittered plot of the 17 | % observations is shown below the density. 18 | %--------------------------------------------------- 19 | % RETURNS: 20 | % h = the interval used 21 | % f = the density 22 | % y = the domain of support 23 | % plot(y,f) will produce a plot of the density 24 | % -------------------------------------------------- 25 | % SEE ALSO hist, histo 26 | %--------------------------------------------------- 27 | 28 | % Anders Holtsberg, 18-11-93 29 | % Copyright (c) Anders Holtsberg 30 | 31 | x = x(:); n = length(x); 32 | if nargin < 4, kernel = 1; end 33 | if nargin < 3, positive = 0; end 34 | if nargin < 2, h = []; end 35 | if isempty(h) 36 | h = 1.06 * std(x) * n^(-1/5); % Silverman page 45 37 | end 38 | if positive & any(x < 0) 39 | error('There is a negative element in X') 40 | end 41 | mn1 = min(x); mx1 = max(x); 42 | mn = mn1 - (mx1-mn1)/3; 43 | mx = mx1 + (mx1-mn1)/3; 44 | gridsize = 256; 45 | xx = linspace(mn,mx,gridsize)'; 46 | d = xx(2) - xx(1); 47 | xh = zeros(size(xx)); 48 | xa = (x-mn)/(mx-mn)*gridsize; 49 | for i=1:n 50 | il = floor(xa(i)); 51 | a = xa(i) - il; 52 | xh(il+[1 2]) = xh(il+[1 2])+[1-a, a]'; 53 | end 54 | xk = [-gridsize:gridsize-1]'*d; 55 | if kernel == 1 56 | K = exp(-0.5*(xk/h).^2); 57 | elseif kernel == 2 58 | K = max(0,1-(xk/h).^2/5); 59 | elseif kernel == 3 60 | c = sqrt(1/7); 61 | K = (1-(xk/h*c).^2).^2 .* ((1-abs(xk/h*c)) > 0); 62 | elseif kernel == 4 63 | c = sqrt(1/6); 64 | K = max(0,1-abs(xk/h*c)); 65 | end 66 | K = K / (sum(K)*d*n); 67 | f = ifft(fft(fftshift(K)).*fft([xh ;zeros(size(xh))])); 68 | f = real(f(1:gridsize)); 69 | if positive 70 | m = sum(xx<0); 71 | f(m+(1:m)) = f(m+(1:m)) + f(m:-1:1); 72 | f(1:m) = zeros(size(f(1:m))); 73 | xx(m+[0 1]) = [0 0]; 74 | end 75 | if nargout == 0 76 | plot(xx,f) 77 | if ~ishold 78 | hold on 79 | d = diff(get(get(gcf,'CurrentAxes'),'Ylim'))/100; 80 | plot(x,(-rand(size(x))*6-1)*d,'.') 81 | plot([mn mx],[0 0]) 82 | axis([mn mx -0.2*max(f) max(f)*1.2]) 83 | hold off 84 | end 85 | end; 86 | -------------------------------------------------------------------------------- /utility/r2phi.m: -------------------------------------------------------------------------------- 1 | function phi = r2phi(R) 2 | % Transformation of a correlation matrix to a set of angles in [0,pi] 3 | % 4 | % USAGE: 5 | % [PHI] = r2phi(R) 6 | % 7 | % INPUTS: 8 | % R - A K by K correlation matrix 9 | % 10 | % OUTPUTS: 11 | % PHI - K(K-1)/2 vector of values in [0,2*pi] 12 | % 13 | % COMMENTS: 14 | % See phi2r for information about the transformation from Z to R. 15 | % 16 | % See also PHI2R, Z2R, R2Z 17 | 18 | 19 | % FIXME : It is necessary to invert both cos and sin to identify where in 0, 2pi the angle is 20 | X = chol(R); 21 | k = length(R); 22 | S = zeros(k); 23 | 24 | P = zeros(k); 25 | S(1,:) = 1; 26 | cumS = S; 27 | for i=1:k-1 28 | P(i,i+1:k) = acos(X(i,i+1:k)./cumS(i,i+1:k)); 29 | S(i+1,i+1:k) = sin(P(i,i+1:k)); 30 | cumS(i+1,i+1:k) = prod(S(1:i+1,i+1:k)); 31 | end 32 | phi = P(P>0); -------------------------------------------------------------------------------- /utility/r2z.m: -------------------------------------------------------------------------------- 1 | function z = r2z(R) 2 | % Transformation of a correlation matrix to an unconstrained K(K-1)/2 vector 3 | % 4 | % USAGE: 5 | % [R] = r2z(Z) 6 | % 7 | % INPUTS: 8 | % R - A K by K correlation matrix 9 | % 10 | % OUTPUTS: 11 | % Z - K(K-1)/2 vector of values in (-inf,inf) 12 | % 13 | % COMMENTS: 14 | % See z2r for information about the transformation from Z to R. 15 | % 16 | % See also Z2R, R2PHI, PHI2R 17 | 18 | % Copyright: Kevin Sheppard 19 | % kevin.sheppard@economics.ox.ac.uk 20 | % Revision: 1 Date: 3/27/2012 21 | 22 | 23 | k = length(R); 24 | C = zeros(k); 25 | C2 = chol(R)'; 26 | 27 | for i=2:k 28 | rem = 1; 29 | for j=i-1:-1:1 30 | C(i,j) = C2(i,j)/sqrt(rem); 31 | rem = rem - C2(i,j)^2; 32 | end 33 | end 34 | 35 | C =C'; 36 | z = C(~tril(true(k))); 37 | z = log((z+1)./(1-z)); -------------------------------------------------------------------------------- /utility/randchar.m: -------------------------------------------------------------------------------- 1 | function c = randchar(n) 2 | 3 | u = rand(1,n); 4 | u = floor(u*26)+65; 5 | c=char(u); -------------------------------------------------------------------------------- /utility/robustvcv.m: -------------------------------------------------------------------------------- 1 | function [VCV,A,B,scores,hess,gross_scores]=robustvcv(fun,theta,nw,varargin) 2 | % Compute Robust Variance Covariance matrix numerically, including 3 | % Newey-West style score covariance using 2-sided derivatives 4 | % 5 | % USAGE: 6 | % [VCV,A,B,SCORES,HESS,GROSS_SCORES]=robustvcv(FUN,THETA,NW,VARARGIN) 7 | % 8 | % INPUTS: 9 | % FUN - Function name ('fun') or function handle (@fun) which will 10 | % return the sum of the log-likelihood (scalar) as the 1st output and the individual 11 | % log likelihoods (T by 1 vector) as the second output. 12 | % THETA - Parameter estimates at the optimum, usually from fmin* 13 | % NW - Number of lags to consider in Newey-West covariance. 14 | % Normally set to 0 15 | % VARARGIN - Other inputs to the log-likelihood function, such as data 16 | % 17 | % OUTPUTS: 18 | % VCV - Estimated robust covariance matrix (see White 1994) 19 | % A - A portion of robust covariance 20 | % B - B portion of robust covariance 21 | % SCORES - T x num_parameters matrix of scores 22 | % HESS - Estimated Hessian (Expectation of second derivative) 23 | % GROSS_SCORES - Numerical scores (1 by num_parameters) of the objective function, usually for diagnostics 24 | % 25 | % COMMENTS: 26 | % This function simplifies calculating sandwich covariance estimators for (Q)MLE estimation 27 | 28 | 29 | % Copyright: Kevin Sheppard 30 | % kevin.sheppard@economics.ox.ac.uk 31 | % Revision: 1 Date: 9/1/2005 32 | 33 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 34 | % Input Argument Checking 35 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 36 | if size(theta,1)size(stackedData,1) 31 | stackedData=stackedData'; 32 | end 33 | 34 | if size(stackedData,2)~=1 35 | error('STACKED_DATA must be a column vector.') 36 | end 37 | 38 | K2=size(stackedData,1); 39 | K=(-1+sqrt(1+8*K2))/2; 40 | 41 | if floor(K)~=K 42 | error(['The number of elemeents in STACKED_DATA must be conformable to' ... 43 | 'the inverse chol2vec operation.']) 44 | end 45 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 46 | % Input Checking 47 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 48 | 49 | % Initialize the output data 50 | matrixData=zeros(K); 51 | 52 | % Use a logical trick to inverse the vech 53 | pl=tril(true(K)); 54 | matrixData(pl)=stackedData; 55 | -------------------------------------------------------------------------------- /utility/vech.m: -------------------------------------------------------------------------------- 1 | function stackedData = vech(matrixData) 2 | % Transform a symmetric matrix to its half-vec representation for use in covariance applications 3 | % 4 | % USAGE: 5 | % STACKEDDATA = vech(MATRIXDATA) 6 | % 7 | % INPUTS: 8 | % MATRIXDATA - a K by K symmetric matrix 9 | % 10 | % OUTPUTS: 11 | % STACKEDDATA - A K(K+1)/2 vector of stacked data 12 | % 13 | % COMMENTS: 14 | % The data is stacked according to 15 | % [ data(1) data(2) data(3) ... data(K) 16 | % data(2) data(K+1) data(K+2) ... ... 17 | % data(3) data(K+2) data(2K) ... ... 18 | % ... .... ... ... data(K(K+1)/2-1) 19 | % data(K) data(2K-1) ... data(K(K+1)/2-1) data(K(K+1)/2) ] 20 | % 21 | % See also IVECH 22 | 23 | % Author: Kevin Sheppard 24 | % kevin.sheppard@economics.ox.ac.uk 25 | % Revision: 3 Date: 2/1/2008 26 | 27 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 28 | % Input Checking 29 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 30 | [k,l] = size(matrixData); 31 | if k~=l || any(any(matrixData~=matrixData')) 32 | error('MATRIXDATA must be a symmetric matrix'); 33 | end 34 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 35 | % Input Checking 36 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 37 | sel = tril(true(k)); 38 | stackedData = matrixData(sel); -------------------------------------------------------------------------------- /utility/x2mdate.m: -------------------------------------------------------------------------------- 1 | function mldate = x2mdate(xlsdate, type) 2 | % X2MDATE provides a simple method to convert between excel dates and MATLAB dates. 3 | % 4 | % USAGE: 5 | % [MLDATE] = x2mdate(XLSDATE) 6 | % [MLDATE] = x2mdate(XLSDATE, TYPE) 7 | % 8 | % INPUTS: 9 | % XLSDATE - A scalar or vector of Excel dates. 10 | % TYPE - [OPTIONAL] A scalar or vector of the same size as XLSDATE that describes the Excel 11 | % basedate. Can be either 0 or 1. If 0 (default), the base date of Dec-31-1899 is 12 | % used. If 1, the base date is Jan 1, 1904. 13 | % 14 | % OUTPUTS: 15 | % MLDATE - A vector with the same size as XLSDATE consisting of MATLAB dates. 16 | % 17 | % EXAMPLE: 18 | % XLSDATE = [35000 40000 41000]; 19 | % MLDATE = x2mdate(XLSDATE); 20 | % datestr(MLDATE) 21 | % 28-Oct-1995 22 | % 06-Jul-2009 23 | % 01-Apr-2012 24 | % 25 | % COMMENTS: 26 | % This is a reverse engineered clone of the MATLAB function x2mdate and should behave the same. 27 | % You only need it if you do not have the financial toolbox installed. 28 | % 29 | % See also C2MDATE 30 | 31 | 32 | % Copyright: Kevin Sheppard 33 | % kevin.sheppard@economics.ox.ac.uk 34 | % Revision: 1 Date: 10/27/2006 35 | 36 | 37 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 38 | % Input Validation 39 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 40 | if nargin==1 41 | type=0; 42 | end 43 | 44 | if any(ischar(xlsdate)) 45 | error('XLSDATE must be numeric') 46 | end 47 | 48 | if ndims('xlsdate')~=2 && min(size(type))~=1 49 | error('XLSDATE must be a T by 1 or 1 by T vector'); 50 | end 51 | 52 | if nargin>1 53 | if nargin>2 54 | error('1 or 2 inputs only'); 55 | end 56 | if min(size(type))~=1 || ndims(type)~=2 57 | error('TYPE must be either a scalar or a vector conformable to xlsdate'); 58 | end 59 | if max(size(type))~=1 60 | if max(size(type))~=max(size(xlsdate)) 61 | error('TYPE must be either a scalar or a vector conformable to xlsdate'); 62 | end 63 | end 64 | if any(~ismember(type,[0 1])) 65 | error('TYPE must be either 0 or 1.') 66 | end 67 | end 68 | 69 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 70 | % Input Validation 71 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 72 | if isscalar(type) 73 | type=type*ones(size(xlsdate)); 74 | end 75 | type = logical(type); 76 | 77 | mldate=zeros(size(xlsdate)); 78 | mldate(~type) = xlsdate(~type) + datenum('30-Dec-1899') ; 79 | mldate(type) = xlsdate(type) + datenum('1-Jan-1904') ; 80 | -------------------------------------------------------------------------------- /utility/z2r.m: -------------------------------------------------------------------------------- 1 | function R = z2r(z) 2 | % Transformation of an unconstrained K(K-1)/2 vector to a correlation matrix 3 | % 4 | % USAGE: 5 | % [R] = z2r(Z) 6 | % 7 | % INPUTS: 8 | % Z - K(K-1)/2 vector of values in (-inf,inf) 9 | % 10 | % OUTPUTS: 11 | % R - A K by K correlation matrix 12 | % 13 | % COMMENTS: 14 | % The unconstrained values are mapped to the correlaiotn matrix through: 15 | % y = 2*exp(Z)./(1+exp(Z))-1 16 | % C(i,j) = y(i,j) * sqrt(1-sum(C(i,j+1:k).^2), for i=2,...,k, j=i-1:-1:1 17 | % R = C*C' 18 | % 19 | % See also R2Z, R2PHI, PHI2R 20 | 21 | % Copyright: Kevin Sheppard 22 | % kevin.sheppard@economics.ox.ac.uk 23 | % Revision: 1 Date: 3/27/2012 24 | 25 | m = length(z); 26 | k = ceil(sqrt(2*m)); 27 | if k*(k-1)/2~=m 28 | error('Incorrect number of elements in z') 29 | end 30 | C = zeros(k); 31 | z = (exp(z)-1)./(1+exp(z)); 32 | count = 1; 33 | for i=2:k 34 | for j=1:i-1; 35 | C(i,j) = z(count); 36 | count = count + 1; 37 | end 38 | end 39 | C(1,1) = 1; 40 | for i=2:k 41 | rem = 1; 42 | for j=i-1:-1:1 43 | C(i,j) = C(i,j)*sqrt(rem); 44 | rem = rem - C(i,j)^2; 45 | end 46 | C(i,i) = sqrt(rem); 47 | end 48 | 49 | R = C*C'; 50 | r = sqrt(diag(R)); 51 | R = R ./ (r*r'); --------------------------------------------------------------------------------