Simple moving average code for forecasting stock prices
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
I need code for predicting stock prices in future using simple moving average calculation
채택된 답변
Clay Swackhamer
2019년 4월 17일
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, $')
xlabel('Trading day')

댓글 수: 3
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, $')
xlabel('Trading day')
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
StockData = readtable('^JKSE.csv','ReadVariableNames',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);
AdjustedClose = cellfun(@str2double,StockData.AdjClose);
Volume = cellfun(@str2double,StockData.Volume);
else
Open = StockData.Open;
High = StockData.High;
Low = StockData.Low;
Close = StockData.Close;
AdjustedClose = StockData.AdjClose;
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)
Response2015(i)="buy";
else
Response2015(i)="Not buy";
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)
Response2016(i)="buy";
else
Response2016(i)="Not buy";
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
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
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Financial Toolbox에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
