%% Obtain Callable Bond Exercise Information Using a CIR Interest-Rate Tree Model
% Create a CIRTree with the following data:

Rates = [0.025; 0.027; 0.028; 0.03]; 
Dates = {'Jan-1-2017'; 'Jan-1-2018'; 'Jan-1-2019'; 'Jan-1-2020'; 'Jan-1-2021'}; 
ValuationDate = 'Jan-1-2017'; 
EndDates = Dates(2:end)'; 
Compounding = 1; 

%
% Create a RateSpec.

RateSpec = intenvset('ValuationDate', ValuationDate, 'StartDates', ValuationDate, 'EndDates',EndDates,...
'Rates', Rates, 'Compounding', Compounding);

%
% Build the CIR tree with the following data.

NumPeriods = length(EndDates); 
Alpha = 0.03; 
Theta = 0.02;  
Sigma = 0.1;
Maturity = '01-Jan-2018'; 
CIRTimeSpec = cirtimespec(ValuationDate, Maturity, NumPeriods); 
CIRVolSpec = cirvolspec(Sigma, Alpha, Theta); 
CIRT = cirtree(CIRVolSpec, RateSpec, CIRTimeSpec);

%
% Define the callable bond instruments.

Settle = '01-Jan-2017';
Maturity = {'01-Jan-2018';'01-Jan-2020'};
CouponRate = {{'01-Jan-2019' .0325;'01-Jan-2020' .0375}};  
OptSpec='call';
Strike= [100;110];
ExerciseDates= {'01-Jan-2018';'01-Jan-2020'};

% Price the instruments.

[Price, PriceTree]= optembndbycir(CIRT, CouponRate,  Settle, Maturity, OptSpec, Strike,...
ExerciseDates, 'Period', 1,'AmericanOpt',1)

% Examine the output PriceTree.ExTree. PriceTree.ExTree contains the exercise indicator arrays. Each element of the cell array is an array containing 1's where an option is exercised and 0's where it is not.

PriceTree.ExTree{4} 

% There is no exercise for instrument 1 or instrument 2.

PriceTree.ExTree{3} 

% There is no exercise for instrument 1 or instrument 2.

PriceTree.ExTree{2} 

% There is exercise for instrument 1 or instrument 2.
% Next view the probability of reaching each node from the root node using PriceTree.ProbTree.

PriceTree.ProbTree{2}
PriceTree.ProbTree{3}
PriceTree.ProbTree{4}

% Then view the exercise probabilities using PriceTree.ExProbTree. PriceTree.ExProbTree contains the exercise probabilities. Each element in the cell array is an array containing 0's where there is no exercise, or the probability of reaching that node where exercise happens.

PriceTree.ExProbTree{4}
PriceTree.ExProbTree{3}
PriceTree.ExProbTree{2}

% View the exercise probabilities at each tree level using PriceTree.ExProbsByTreeLevel. PriceTree.ExProbsByTreeLevel is an array with each row holding the exercise probability for a given option at each tree observation time.

PriceTree.ExProbsByTreeLevel

% Copyright 2019 The MathWorks, Inc.