function YTM = stepcpnyield(Price, Settle, Maturity, ConvDates, CouponRates, ...
    varargin)
%STEPCPNYIELD Yield-to-Maturity of stepped-coupon bonds.
%   Calculates yields on NSTP stepped-coupon bonds over NCONV conversion dates.
%
%   YTM = stepcpnyield(Price, Settle, Maturity, ConvDates, CouponRates)
%   YTM = stepcpnyield(Price, Settle, Maturity, ConvDates, CouponRates, ...
%      Period)
%   YTM = stepcpnyield(Price, Settle, Maturity, ConvDates, CouponRates, ...
%      Period, Basis)
%   YTM = stepcpnyield(Price, Settle, Maturity, ConvDates, CouponRates, ...
%      Period, Basis, EndMonthRule)
%   YTM = stepcpnyield(Price, Settle, Maturity, ConvDates, CouponRates, ...
%      Period, Basis, EndMonthRule, Face)
%
%   Optional Inputs: Period, Basis, EndMonthRule, Face
%
%   Inputs:
%            Price - NSTPx1 vector of clean prices of the stepped coupon
%                    bonds.
%
%           Settle - NSTPx1 vector of settlement dates of the bonds in
%                    serial dates.
%
%         Maturity - NSTPx1 maturity dates for each bond in the portfolio.
%
%        ConvDates - Matrix(*) of NSTP x max(NCONV) containing conversion
%                    dates AFTER Settle.
%
%      CouponRates - Matrix(*) of NSTP x max(NCONV+1) containing coupon
%                    rates for each bond in the portfolio in decimal form.
%                    First column of this matrix contains rates applicable
%                    between Settle and dates in the first column of
%                    ConvDates.
%
%     (*)ConvDates MUST HAVE 1 (one) less column than CouponRates.
%        A diagram to illustrate the above description:
%
%       Settle-----------ConvDate1------------ConvDate2-----------Maturity
%               CpnRate1            CpnRate2             CpnRate3
%
%     If first column of ConvDates, ConvDate1, equals Settle, then CpnRate1
%     will have NO effect. At the event that there is bond with different
%     number of conversion dates, the shorter schedule will need to be
%     padded with NaN.
%
%   Optional Inputs:
%           Period - NSTPx1 vector of coupon payments frequency per year in
%                    integer form;
%                     0 - zero coupon payments
%                     1 - annual coupon payments
%                     2 - semi-annual coupon payments  (default)
%                     3 - three coupon payments per year
%                     4 - quarterly coupon payments
%                     6 - semi-monthly coupon payments
%                    12 - monthly coupon payments
%
%            Basis - NSTPx1 vector of values specifying the basis for each
%                    bond. Possible values are:
%                    0 - actual/actual   (default)
%                    1 - 30/360 SIA
%                    2 - actual/360
%                    3 - actual/365
%                    4 - 30/360 PSA
%                    5 - 30/360 ISDA
%                    6 - 30/360 European
%                    7 - actual/365 Japanese
%                    8 - actual/actual ISMA
%                    9 - actual/360 ISMA
%                   10 - actual/365 ISMA
%                   11 - 30/360 ISMA
%                   12 - actual/365 ISDA
%                   13 - bus/252
%
%     EndMonthRule - NSTPx1 vector of values specifying whether or not "end
%                    of month rule" is in effect for each bond.
%                    0 - off
%                    1 - on  (default)
%
%             Face - NSTPx1 vector of face value of each bond.
%                    Default is $100
%
%   Outputs:
%        YTM - Yield-to-Maturity in decimal.
%
%   Example:
%     This is an example to find YTM of a stepped coupon
%     of known prices, given three scenarios:
%
%     A. Two Conversion, the first one however, falls on Settle and thus
%        immediately expires.
%     B. Three Conversions, with conversion dates exactly on the
%        CouponDates.
%     C. Three Conversions, with one or more conversion dates not on
%        CouponDates.
%
%     The last case illustrates that only cash flows after conversion dates
%     are affected.
%
%     Price = [117.3824;113.4339;113.4339];
%     Settle   = datenum('02-Aug-1992');
%
%     ConvDate = [datenum('02-Aug-1992'), datenum('15-Jun-2003'), ...
%                 nan; datenum('15-Jun-1997'), datenum('15-Jun-2001'), ...
%                 datenum('15-Jun-2005'); datenum('14-Jun-1997'), ...
%                 datenum('14-Jun-2001'), datenum('14-Jun-2005')];
%
%     Maturity = datenum('15-Jun-2010');
%
%     CouponRates = [0.075 0.08875 0.0925 nan;
%                    0.075 0.08875 0.0925 0.1;
%                    0.075 0.08875 0.0925 0.1];
%     Basis = 1;
%     Period = 2;
%     EndMonthRule = 1;
%     Face = 100;
%
%     YTM = stepcpnyield(Price, Settle, Maturity, ConvDate, ...
%        CouponRates, Period, Basis, EndMonthRule, Face)
%
%     YTM =
%        0.07221440205
%        0.07221426780
%        0.07221426780
%
% See also STEPCPNPRICE, STEPCPNCFAMOUNTS
%
% References: This function adheres to SIA Fixed Income Securities Formulas
%             for Price, Yield, and Accrued Interest.

