# Simple moving average code for forecasting stock prices

73 views (last 30 days)
Megawaty Lestari on 17 Apr 2019
Commented: Clay Swackhamer on 21 Apr 2019
I need code for predicting stock prices in future using simple moving average calculation

Clay Swackhamer on 17 Apr 2019
Hi Megawaty,
Here is an idea:
time = 1:1:100' %100 trading days
stockPrice = rand(100,1)+3 %closing price in dollars on each day
movingAve = movmean(stockPrice,5) %moving average for weekly intervals
plot(time, stockPrice)
hold on
plot(time, movingAve)
legend('Price every day', 'Moving average price every week')
ylim([0 6])
ylabel('Price, \$')

Clay Swackhamer on 20 Apr 2019
Hi Megawaty,
You mentioned that there was an error message when you tried this code. Can you be more specific? What was the error? Here is a code with a manual method to calculate moving average. Maybe this will help you get started.
time = 1:1:100' %100 trading days
stockPrice = rand(100,1)+3 %closing price in dollars on each day
movingAve = movmean(stockPrice,5) %moving average for weekly intervals
%Manually calculate moving average, using a 5 space look-forward method
for i = 1:1:length(stockPrice)-5
movingAveManual(i) = mean(stockPrice(i:i+5));
end
plot(time, stockPrice)
hold on
plot(time, movingAve)
plot(time(1:length(movingAveManual)), movingAveManual)
legend('Price every day', 'Moving average price every week', 'Moving average, manual calculation')
ylim([0 6])
ylabel('Price, \$')
Megawaty Lestari on 21 Apr 2019
Dear Mr. Clay Swackhamer,
Thankyou for your fast response. So actually the code is like this, I got it from https://www.mathworks.com/matlabcentral/fileexchange/68637-machine-learning-classification-used-to-predict-stock?s_tid=mwa_osa_a as my references, because i want the ouput can show the price and the date on the label including the actual price that i get from yahoo and the predicted price from calculation using moving averge. But when i run it, it doesn't show as how i want it to be, and get some error that says :
Undefined function or variable 'MachineLearningModellingNewUpdate'.
Error in getdata (line 109)
[ModelPrediction,ModelNameFina,Model_Accuracy] =
MachineLearningModellingNewUpdate(tableprediction) ;
clc;
clear all;
UseDefaultData = true;
warning('OFF', 'MATLAB:table:ModifiedAndSavedVarnames');
if UseDefaultData == true
else
StockData = getMarketDataViaYahoo('^JKSE', '1-January-2014', '30-April-2018');
end
warning('OFF', 'MATLAB:table:ModifiedAndSavedVarnames');
%Ensure the data is in correct data type
if isnumeric(StockData.Open) == false
Open =cellfun(@str2double,StockData.Open);
High = cellfun(@str2double,StockData.High);
Low = cellfun(@str2double,StockData.Low);
Close = cellfun(@str2double,StockData.Close);
Volume = cellfun(@str2double,StockData.Volume);
else
Open = StockData.Open;
High = StockData.High;
Low = StockData.Low;
Close = StockData.Close;
Volume = StockData.Volume;
end
Date = StockData.Date;
%Tranform the data to timetable
StockData_TimeTable = timetable(Date,Open,High,Low,Close,Volume);
%Check for missing Data
%Fill the missing data with linear
if any(any(ismissing(StockData_TimeTable)))==true
StockData_TimeTable = fillmissing(StockData_TimeTable,'linear');
end
%Delete the row if volume is 0
StockData_TimeTable(StockData_TimeTable.Volume==0,:) =[];
%View the data
plot(StockData_TimeTable.Date,StockData_TimeTable.Close);
title('Jakarta Stock Exchange');
ylabel('IDR');
xlabel('Timeline');
grid on
time = 1:1:100' %100 trading days
stockPrice = rand(100,1)+3 %closing price in dollars on each day
movingAve = movmean(stockPrice,5) %moving average for weekly intervals
%Manually calculate moving average, using a 5 space look-forward method
for i = 1:1:length(stockPrice)-5
movingAveManual(i) = mean(stockPrice(i:i+5));
end
plot(time, stockPrice)
hold on
plot(time, movingAve)
PredictionTable = timetable(StockData_TimeTable.Date);
% get Year 2016 data out for training
tr = timerange('2015-01-01' , '2015-12-31');
PredictionTable_2015 = PredictionTable(PredictionTable.Time(tr),:);
% get 2H Year 2017 data out for prediction
tr = timerange('2016-01-01' , '2016-12-31');
PredictionTable_2016 = PredictionTable(PredictionTable.Time(tr),:);
% Deal with missing data
PredictionTable_2015(any(ismissing(PredictionTable_2015),2),:)=[];
PredictionTable_2016(any(ismissing(PredictionTable_2016),2),:)=[];
% Get the Open and Close Price Data for year 2016 & 2017
OpenClose_2015 = StockData_TimeTable(PredictionTable_2015.Time,:);
OpenClose_2016 = StockData_TimeTable(PredictionTable_2016.Time,:);
% In this strategy, it consider worth to buy the stock or not if we buy the stock at market open rate and sell out at the end of the day
% We does not know the close rate, but we will know the open rate before prediction.
% if the close rate higher than open rate more than 1%, then we classify it as 'buy' in our original data.
for i =1:height(OpenClose_2015)
if OpenClose_2015.Open(i)*1.01 < OpenClose_2015.Close(i)
else
end
end
Response2015=categorical(Response2015);
Categ=categories(Response2015)
for i =1:height(OpenClose_2016)
if OpenClose_2016.Open(i)*1.01 < OpenClose_2016.Close(i)
else
end
end
Response2016=categorical(Response2016);
categories(Response2016)
% Convert Timestable to table
PredictionTable_2015_Table = timetable2table(PredictionTable_2015);
PredictionTable_2015_Table.Response=Response2015';
PredictionTable_2016_Table = timetable2table(PredictionTable_2016);
PredictionTable_2016_Table.Response=Response2016';
% update the table and re-train the model for next prediction
% keep them into for loop to predict the first 30 days of trading day in year 2017
% since first day is predicted, therefore we need to predict the next 29 days
for i=1:1:14
tableprediction = [PredictionTable_2015_Table;PredictionTable_2016_Table(i,:)];
%trainmodelwithnewupdate
[ModelPrediction,ModelNameFina,Model_Accuracy] = MachineLearningModellingNewUpdate(tableprediction) ;
% predict for first trading day of 2016 before stock market open
predictionoutcome=ModelPrediction.predictFcn(PredictionTable_2016_Table(i+1,:));
Newresult=table(OpenClose_2016.Date(i+1),OpenClose_2016.Open(i+1),OpenClose_2016.Close(i+1),Response2016(i+1),predictionoutcome,ModelNameFinal,Model_Accuracy);
Newresult.Properties.VariableNames(1)={'Date'};
Newresult.Properties.VariableNames(1)={'Open'};
Newresult.Properties.VariableNames(1)={'Close'};
resulttable= [resulttable;Newresult];
end
% Result
display(resulttable);
Sincerely,
Megawaty Lestari
Clay Swackhamer on 21 Apr 2019
Hi Megawaty,
In this case "MachineLearningModellingNewUpdate" is a function, and the error "Undefined function or variable 'MachineLearningModellingNewUpdate'" tells us that Matlab does not know where this function can be found. Do you know where to get this function, or alternatively what it is supposed to do so that you could write it on your own?
Clay