% Reference: https://www.mathworks.com/matlabcentral/fileexchange/68576-stock-prediction-using-arima

% from: https://finance.yahoo.com/quote/5099.KL/history/
% Capital A Berhad, operating as AirAsia, is a Malaysian multinational low-cost airline
warning('OFF', 'MATLAB:table:ModifiedAndSavedVarnames');
StockData = readtable('5099.KL.csv','ReadVariableNames',true); 

%

figure("Name",'Original Data')
plot(StockData.Close)
grid on

%

figure("Name",'Diff = Detrend')
subplot(211)
plot(diff(StockData.Close))
subplot(212)
plot(diff(diff(StockData.Close)))

%

figure
autocorr(StockData.Close,"NumLags",100)
figure
autocorr(diff(StockData.Close),'NumLags',50)

%

figure
parcorr(StockData.Close)
figure
parcorr(diff(StockData.Close))

%

p = 3;
q = 3;
d = 1;
Mdl = arima(p,d,q);
[Mdl,~,logL] = estimate(Mdl,StockData.Close);
[~,~,ic] = aicbic(logL,p+q+d,length(StockData.Close))
residual = infer(Mdl,StockData.Close);
histogram(residual)
grid on

%

figure
plot(StockData.Close)
hold on
plot(StockData.Close + residual)
hold off
legend('Original','ARIMA')
grid on

%

fr = forecast(Mdl,10,'Y0',StockData.Close(1:end-10));
figure
plot(StockData.Close)
hold on
ln = length(StockData.Close);
plot(ln-9:ln,fr,'.-')
grid on