%% Multi-Period Loans, One-Period Loans, Roll-over Loans, Bridge Loans
% *<https://fanwangecon.github.io/ThaiForInfLuuRobFan/ Go back to LuuRobFan 
% Project Main Page>*
% 
% This file discusses the role of bridge loan in improving consumption smoothing 
% when only one period loans with roll-over is allowed in a 3 period deterministic 
% model with fixed but unevenly distributed endowment. Development banks could 
% be offering these one-period loans without roll-over, and informal lenders could 
% be offering bridge loans. Informal loans with higher interest rates co-exist 
% with formal loans in this environment. 
% 
% Note that this is a context without default. Households always pay back 
% their debts. 
%% Optimal Choices in a Three Period Model With Fixed Endowments
% Suppose there are three periods, there are fixed endowments in each period:
% 
% * $\textbf{e} = \left\{ e_1, e_2, e_3 \right\}$
% * $e_1 = 0$
% * $e_2 = 1$
% * $e_3 = 8$
% 
% What is the standard budget constraint we write down for this problem and 
% what does it imply for the length of loan? Let's abstract away from interest 
% rate and discount, $\beta = 1$, and $r=0$. With log utility, we have:
% 
% $$\max_{b_2, b_3} \log(c_1) + \log(c_2) + \log(c_3)$$
% 
% such that: $c_1 + b_2 = e_1$, $c_2 + b_3 = e_2 + b_2$, and $c_3 = e_3 + 
% b_3$
% 
% the implied non-binding _natural borrowing constraints_ are: $b_2 > -1\cdot 
% \left( e_2 + e_3\right)$ and, $b_3 > -1\cdot \left( e_3\right)$
% 
% Combining the budgets together:
% 
% $$c_1 + c_2 + c_3 = e_1 + e_2 + e_3$$
% 
% Endowments over the three periods can be shared across the three periods, 
% optimal choices are:
% 
% $$b_2^{*}=-3, b_3^{*}=-5$$
% 
% $$c_1^{*}=c_2^{*}=c_3^{*}=\frac{0+1+8}{3}=3$$
%% Multi-Period Loan and One-Period Loan with Roll-over
% The standard budget constraint that we write down as shown above describes 
% short-term loans that allow for roll-overs. One-Period loan with roll-over in 
% this case achieves the same smoothing as Multi-Period loan + savings. In both 
% cases, we get the optimal choices as shown above.
% 
% * _*Multi-Period Loan_*:_* _*If borrowing in the 1st period is due in the 
% 3rd period, that is a multi-period loan.
% * _*One-Period Loan_*: Borrowing in $t$ is due in $t+1$
% * _*Roll-over_*: You are allowed to repay existing debt with new debt. 
% 
% _*Smoothing using Multi-Period Loan and savings*:_
% 
% Multi-Period borrowing + savings achieves consumption smoothing (with $b$ 
% denoting just borrowing, and $s$ just savings):
% 
% $c_1 + b_2 + s_2 = e_1$, $c_2 + b_3 + s_3 = e_2 + b_2 + s_2$, and $c_3 
% = e_3 + b_3 + s_3$
% 
% # In the first period, borrow $5$ units of Multi-Period loan and save 1 unit: 
% $b_2 = -5$, $s_2 = 2$
% # In the second period, carry $5$ units of Multi-Period loan debt to 3rd period: 
% $b_3 = -5$, $s_3 = 0$
% # pay off $5$ unit Multi-Period debt in the 3rd period
% 
% _*Smoothing using One-Period loan with Roll-overs:*_
% 
% This is implicitly what the standard budget constraint above allows for:
% 
% $c_1 + b_2 = e_1$, $c_2 + b_3 = e_2 + b_2$, and $c_3 = e_3 + b_3$
% 
% # borrow 3 units of One-Period loan in $t=1$: $b_2 = -3$
% # borrow 5 units of One-Period loan in $t=2$ to repay $b_2=-3$ debt and add 
% 2 units to $c_2$ consumption: $b_3 = -5$
% # pay off 5 units of One-Period loan in $t=3$
%% *One-Period Loan without Roll-over*
% The budget constraints when we have no-roll-over one-period loans is the same 
% as before:
% 
% _We still have_: $c_1 + b_2 = e_1$, $c_2 + b_3 = e_2 + b_2$, and $c_3 = 
% e_3 + b_3$
% 
% but now we have these borrowing constraints:
% 
% $b_2 \ge -e_2$, and $b_3 \ge - e_3$
% 
% Households still face the same natural borrowing constraint as before, 
% but they now face the tigether constraint imposed by the bank that requires 
% principal repayments before new loans are issued. These bank short-term repayment 
% constraints could bind. In our example here, households only have $e_2=1$, limiting 
% their borrowing to below this level, but they want to move $3$ units over to 
% first period for consumption. 
% 
% Optimal choices now with no-roll-over one-period loan is:
% 
% $$b_2^{*}=-1, b_3^{*}=-4$$
% 
% $c_1^{*}=1$, $c_2^{*}=4$, $c_3^{*}=4$
% 
% Smoothing between the three periods is no longer achieved. 
%% *Bridge Loan*
% It is common for banks to issue one year loans which require the repayment 
% of principles and interest rates after 12 months. 12 month could be a model 
% period, so what could households do to improve smoothing?
% 
% Suppose there is a high interest rate (informal) lender: $r_{\text{B}}=0.75$, 
% $75$ percent interest rate. This lender is unconcerned about lending to a household 
% with outstanding loans. This informal lender $B$ could lend a little bit to 
% the borrower, to help the borrower bridge over and pay for the existing debt 
% from formal bank $A$, which offers lower interest rates loans. Informal lender 
% $B$ is willing to issue new debt before borrower has paid off their existing 
% interests + principles.
% 
% Our budgets now are:
% 
% $$c_1 + b^A_2 + b^B_2 = e_1$$
% 
% $$c_2 + b^A_3 + b^B_3 = e_2 + b^A_2 + b^B_2 \cdot (1+r_{\text{B}})$$
% 
% $$c_3 = e_3 + b^A_3 + b^B_3 \cdot (1+r_{\text{B}})$$
% 
% And the borrowing constraints are: 
% 
% debt is less than endowment and new $B$ borrowing: $b^A_2 + b^B_2 \cdot 
% (1+r_{\text{B}}) \ge -e_2 + b^B_3$
% 
% and $b^A_3 + b^B_3 \cdot (1+r_{\text{B}}) \ge - e_3$
%% Optimization With Bridge Loan
% Given that loan type $B$ is a lot more expensive than $A$, you will only use 
% it for bridge-loan purposes, and will not choose to borrow from source $B$ in 
% the first period. Additionally, we also know eactly how much you will borrow 
% from source $B$, you will only borrow exactly enough to cover you unpaid principle 
% from borrowing $b^A_2$ given $e_2$. What these mean is that we can write down 
% the following: 
% 
% $$c_1 + b^A_2 = e_1$$
% 
% $$c_2 + b^A_3 + b^B_3 = e_2 + b^A_2$$
% 
% $$e_2 + b^A_2 - b^B_3 = 0$$
% 
% $$c_3 = e_3 + b^A_3 + b^B_3 \cdot (1+r_{\text{B}})$$
% 
% Jointly, what these imply is a new aggregate budget constraint given which 
% we can solve the maximization problem with bridge loans:
% 
% $$\max_{b_2, b_3} \log(c_1) + \log(c_2) + \log(c_3)$$
% 
% $$c_1\cdot(1+r_B) + c_2 + c_3 = e_2 \cdot (1+r_B) + e_3$$
% 
% with $r^B=0.75$, we now achieve better smoothing than when bridge loans 
% are not available:
% 
% $$b_2^{A,*}=-1.86, b_3^{B,*}=-0.86,  b_3^{A,*}=-3.25$$
% 
% $c_1^{*}=1.86$, $c_2^{*}=3.25$, $c_3^{*}=3.25$
%%
% Variables and Parmaeters
syms c1 c2 c3 r e2 e3 lambda
r_num = 0.75; % r_num = 0.75, then bridge loan demand = 0
e2_num = 1;
e3_num  = 8;

