% Script: ImmuneDur.m
% description: this file calculates the numbers required
% by a specific example of the lecture presentation.

disp(' The prevailing interest rate at start of investment:')
r = 0.06
disp(' Our investment goal:')
goal = 100000
disp(' The amount we have to invest at the current rate to meet our goal:')
invest = goal/(1+r)^3
disp(' The available instruments and their prices:')
bondA = [0 8 8 8 8 108]
priceA = pvvar(bondA,r)
couponA = bondA(2)
bondB = [0 106]
priceB = pvvar(bondB,r)
couponB = bondB(2)
deltar = 0.02;
disp(' Go all bond A:')
pause
finalcashA = zeros(2,1)
numbondA = invest/pvvar(bondA,r)
disp(' Suppose after one year the rate jumps 2%:')
newr = r + deltar
disp(' At end of 3 years the money weve made so far:')
moneysofar = numbondA*(couponA*((1+newr)*(1+newr) +(1+newr) + 1))
disp(' Now sell the bonds at their market price')
bondsaleprice = pvvar([0,bondA(5:6)],newr)
finalcashA(1) = moneysofar + numbondA*bondsaleprice 
disp(' Suppose after one year the rate drops 2%:')
newr = r - deltar
disp(' At end of 3 years the money weve made so far:')
moneysofar = numbondA*couponA*((1+newr)*(1+newr) +(1+newr) + 1)
disp(' Now sell the bonds at their market price')
bondsaleprice = pvvar([0,bondA(5:6)],newr)
finalcashA(2) = moneysofar + numbondA*bondsaleprice
deltagoal = finalcashA - [100000;100000]
disp(' Next, go all bond B:')
pause
finalcashB = zeros(2,1)
disp(' Suppose after one year the rate jumps 2%:')
newr = r + deltar
disp(' At end of three years we have:')
finalcashB(1)=invest*(1+r)*(1+newr)^2
disp(' Suppose after one year the rate drops 2%:')
newr = r - deltar
disp(' At end of 3 years we have:')
finalcashB(2)=invest*(1+r)*(1+newr)^2
finalcash=invest*(1+r)*(1+newr)^2
deltagoal = finalcashB - [100000;100000]
disp(' Now lets immunize the portfolio')
disp('only to extent of matching durations.')
pause
targetdur = cfdur([0 0 100000],0.06)
durA = cfdur(bondA(2:length(bondA)),0.06)
durB = cfdur(bondB(2:length(bondB)),0.06)
coef = [durA durB; 1 1]
rhs = [targetdur;1]
wts = coef \ rhs
finalcash = zeros(2,1);
finalcash(1) = wts(1)*finalcashA(1) + wts(2)*finalcashB(1);
finalcash(2) = wts(1)*finalcashA(2) + wts(2)*finalcashB(2)
% OR the quick way:
finalcash = [finalcashA,finalcashB]*wts
deltafinalcash = finalcash - [100000;100000]