%   Copyright 2002-2006 The MathWorks, Inc.

if nargin < 5
    error(message('fininst:stepcpnyield:invalidInputs'));
end

Price = Price(:);

data{3} = Settle;
data{4} = Maturity;

if nargin < 6 || isempty(varargin{1})
    data{5} = 2;

else
    data{5} = varargin{1};
end

if nargin < 7 || isempty(varargin{2})
    data{6} = 0;

else
    data{6} = varargin{2};
end

if nargin < 8 || isempty(varargin{3})
    data{7} = 1;

else
    data{7} = varargin{3};
end

if nargin < 9 || isempty(varargin{4})
    data{12} = 100;

else
    if any(varargin{4} < 0)
        error(message('fininst:stepcpnyield:invalidFace'));

    else
        data{12} = varargin{4};
    end
end

[CouponRate, Settle, Maturity, Period, Basis, EndMonthRule, IssueDate, ...
    FirstCouponDate, LastCouponDate, StartDate, Face] = instargbond(data{2:end}); %#ok

% The scalar expansion done inside instargbond may not be
% correct since it doesn't consider "Yield". Make another
% scalar expansion to make sure sizes are appropriate.
[CouponRate, Settle, Maturity, Period, Basis, EndMonthRule, Face, Price] =  ...
    finargsz(1, CouponRate, Settle, Maturity, Period, Basis, EndMonthRule, ...
    Face, Price); %#ok

% Checking the size
[convdaterow, convdatecol] = size(ConvDates);
[cpnraterow,  cpnratecol]  = size(CouponRates);

if (convdaterow ~= cpnraterow) || (convdatecol ~= (cpnratecol-1))
    error(message('fininst:stepcpnyield:invalidSizeConvDataCpnRate'));
end

if (convdaterow ~= length(Settle))
    error(message('fininst:stepcpnyield:invalidConvDataCpnRateMatrix'));
end

NBonds = length(Settle);

% Use semi-anual compounding frequency for yields-to-maturity (BEY)
% Use annual for compounding frequency for ISMA convention
Frequency = repmat(2, NBonds, 1);
Frequency(isisma(Basis)) = 1;

% Start out with NaN
PerDisc = nan(NBonds, 1);

% set options for FZERO
foptions = optimset('fzero');
foptions = optimset(foptions, 'TolX', 1e-12);
foptions = optimset(foptions, 'Display', 'off');

% Get Cashflows and TimeFactors
[CFlow, CDates, TFact] = stepcpncfamounts(Settle, Maturity, ...
    ConvDates, CouponRates, Period, Basis, EndMonthRule, Face); %#ok


for i = 1:NBonds
    % Separate CFlows and TFactors to relate to proper bond
    CFlowAmounts = CFlow(i, :);
    TFactors = TFact(i, :);

    % First CFamount to be dirty price
    CFlowAmounts(1) = CFlowAmounts(1) - Price(i);

    % Remove NaN for calculation of XGuess
    CpnRates = CouponRates(i, ~isnan(CouponRates(i, :)));

    % Initial Guess for the discount based on Yield = Coupon Rate
    XGuess = 1./(1 + mean(CpnRates)./Frequency);
    
    % Determine where there are nans and do not pass them into the
    % optimization.
    nonNanIdx = ~isnan(CFlowAmounts);
    
    [X,Fval,Flag,Output] = fzero(@bndyieldsub, XGuess(i), foptions,...
        CFlowAmounts(nonNanIdx), TFactors(nonNanIdx)); %#ok

    % if fzero was unable to find a zero, try using fsolve
    if (Flag < 0)
        fsoption = optimset('fsolve');
        fsoption = optimset(fsoption, 'TolX', 1e-12);
        fsoption = optimset(fsoption, 'TolFun', 1e-12);
        fsoption = optimset(fsoption, 'Display', 'off');
        fsoption = optimset(fsoption, 'LargeScale', 'off');

        [X, Fval, Flag, Output] = ...
            fsolve(@bndyieldsub, XGuess(i), fsoption, CFlowAmounts, TFactors); %#ok
    end

    % Assign result to PerDisc
    PerDisc(i) = X;
    %Iterations(i) = Output.iterations - 1;
end

if (Flag < 0)
    % convergence failure
    warning(message('fininst:stepcpnyield:solutionConvergenceFailure'));
end

% Compute Yield from the periodic discount factors
YTM = (1./PerDisc - 1).*Frequency;


% -------------------------------------------------------------------------
function PV = bndyieldsub(X, CFlow, TimeFactor)
% BNDYIELDSUB objective function for bndyield
%
PV = sum(CFlow .* (X.^TimeFactor));