% Lagrangian
lagrangian = log(c1) + log(c2) + log(c3) - lambda*(e2*(1+r) + e3 - c1*(1+r) - c2 - c3);
% Analytical Solutions
solu_max = solve(diff(lagrangian, c1)==0,...    
                 diff(lagrangian, c2)==0,...
                 diff(lagrangian, c3)==0,...
                 diff(lagrangian, lambda)==0,...
                 c1, c2, c3, lambda,...
                 'Real', true);
solu_c1 = solu_max.c1
solu_c2 = solu_max.c2
solu_c3 = solu_max.c3
% Numerical Solutions
opti_c1 = double(subs(solu_c1, {r, e2, e3}, {r_num, e2_num, e3_num}));
opti_c2 = double(subs(solu_c2, {r, e2, e3}, {r_num, e2_num, e3_num}));
opti_c3 = double(subs(solu_c3, {r, e2, e3}, {r_num, e2_num, e3_num}));
% First period borrowing fully finances c1 consumption, only borrow from source A with 0 interest
opti_bA_t2 = double(-opti_c1);
% Second period borrowing first borrow from bridge loan to fill gap
opti_bB_t3 = double(opti_bA_t2 + e2_num);
% Second period consumption fully financial by borrowing from source A wiht 0 interest.
opti_bA_t3 = double(-opti_c2);
% Display results
outcomes_bridge = table(opti_c1, opti_c2, opti_c3, opti_bA_t2, opti_bB_t3, opti_bA_t3);
disp(table(opti_c1, opti_c2, opti_c3, opti_bA_t2, opti_bB_t3, opti_bA_t3));
%% Wealth Recovery from Bridge Loan with No-Roll-Over One Period Loans
% We have these three cases:
% 
% # Multi-Period loan (borrow + save) or One-Period loan with roll-over: $c_1^{*}=c_2^{*}=c_3^{*}=3$
% # One-Period loan without roll-over: $c_1^{*}=1$, $c_2^{*}=4$, $c_3^{*}=4$
% # By allowing for bridge loan, we can move from the second world of imperfect 
% smoothing towards the first world of perfect smoothing.
% 
% If $r_B=0$, then we are back to perfect smoothing, given the endowment 
% sequence here, if $r_B = 3.00$, which is $300$ percent interest rate, bridge 
% loan demand is zero, and we are back to the no-roll-over One-Period loan world. 
% With bridge loan, very high interest rate informal loans can co-exist with very 
% low interest rate formal loans.
% 
% Solving the expenditure minimization problem, we can solve for the wealth 
% loss due to not allowing for roll-over, and the wealth recovery achieved when 
% bridge loans are possible. The recovery varies depending on interest rate. 
% 
% *1. First define Parameters:*
%%
% Total wealth avaialble
e1 = 0;
e2 = 1;
e3 = 8;
e_total = e1 + e2 + e3;

