clear;
format('compact')
global solF etah kappa A delta rho targetR currente currentK sigma m phi KKK beta lambda criticalc gamma maversion policy
%policyon=0;counterfactual=0;% whether recognizing fed CPP policy and computing coutnerfactual

load  simulation_Baseline.mat;
loadedvariables  = load('simulation_Baseline_ProbCrisis.mat');
distress = loadedvariables.distress;
estartt = loadedvariables.estartt;

e0=ec;policy=0;


Cases = {'Savings and Loan Crisis',  'Corporate Bond Crisis'} ;

for i  = 1:numel(Cases)  
    if( i ==1) 
    % 1988 Savings and Loan Crisis
    Requity=[0.069522408
0.136888605
-0.113724365
-0.093849612
0.021842196
-0.284745882];
    else
    % 2001 Corporate Bond Crisis
    Requity=[-0.016646216
0.194245699
0.00798998
-0.075556629
0.068504707
-0.136422997
0.083726776
0.038448565];
    end
    
    R=Requity;
    T=numel(R);e=zeros(T,1);K=zeros(T,1);K_counterfactual=zeros(T,1);
    investment=zeros(T,1);landprice=zeros(T,1);Sharperatio=zeros(T,1);equity=zeros(T,1);consumption=zeros(T,1);crisis_prob=zeros(T,3);
    xx=zeros(T,3);dt=0.25;
    e(1)=e0;K(1)=1;K_counterfactual(1)=1;
    outcome=ils(e(1));
    investment(1)=outcome(1)*K(1);
        landprice(1)=outcome(2)*K(1);
        Sharperatio(1)=outcome(3);
        equity(1)=min((1-lambda)*(outcome(2)+outcome(4)),e(1))*K(1);
        consumption(1)=outcome(5)*K(1);
    eee=e(1);
    k=floor((eee-min(estartt))./0.1)+1;
    ww=(eee-estartt(k))./0.1;
    crisis_prob(1,:)=(1-ww)*distress(k,:)+ww*distress(k+1,:);
    dZ=zeros(T+1,1);
    for t=1:T
        %if t==6; policy=policyon*CPP; else policy=0; end;
        currente=e(t);currentK=K(t);targetR=R(t);
        dZ(t+1)=fsolve(@myfunequity,0);
        %dZ(t)=fsolve(@myfunlandprice,0);
        xx(t,:)=musigma(currente);
        e(t+1)=max(e(t)+xx(t,1)*0.25+xx(t,2)*dZ(t+1)+policy*e(t),elbarnew);
        eee=e(t+1);
    k=floor((eee-min(estartt))./0.1)+1;
    if k<=0
        crisis_prob(t+1,:)=[1 1 1];
    else
    ww=(eee-estartt(k))./0.1;
    crisis_prob(t+1,:)=(1-ww)*distress(k,:)+ww*distress(k+1,:);
    end
        K(t+1)=KKK;
        outcome=ils(e(t+1));
        investment(t+1)=outcome(1)*K(t+1);
        landprice(t+1)=outcome(2)*K(t+1);
        Sharperatio(t+1)=outcome(3);
        equity(t+1)=min((1-lambda)*(outcome(2)+outcome(4)),e(t+1))*K(t+1);
        consumption(t+1)=outcome(5)*K(t+1);
    end
    equitynorm=equity/equity(1);
    landpricenorm=landprice/landprice(1);
    investmentnorm=investment/investment(1);
    Sharperationorm=Sharperatio/Sharperatio(1);
    consumptionnorm=consumption/consumption(1);

    output=[equitynorm,investmentnorm,landpricenorm,Sharperationorm,consumptionnorm,dZ,e,K,crisis_prob];
    filename = char( strcat( Cases(i),  '.xlsx') );
    xlswrite( filename , output);
end


