楼主: tulipsliu
2269 5

[学科前沿] MATLAB SVAR model toolboxs [推广有奖]

促进中国计量经济学发展学科带头人

学科带头人

43%

还不是VIP/贵宾

-

威望
0
论坛币
386070 个
通用积分
469.6002
学术水平
127 点
热心指数
140 点
信用等级
103 点
经验
46957 点
帖子
1769
精华
0
在线时间
2483 小时
注册时间
2007-11-5
最后登录
2024-4-28

初级热心勋章

相似文件 换一批

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币

DSGE: SVAR model

Do it best ,economy and management.
中国人民大学,经济学院。
刘旭东 (Daniel tulips liu)


main (use three ` and char C print like C++ program)

main

%% SVAR: An application
% Paper: 'Identifying the interdependence between US monetary policy and
%         the stock market', Bjornland and Leitemo (2009)
% 
% *************************************************************************
%  By Alex Carrasco, november 2017
% *************************************************************************
tic
clear all; clc; close all;
boot = 1;                     % bootstrap again?
B    = 50;                   % numbers of replications [2000]
K    = 100;                   % total periods for IRF

% set up for printing figures 
% path_g = [pwd '\Graphs'];
% imprime = @(x) print( gcf, '-depsc2', [path_g filesep x]);
% imprpdf = @(x) eps2pdf( [path_g filesep x '.eps']);
formataxis  = @(x) set(x, 'Fontname', 'Times', 'FontWeight', 'normal', 'Fontsize', 23, 'Box', 'Off', 'PlotBoxAspectRatio', [1 0.75 1]);
formatlegend  = @(x) set(legend, 'Location', x, 'Orientation', 'Vertical', 'Box', 'Off', 'Fontsize', 22, 'Fontangle', 'normal');

%% [I] loading dataset and data transformation
% [a] loading
load data;
ran = se(1):47:se(end);       % range for plots [do not change!]
m=size(DD,2);

% [b] unit root tests
UR=uroottest(DD,'report','ur_test','names',var_names,'alpha',0.05); % creates a table with test results

% [c] plotting data
cc=1;

for ii=1:m
    figure(cc);
    h=plot(se,DD(:,ii),'-','linewidth',2.5); axis tight;   
    set(h,'color',[0 0 0.5]);
    x=gca;
    set(x,'xtick',ran,'xticklabel',ranlab);
    formataxis(x);
%     imprime([cod_names{ii} '_data']);
%     imprpdf([cod_names{ii} '_data']);
    cc=cc+1;
end

%% [II] Model selection, p: FPE, AIC, BIC, HQ
pmax=8;
[popt,ic]=VAROptLag(DD,pmax);
fprintf('\n Optimal lags: %1.0f %1.0f %1.0f %1.0f\n', popt);

%% [III] Reduced form estimation: VAR(p) 
p = popt(3);     % BIC optimal lag

% [a] Baseline model
[Chat,Shat,F,Theta]=VARest(DD,p);

% [b] Alternative model
DD(:,[4 5])=DD(:,[5 4]);
[Chata,Shata,Fa]=VARest(DD,p);

DD(:,[4 5])=DD(:,[5 4]);

P = chol(Shat);                  % Cholesky decomposition (baseline)
Pa = chol(Shata);                % Cholesky decomposition (alternative)           

%% [IV] A-model, identification and estimation
% RA is the restriction matrix
A = nan(m,m);
% [a] Zero restrictions
A(1,2:5) = 0; A(2,3:5)=0; A(3,4:5)=0;

free_param = isnan(A);
nfree      = sum(vec(free_param));

ind0 = reshape(1:m^2,m,m);
ind0 = ind0(free_param);

RA = zeros(m^2,nfree);
[I,J] = ind2sub([m,m],ind0);
for k=1:nfree
    RA((J(k)-1)*m+I(k),k)=1;
end

% [b] Long-run restriction
RA(m^2,m*(m+1)/2)=-Theta(4,4)/Theta(4,5);
RA(:,m*(m+1)/2+1)=[];

% [c] Estimation: 
%  Based on Amisano and Gianini (1997)/ Marquardt algorithm (Baseline ordenation)
gamma0=.8*ones(nfree-1,1); gamma0(nfree-1)=-gamma0(nfree-1); % Sign restriction
[gammaA,logL,error,S]=mlSVAR(RA,gamma0,Shat,T,'tau',0.3,'errotol_score',1e-7,'errortol_grad',1e-7);
A=reshape(RA*gammaA,m,m);

%% [V] IRF [mean]
% [a] Structural identifcation
IR=VARimpulse(F,A,K); % mean responses in structural identifcation

% [b] Models identificated with recursive restrictions
Kmax = 46;        % toplot
x =(1:Kmax)';
sh = [5 4];       % shocks: i/Ds \\ Ds/i
resp = [5 4];     % shocks: i/Ds \\ Ds/i
IRchol1 =VARimpulse(F,P',K);    % IRF using baseline order
IRchol2 =VARimpulse(Fa,Pa',K);  % IRF using alternative order

for ss=1:numel(sh)
    for vv=1:numel(resp)
        figure(cc);
        irf1 = IRchol1(resp(vv),:,sh(ss))'/IRchol1(sh(ss),1,sh(ss));  % normalizing responses
        irf2 = IRchol2(resp(resp(vv)~=resp),:,sh(sh(ss)~=sh))'/IRchol2(sh(sh(ss)~=sh),1,sh(sh(ss)~=sh));
        if resp(vv)==4
            irf1=cumsum(irf1);
            irf2=cumsum(irf2);
        end
        irf1=irf1(x); irf2=irf2(x); 
        
        h=plot([irf1,irf2]); hold on;
        plot([1 Kmax],[0 0],':k');
        set(h(1),'color',[0 0 .5],'linewidth',3);
        set(h(2),'color',[0 0 .5],'linestyle','--','linewidth',2);
        
        % axis
        axs=gca; miny=min(min([irf1,irf2])); maxy=max(max([irf1,irf2])); 
        xlim([1 Kmax]); 
        ylim([min(miny,0)*1.2 maxy*1.2]);
        set(axs,'xtick',6:5:Kmax,'Xticklabel',5:5:Kmax-1);
        xlabel('Months','fontname','Times','FontWeight', 'normal', 'Fontsize', 22); 
        ylabel('Percent','fontname','Times','FontWeight', 'normal', 'Fontsize', 22);
        formataxis(axs);
        if resp(vv)==5
            lg=legend('Baseline','Alterntive');        
            formatlegend('NorthEast');
        end
            
%         imprime(['IRFChol_' cod_names{resp(vv)} '_' cod_names{sh(ss)}]);
%         imprpdf(['IRFChol_' cod_names{resp(vv)} '_' cod_names{sh(ss)}]);
        cc=cc+1;
    end
end

%% [VI] Standard errors [Bootstraping]
if boot                             
    [bhat,Omg]=VAR_boots(DD,'order',p,'n_replic',B,'burnin',20,'wild');
    [T,m]=size(DD);
    
    fprintf('\n Estimating bootstrap sample ... '); kk=1;    
    IRb = [];   
    for b=1:B
        if b==floor(kk*B/10)
            fprintf('%1.0f ',kk);
            kk=kk+1;
        end
        beta  = bhat(:,b);
        BET   = reshape(beta,m,[]);
        Sb    = Omg(:,:,b);        
        F = [BET(:,2:end);...
            [kron(eye(p-1,p-1),eye(m,m)), zeros(m*(p-1),m)]];
        eigen = eig(F);          
        if ~any(abs(eigen)>1)   % is stable?
            LR    =  inv(eye(m)-BET(:,2:m+1)-BET(:,m+2:2*m+1));
            % Long-run restriction
            RA(m^2,m*(m+1)/2) = -LR(4,4)/LR(4,5); 
            gammaAb = mlSVAR(RA,gamma0,Sb,T,'tau',.3, ...
                    'errotol_score',1e-4,'errortol_grad',1e-6,'quiet');    
            Ab     = reshape(RA*gammaAb,m,m);        
            IRb(:,:,:,b) = VARimpulse(F,Ab,K);
        end
    end
    fprintf(', done!\n');

    save SVAR_irf IR IRb DD var_names B
else
    load SVAR_irf
end

%% [VII] Plotting IRFs based on structural identification
Kmax = 46;
x  = (1:Kmax)';
ll=0.16;
uu=0.84;

sh = [5 4];             % i / Ds
resp   = [5 4 2 1];     % i/Ds/pi/y
for ss=1:numel(sh)
    for vv=1:numel(resp)
        posit = 'NorthEast';
        tempb=squeeze(IRb(resp(vv),:,sh(ss),:));
        % normalizing
        aux = ones(K+1,1)*squeeze(IRb(sh(ss),1,sh(ss),:))';
        tempb=tempb./aux;
        irf = IR(resp(vv),:,sh(ss))'/IR(sh(ss),1,sh(ss));
        if resp(vv)~=4;
            irfb   = quantile(tempb,.5,2);
            irfb_l = quantile(tempb,ll,2);
            irfb_u = quantile(tempb,uu,2);
        else
            irfb = quantile(cumsum(tempb),.5,2);
            irfb_l = quantile(cumsum(tempb),ll,2);
            irfb_u = quantile(cumsum(tempb),uu,2);
        end
        irf = irf(x);
        irfb=irfb(x); irfb_l=irfb_l(x); irfb_u=irfb_u(x);
        miny=min(irfb_l);
        maxy=max(irfb_u); 
        
        figure(cc); hold on;
        dif = irfb_u-irfb_l;
        a = area([irfb_l dif],-15);
        h=plot(x, irfb);
        plot([1 K],[0 0],':k');
        set(a(1), 'EdgeColor', 'none', 'FaceColor', 'none');
        set(a(2), 'EdgeColor', 'none', 'FaceColor', [0.65 0.65 1]);
        set(h, 'Linewidth', 2.5, 'Color', [0 0 0.5]); 
        % axis
        axs=gca;     
        ylim([min(miny,0)*1.2 maxy*1.2]);
        set(axs,'xtick',1:5:Kmax,'Xticklabel',0:5:Kmax-1);
        xlabel('Months','fontname','Times','FontWeight', 'normal', 'Fontsize', 22); 
        ylabel('Percent','fontname','Times','FontWeight', 'normal', 'Fontsize', 22);
        formataxis(axs);
        xlim([0 Kmax+1]);
        if resp(vv)==5
            % legend only for one subplot
            legend([h;a(2)],'IRF',['Percentiles [' num2str(ll) ' - ' num2str(uu) ']']);        
            formatlegend(posit);
        end
%         imprime(['IRF' cod_names{resp(vv)} '_' cod_names{sh(ss)}]);
%         imprpdf(['IRF' cod_names{resp(vv)} '_' cod_names{sh(ss)}]);
        cc=cc+1;
    end
end
toc
%% Extra [Model selection table]
fprintf('\n');
for ii=1:size(ic,1)
fprintf('$%2.0f$ & $%2.4f$ & $%2.4f$ & $%2.4f$ & $%2.4f$ \\\\ \n',ii,ic(ii,:))
end

LATEX file (but has wrong problem can not compile)

report.tex file

\documentclass[12pt]{article}
\usepackage[margin=2cm]{geometry}
\usepackage{psfrag}
\usepackage{graphicx}
\usepackage{epstopdf}
\usepackage{longtable,booktabs}
\usepackage{amsmath,amsfonts}
\usepackage{breqn}
\usepackage{float,morefloats,caption}
\begin{document}
\hspace*{+0.2cm} \begin{tabular}{lcccccccc}
\toprule
\multirow{3}[3]{*}{\textsc{\textbf{Variable}}}& \multicolumn{ 4}{c}{\textsc{\textbf{adf}}}& \multicolumn{ 4}{c}{\textsc{\textbf{pp}}}\\
\cmidrule(lr){2-5}\cmidrule(lr){6-9}& \multicolumn{2}{c}{\textsf{ard}}& \multicolumn{2}{c}{\textsf{ts}}& \multicolumn{2}{c}{\textsf{ard}}& \multicolumn{2}{c}{\textsf{ts}}\\
\cmidrule(lr){2-3}\cmidrule(lr){4-5}\cmidrule(lr){6-7}\cmidrule(lr){8-9} & \textit{Reject \textsc{H}_0?} & \textit{Lag} & \textit{Reject \textsc{H}_0?} & \textit{Lag} & \textit{Reject \textsc{H}_0?} & \textit{Lag} & \textit{Reject \textsc{H}_0?} & \textit{Lag} \\
\midrule
\textit{Output (HP cycle)}  &  1 &  8 &  1 &  8 &  1 &  0 &  1 &  0\\
\textit{Inflation}  &  1 &  1 &  1 &  4 &  0 &  0 &  0 &  0\\
\textit{Commodity inflation}  &  1 &  8 &  1 &  8 &  1 &  1 &  1 &  3\\
\textit{Real stock prices}  &  1 &  8 &  1 &  8 &  1 &  0 &  1 &  0\\
\textit{Interest rate}  &  0 &  4 &  1 &  1 &  0 &  0 &  0 &  0\\
\bottomrule
\end{tabular} \hspace*{+0.2cm}
\end{document) 

download file after this paper

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:toolbox MATLAB matla atlab model

劳动经济学
沙发
tulipsliu 在职认证  发表于 2020-6-7 13:29:32 |只看作者 |坛友微信交流群
有***蒙特卡洛*** 模拟程序,
也有单独的文件夹是做 SVAR模型的。
其中也有对单位根的
$% [b] unit root tests$

enjoy ,
       yours daniel tulips liu

Econometric-methods-master.zip

4.06 MB

需要: 1 个论坛币  [购买]

蒙特卡洛模拟和SVAR模型

使用道具

藤椅
tulipsliu 在职认证  发表于 2020-6-7 15:43:59 |只看作者 |坛友微信交流群
没论坛币的发电子邮箱索取: xudongliu520@vip.qq.com

[titter][titter]

我下载资料下破产了。哈哈

使用道具

板凳
zhaochuan2 学生认证  发表于 2020-9-16 21:12:37 |只看作者 |坛友微信交流群
不会C语言  没法支持你了

使用道具

报纸
tulipsliu 在职认证  发表于 2020-9-26 11:07:46 |只看作者 |坛友微信交流群
zhaochuan2 发表于 2020-9-16 21:12
不会C语言  没法支持你了
没事的,不过国内如果要学习高性能计算。 不论是R 使用金融计量工具包。
比如我举例, rugarch 作者的  rolling windows 的滚动窗口方法计算资产组合的 VaR ,并计算他们的 kupiec等,计算量很大。  C 语言的速度是 R 语言的100倍;

作者的 rugarch 工具包用的就是C 语言写。  同样MATLAB 其实已经很快,但是也没C语言快。
DSGE 计算里, 国际的 dynare 是通过 C++ 开发的;  有的国际的不通过dynare 写的动态宏观经济学模型,要么是通过 FORTRAN 高级语言来写,然后编译为可执行的二进制文件,也就是后缀名为 .exe 的文件。我过段时间上传一个国际的编译了FORTRAN 语言的,被MATLAB 调用的 .exe 可执行文件。部分是MATLAB 带啊名,调用FORTRAN 编译后的 .exe 文件;

另外 dynare 其实可以很快,不过当前国际上做宏观经济学动态模型越来越大。所以计算越来越复杂。只好通过安装编译器,编译 C语言代码。

我以后会教学,怎么编译 mex 文件(C语言源代码文件,通过 MinGW 64-bit 编译器,编译为 .mexw64 文件)。

使用道具

地板
吕he 发表于 2023-12-14 19:16:42 来自手机 |只看作者 |坛友微信交流群

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-28 13:24