% Loop over variations in interest rates of the bridge loan
r_min = 0; % no better than main/formal loan r
r_max = 3; % if higher than this, want to save
bridge_loan_r_vector = linspace(r_min, r_max, 100);
%% 
% *2. Utility Maximization and Expenditure Minimization*

% Symbols
syms c1 c2 c3 lambda

% Utility Function
UTIL = log(c1) + log(c2) + log(c3);

% Lagrangian for Utility Maximization with Bridge Loan
lagrangian = UTIL - lambda*(e2*(1+r) + e3 - c1*(1+r) - c2 - c3);
% Analytical Solutions
solu_max = solve(diff(lagrangian, c1)==0,...    
                 diff(lagrangian, c2)==0,...
                 diff(lagrangian, c3)==0,...
                 diff(lagrangian, lambda)==0,...
                 c1, c2, c3, lambda,...
                 'Real', true);
solu_c1 = solu_max.c1;
solu_c2 = solu_max.c2;
solu_c3 = solu_max.c3;

syms util
% Lagrangian for the unconstrained original Expenditure Minimization problem
lagrangian = (c1 + c2 + c3 - lambda*(log(c1) + log(c2) + log(c3) - util));
% Expenditure Minimization Solutions
solu_min = solve(diff(lagrangian, c1)==0,...
                 diff(lagrangian, c2)==0,...
                 diff(lagrangian, c3)==0,...
                 diff(lagrangian, lambda)==0,...
                 c1, c2, c3, lambda,...
                 'Real', true);
