%% Fitting an IRFunctionCurve Object Using fitSmoothingSpline with Penalty Function
% This example shows for to use fitSmoothinSpline function to fit the interest-rate curve and model the Lambdafun penalty function.
% First, load the data.

load ukdata20080430

% Convert the repo rates to be equivalent zero coupon bonds.

RepoCouponRate = repmat(0,size(RepoRates));
RepoPrice = bndprice(RepoRates, RepoCouponRate, RepoSettle, RepoMaturity);

% Aggregate the data.

Settle = [RepoSettle;BondSettle];
Maturity = [RepoMaturity;BondMaturity];
CleanPrice = [RepoPrice;BondCleanPrice];
CouponRate = [RepoCouponRate;BondCouponRate];
Instruments = [Settle Maturity CleanPrice CouponRate];
InstrumentPeriod = [repmat(0,6,1);repmat(2,31,1)];
CurveSettle = datenum('30-Apr-2008');

% Choose the parameters for the Lambdafun input argument.

L = 9.2;
S = -1;
mu = 1;

% Define the Lambdafun penalty function.

lambdafun = @(t) exp(L - (L-S)*exp(-t/mu));
t = 0:.1:25;
y = lambdafun(t);
figure
semilogy(t,y);
title('Penalty Function for VRP Approach')
ylabel('Penalty')
xlabel('Time')

% Use the fitSmoothinSpline function to fit the interest-rate curve and model the Lambdafun penalty function.

VRPModel = IRFunctionCurve.fitSmoothingSpline('Forward',CurveSettle,...
Instruments,lambdafun,'Compounding',-1, 'InstrumentPeriod',InstrumentPeriod)

% Plot the smoothing spline interest-rate curve for the forward rates.

PlottingDates = CurveSettle+20:30:CurveSettle+365*25;
TimeToMaturity = yearfrac(CurveSettle,PlottingDates);
VRPForwardRates = getForwardRates(VRPModel, PlottingDates);
figure;plot(TimeToMaturity,VRPForwardRates)
title('Smoothing Spline Model of UK Instantaneous Nominal Forward Curve')

% Copyright 2020 The MathWorks, Inc.