forecasting method in matlab using VAR model
57 views (last 30 days)
Show older comments
Good evening sir
I request you please resolve the error from my code. I attached DATA also sir .
CODE:
% Step 1: Load data
data = xlsread('DATA.xlsx');
time = data(1:400, 1); % Time column (1st column)
inf_data = data(1:400, 2); % Infected data column (2nd column)
% Step 2: Prepare data for VAR
% Since we are using univariate data, we treat it as a single-variable time series
% Create lagged data (you can modify the lag length)
lags = 2; % Number of lags
dataForVAR = [inf_data(1:end-lags), inf_data(lags+1:end)];
% Step 3: Fit the VAR model
model = varm(2, 1); % 2 lags, 1 variable
fitModel = estimate(model, dataForVAR); % Fit the model
% Step 4: Forecasting using the VAR model
numForecasts = 10; % Number of steps to forecast
% Ensure 'Y0' is a numeric matrix, not a vector
presampleData = dataForVAR(end-lags+1:end, :); % The last lags data as presample
YForecast = forecast(fitModel, numForecasts, 'Y0', presampleData);
% Rescale the forecasted data (if needed)
forecastData = YForecast(:, 1); % First column is the forecast for the 'inf_data' series
% Step 5: Plot the results
figure;
hold on;
plot(time, inf_data, 'b-', 'LineWidth', 1.5, 'DisplayName', 'Actual Data'); % Actual data
forecastTime = time(end) + (1:numForecasts); % Forecast time points
plot(forecastTime, forecastData, 'r-', 'LineWidth', 1.5, 'DisplayName', 'Forecasted Data'); % Forecasted data
xlabel('Time', 'FontSize', 14);
ylabel('Infected Cases', 'FontSize', 14);
title('Forecasting with VAR Model', 'FontSize', 16);
legend('Location', 'Best');
grid on;
hold off;
ERROR:
Error using varm/forecast (line 195)
The value of 'Y0' is invalid. Expected presample responses to be one of these types:
double
Error in plots (line 20)
YForecast = forecast(fitModel, numForecasts, 'Y0', presampleData);
0 Comments
Answers (3)
Pavl M.
on 19 Nov 2024 at 17:15
Edited: Pavl M.
about 17 hours ago
clc
clear all
close all
%% Step 1: Load data
data = xlsread('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1809848/DATA.xlsx');
time = double(data(1:400,1)); % Time column (1st column)
inf_data = double(data(1:400,2)); % Infected data column (2nd column)
d2 = double(data(1:400,3));
%% Step 2: Prepare data for VAR
% Since we are using univariate data, we treat it as a single-variable time series
% Create lagged data (you can modify the lag length)
lags = 2; % Number of lags
dataForVAR = [inf_data(1:end-lags);inf_data(lags+1:end)];
%% Step 3: Fit the VAR model
model = varm(1,lags); % 2 lags, 1 sequence of variables
fitModel = estimate(model,dataForVAR); % Fit the model
%Identified model whose output is to be forecasted, specified as one of the following:
%Linear model — idpoly, idproc, idss, idtf, or idgrey
%Nonlinear model — idnlgrey, idnlhw, or idnlarx
%If a model is unavailable, estimate sys from PastData using commands
% such as ar, arx, armax, nlarx, and ssest.
%% Step 4: Forecasting using the VAR model
summarize(fitModel)
numForecasts = 10; % Number of steps to forecast
presampleData = dataForVAR(end-lags+1:end,:); % The last lags data as presample
%opt = forecastOptions('InitialCondition','e'); % Add more options
%opt.InputOffset = 0;
YForecast = forecast(fitModel,presampleData,numForecasts);
%or try using the estimated model and in-sample data as presample observations.
YForecast2 = forecast(fitModel,dataForVAR,numForecasts);
% Rescale the forecasted data (if needed)
forecastData = YForecast(:, 1); % First column is the forecast for the 'inf_data' series
forecastData2 = YForecast2(:,1);% Step 5: Plot the results
forecastTime = time(end)+(1:numForecasts); % Forecast time points
%% Visualize anticipative foreseeing:
figure;
hold on;
plot(time,inf_data,'b-','LineWidth',1.5,'DisplayName','Actual Data'); % Actual data
plot(forecastTime,forecastData,'r-','LineWidth',1.5,'DisplayName','Forecasted Data'); % Forecasted data
xlabel('Time','FontSize',14);
ylabel('Infected Cases','FontSize',14);
title('Forecasting with VAR Model on presampled input','FontSize',16);
legend('Location','Best');
grid on;
hold off;
figure
plot(time,inf_data,'b-','LineWidth',1.5,'DisplayName','Actual Data'); % Actual data
plot(forecastTime,forecastData2,'r-','LineWidth',1.5,'DisplayName','Forecasted Data'); % Forecasted data
xlabel('Time','FontSize',14);
ylabel('Infected Cases','FontSize',14);
title('Forecasting with VAR Model on original input','FontSize',16);
legend('Location','Best');
grid on;
hold off;
2 Comments
Pavl M.
on 20 Nov 2024 at 6:38
Edited: Pavl M.
on 20 Nov 2024 at 7:23
OK
Yes, of course. It is what m for to contribute simple solutions to complex conundrums.
Today Fixed to (';' instead of your ',' for making data as a row, varm parameters swap to meet the standard how the function signature is defiend,forceast(...) params swap to meet the standard of how the function signature is defined in TCE):
...
dataForVAR = [inf_data(1:end-lags);inf_data(lags+1:end)];
%% Step 3: Fit the VAR model
model = varm(1,2); % 2 lags, 1 sequence of variables
fitModel = estimate(model,dataForVAR); % Fit the model
%Identified model whose output is to be forecasted, specified as one of the following:
%Linear model — idpoly, idproc, idss, idtf, or idgrey
%Nonlinear model — idnlgrey, idnlhw, or idnlarx
%If a model is unavailable, estimate sys from PastData using commands
% such as ar, arx, armax, nlarx, and ssest.
%% Step 4: Forecasting using the VAR model
summarize(fitModel)
numForecasts = 10; % Number of steps to forecast
presampleData = dataForVAR(end-lags+1:end,:); % The last lags data as presample
%opt = forecastOptions('InitialCondition','e'); % Add more options
%opt.InputOffset = 0;
YForecast = forecast(fitModel,presampleData,numForecasts);
...
*****
What do you get?
Next conundrum predicted:
What if you run predict to evaluate / backtest how predicted result matches the observed response of an estimated model:
[yp,x0,Predictor]= predict(fitModel,[crossvalidationdatum],numForecasts)
crossvalidationdatum = presampleData or dataForVAR or?
to check whether yp equals to YForecast to estimate your forecast accuracy?
What if the numForecasts growing / shrinking?
What if in forecast(...) you increase the presampleData from just 2 rows in 1 column orginally towards more rows and columns to get more evolutional funcional dependency (distribution) resemblings (subleties) of the original process/plant/environment model that produced such datum distribution?
*****
What if you exchange your varm model to
ar,(too simple model, losses in peculiarities)
arx, (too simple model, losses in peculiarities)
armax (not advisable to use, better use VARIMAX),
nlarx,
ssest (better also try this).
?
Then you can construct more sophisticated:
dataForVAR1 = [inf_data(1:end-lags);inf_data(lags+1:end)];
dataForVAR2 = [d2(1:end-lags);d2(lags+1:end)];
lags = 4;
dataForVAR3 = [inf_data(1:end-lags);inf_data(lags+1:end)];
dataForVAR4 = [d2(1:end-lags);d2(lags+1:end)];
model1 = varm(1,2,'Covariance',cov1); % 2 lags, 1 sequence of variables
model2 = varm(1,4,'Covariance',cov2); % 4 lags
fitModel1 = estimate(model1,dataForVAR1); % Fit the model
fitModel2 = estimate(model1,dataForVAR2); % Fit the model
fitModel3 = estimate(model2,dataForVAR3); % Fit the model
fitModel4 = estimate(model2,dataForVAR4); % Fit the model
%Model with states:
mc = dtmc(dataForVARArray,'StateNames',["State1" "State2" "State3" "State4"])
mdl = [fitModel1; fitModel2;fitModel3;fitModel4];
Use msVAR to create a Markov-switching dynamic regression model from the switching mechanism mc and the state-specific submodels mdl.
Mdl = msVAR(mc,mdl) %Markov switching model with states
Or simply use sset instead of msVAR. Interesting research gap question is identified here can sset outperform msVAR in stated model accuracy ?
sys = ssest(datum,4); %if for 4 stated model estimation
mallela ankamma rao
on 20 Nov 2024 at 7:37
Edited: mallela ankamma rao
about 14 hours ago
2 Comments
Pavl M.
on 20 Nov 2024 at 7:54
Edited: Pavl M.
on 20 Nov 2024 at 8:12
Why, for what You invoked
estimate(model, dataForVAR'); with dataForVAR transposed (' sign)?
while at the time of your latest comment I've already updated(corrected) the my answer:
estimate(model, dataForVAR);
after I had constructed the correct column vector:
dataForVAR = [inf_data(1:end-lags);inf_data(lags+1:end)];
which is a 1 column vector and estimate "eats" 1 column vector.
With no transposed version, run it what you get?
I think you used un-updated versions.
I corrected it initially:
That is your dataForVAR in green.
Are you sure about it. It contains 1 peak, gaussian-like distribution and seasonable(periodic) components.
What is your time scale/units? (start date, end date?)
I think the data to modify to
Human operator can analyse and predict, the best forecast by natural intelligence on this data is that it will further grow up(uptrend) till some second following peak then will go downtrend.
The dataForVAR so far is more like for evaluation of how varm(...) estimated the underlying model and for forecast m on it ongoing construction of the data...
Let me kow which more help is required? It should be OK now and in the future.
Please run it and let me know what you get, there are a few very valued R&D workstreams to proceed and continue furthermore.
Pavl M.
on 20 Nov 2024 at 8:54
Edited: Pavl M.
on 20 Nov 2024 at 9:05
It's still OK, quite smooth and not problematic to solve complete and resolve in full.
There are 2 different forecast functions with the same name:
and
where Mdl is the system and Y0 is your presample.
One in Econometrics toolbox and 1 in system identification toolbox. In econometrics they assume by default ARIMA and GARCH composite model.
System identification is better, since it covers more real world cases(more general). While forecast in Econometrics mainly fitted for ARIMAX model. That 's why even before I putted in my answer the hint to try other estimators of model, in addition to varm.
I know why your system invoked the forecast from Econometrics. That is mechanism of function dispatch in TCE, identified it due to the input Mdl of type varm.
I assumed the first one as most reasonable per se.
It's still ok, the solution is just swap the tail 2 function arguments places.
Before R2023 version they may be calling the Econometrics 1 by default
Check and let me know.
Which toolboxes do you have which you will be needing?
Swap presampleData and numForecasts places in it.
What on TCE R2024b?
If on R2021b value of 'numperiods' Expected forecast horizon to be a scalar.
(line 121)
YForecast = forecast(fitModel,presampleData,numForecasts);
Try to swap parameters
numForecasts is the predictionHorizon, which is scalar
numForecasts = 10;
I think I esablished robust trust. Let's build solid understanding. Will you be needing it in R and Python as well?
Turst me.
I'll be happy to help, to debug your code.
I think now you have succeeded to launch it and get intial results.
What do you get now?
6 Comments
Pavl M.
about 3 hours ago
Edited: Pavl M.
about 3 hours ago
Contact me more for work at: hireworktrust@proton.me, my genuine ms skype instead of whatsapp: join.skype.com/invite/oXnJhbgys7oW ™®©
Please carefully think about the honest real future business roadmap:
Due to we met for specific work here, no hacking please, only ethically correct paid employment.
Have you proof-read well the recent PuMed article published at 27 September 2024?
Have you published also at Springer Nature ™®© ?
Who will be glad to hire on proof-reading services?
How SAIUGR model is accurate, what else high value models to help with?
Can we uphold and maintain focus group with Chilean, Portugeese and Spanish investors/stakeholders, which components, visual artefacts, digital items they will be happy to pay for under the free trade framework proposed?
Which specific commitment who will be glad to transact salary via onlne banking or via WU?
Which team is there to publish at PubMed?
What if to improve Λ Human recruitment rate?
What on Optimal Control who will be needing most valuable?
I can do in Technical Computing Environment, Numerical Computing, Multi-Paradigm Programming,
tending to holistic dynamics and statics analysis, which ICER, NFSI, other metrics to implement?
Which objective functions to care for?
What on me to do and look what I did before in order to get more necessary substantial supplies?
See Also
Categories
Find more on Vector Autoregression Models in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!