solu_min_c1 = solu_min.c1;
solu_min_c2 = solu_min.c2;
solu_min_c3 = solu_min.c3;
f_total_budget = solu_min_c1 + solu_min_c2 + solu_min_c3;
%% 
% *3. Loop Over Interest Rates*

% Solution over interest rate
value_vec = zeros(size(bridge_loan_r_vector));
bridge_frac_b_vec = zeros(size(bridge_loan_r_vector));
total_b_vec = zeros(size(bridge_loan_r_vector));
c1_o_vec = zeros(size(bridge_loan_r_vector));
c2_o_vec = zeros(size(bridge_loan_r_vector));
for bridge_r_ctr=1:length(bridge_loan_r_vector)
    bridge_r = bridge_loan_r_vector(bridge_r_ctr);
    
    % Optimal choices given interest rate
    c1_o = double(subs(solu_c1, {r}, {bridge_r}));
    c2_o = double(subs(solu_c2, {r}, {bridge_r}));
    c3_o = double(subs(solu_c3, {r}, {bridge_r}));
    
    % Store Util at optimal choices
    value_vec(bridge_r_ctr) = double(subs(UTIL, {c1,c2,c3}, {c1_o, c2_o, c3_o}));
    
    % Store Bridge Loan Choices to cover short fall as a fraction of total second period borrowing
    % Consider principle + interest 
    % e2 - c1_o is bridge loan amount, because c1_o = b2.
    % And since all e2 is used to repay loans, c2_o is regular loan second period borrowing.
    bridge_frac_b_vec(bridge_r_ctr) = (abs(e2 - c1_o))/(abs(e2 - c1_o) + abs(c2_o));
    total_b_vec(bridge_r_ctr) = (e2 - c1_o) -(c2_o);
    
    % Optimal consuption choices for t1 and t2
    c1_o_vec(bridge_r_ctr) = c1_o;
    c2_o_vec(bridge_r_ctr) = c2_o;
end
%% *Graphing the Effects of Bridge Loans with Varying Interest Rates*
% Two graphs below, first wealth loss recovery achieved by using bridge loans, 
% and then consumption in the three periods with bridge loan given different interest 
% rates.
% 
% * Without bridge loan, 16% wealth loss (from exp. min.) due to having no-roll-over 
% one-period loans compared to perfect smoothing which is achieved by roll-over 
% loans.
% * If bridge loans are available, no-roll-over one-period + bridge loan moves 
% consumption much closer to perfect smoothing achieved by roll-over loans.
% * If informal bridge loan interest rate is the same as no-roll-over one period 
% formal loan, perfect smoothing is achieved.
% * Bridge loan helps to improve consumption smoothing, given the parameters 
% here, as long as its interest rate is below $300$ percent.
%%
% Budget Cost to Achieve the utility vector given varying bridge loan Interests
budget_vec = double(subs(f_total_budget, {util}, {value_vec}));

% Plot Margins
r_graph_margin = (r_max - r_min)/10;
r_graph_max = r_max + r_graph_margin;
r_graph_min = r_min - r_graph_margin;
x_title_line = ['(Informal) Bridge Loan Interest Rate, 1 = 100%'];

