%% Compute Fitted Response Values
% Load the US equity index data set Data_EquityIdx.

load Data_EquityIdx

% The table DataTable includes the time series variable NYSE, which contains daily NYSE composite closing prices from January 1990 through December 1995.
% Convert the table to a timetable.

dt = datetime(dates,'ConvertFrom','datenum','Format','yyyy-MM-dd');
TT = table2timetable(DataTable,'RowTimes',dt);
T = size(TT,1);

% Suppose that an ARIMA(1,1,1) model is appropriate to model NYSE composite series during the sample period.
% Fit an ARIMA(1,1,1) model to the data. Specify the required presample and turn off the estimation display.

Mdl = arima(1,1,1);

preidx = 1:Mdl.P;
estidx = (Mdl.P + 1):T;
EstMdl = estimate(Mdl,TT{estidx,"NYSE"},...
    'Y0',TT{preidx,"NYSE"},'Display','off');    

% Infer residuals \hat{\varepsilon_t } from the estimated model, specify the required presample.

resid = infer(EstMdl,TT{estidx,"NYSE"},...
    'Y0',TT{preidx,"NYSE"});

% resid is a (T – Mdl.P)-by-1 vector of residuals.
% Compute the fitted values \hat{\;y_t }.

yhat = TT{estidx,"NYSE"} - resid;

% Plot the observations and the fitted values on the same graph.

plot(TT.Time(estidx),TT{estidx,"NYSE"},'r',TT.Time(estidx),yhat,'b--','LineWidth',2)

% The fitted values closely track the observations.
% Plot the residuals versus the fitted values.

plot(yhat,resid,'.')
ylabel('Residuals')
xlabel('Fitted values')

% Residual variance appears larger for larger fitted values. One remedy for this behavior is to apply the log transform to the data.
% Copyright 2020 The MathWorks, Inc.
%