% wealth loss Plot
figure();
subplot(1,2,1);
hold on;
% wealth loss share compared to if roll-over loans are allowed
inc_loss = (budget_vec/e_total - 1)*100;
% Plot
plot(bridge_loan_r_vector, inc_loss);
% graph x and y limits
iloss_margin = (0 - min(inc_loss))/10;
iloss_graph_max = 0 + iloss_margin;
iloss_graph_min = min(inc_loss) - iloss_margin;
xlim([r_graph_min r_graph_max]);
ylim([iloss_graph_min iloss_graph_max]);
% Extra Lines
plot(0*ones(1,10), linspace(iloss_graph_min, iloss_graph_max,10), 'k-', 'LineWidth', 1);
% Labels
title({['% Wealth Loss vs. Full Smoothing'], ['Bridge + no-roll-over Formal Loans'],...
       ['e1 = ' num2str(e1)...
        ', e2 = ' num2str(e2) ...
        ', e3 = ' num2str(e3) ]});
xlabel(x_title_line);
ylabel({['Exp. Min. % Wealth Loss'] ['vs. Perfect Smoothing']});
% grids
grid on;
grid minor;

subplot(1,2,2);
hold on;
plot(bridge_loan_r_vector, bridge_frac_b_vec);
% graph x and y limits
brdgfrac_margin = (max(bridge_frac_b_vec) - 0)/10;
brdgfrac_graph_max = max(bridge_frac_b_vec) + brdgfrac_margin;
brdgfrac_graph_min = 0 - brdgfrac_margin;
xlim([r_graph_min r_graph_max]);
ylim([brdgfrac_graph_min brdgfrac_graph_max]);
% Extra Lines
plot(0*ones(1,10), linspace(brdgfrac_graph_min, brdgfrac_graph_max,10), 'k-', 'LineWidth', 1);
plot(linspace(r_graph_min, r_graph_max, 10), ones(10) * 0, 'k-', 'LineWidth', 1);
% Labels
title({['Fraction of Bridge Loan in Total Loans'], ['Bridge + no-roll-over Formal Loans'],...
       ['e1 = ' num2str(e1)...
        ', e2 = ' num2str(e2) ...
        ', e3 = ' num2str(e3) ]});
xlabel(x_title_line);
ylabel({['Bridge Loan Share'] ['of Total Loans']});
% grids
grid on;
grid minor;
figure();
hold on;
plot(bridge_loan_r_vector, c1_o_vec);
plot(bridge_loan_r_vector, c2_o_vec);
% graph x and y limits
c12_max = max([c1_o_vec c2_o_vec]);
c12_min = min([c1_o_vec c2_o_vec]);
c12_margin = (c12_max - c12_min)/10;
c12_graph_max = max([c1_o_vec c2_o_vec]) + c12_margin;
c12_graph_min = min([c1_o_vec c2_o_vec]) - c12_margin;
xlim([r_graph_min r_graph_max]);
ylim([c12_graph_min c12_graph_max]);
% Extra Lines
plot(linspace(r_graph_min, r_graph_max, 10), ones(10) * 3, 'k:');
plot(linspace(r_graph_min, r_graph_max, 10), ones(10) * 4, 'k--');
plot(linspace(r_graph_min, r_graph_max, 10), ones(10) * 1, 'k--');
plot(0*ones(1,10), linspace(c12_graph_min, c12_graph_max,10), 'k-', 'LineWidth', 1);
% Labels
title({['Consumption with Bridge + No-Roll-Over Formal Loans'],...
       ['e1 = ' num2str(e1)...
        ', e2 = ' num2str(e2) ...
        ', e3 = ' num2str(e3) ', one period no-rollover loan r = ' num2str(0)],...
       ['c=3 is perfect smoothing']});
xlabel(x_title_line);
ylabel('Consumption');
legend({['consumption at t=1'],...
        ['consumption at t=2 and t=3']...
        }, 'Location', 'east')            
% grids
grid on;
grid minor;