Getting corresponding y values from moving average graph when having x values
조회 수: 9 (최근 30일)
이전 댓글 표시
I have a data of daily stock prices in 10 years, I used moving average to analyze. I used the code below to calculate moving average data and then plot:
date=datenum(Date); x = FTSE100; windowSize1 = 252;
outputLength1 = length(date)-windowSize1+1; y1 = zeros(1,outputLength1);
for k=1:outputLength1 y1(k) = sum(x(k:(k+windowSize1-1)))/windowSize1; end
Now I want to find the y-value from the moving average line (red line) on a specific date (Ex: I need to calculate price at the beginning and at the end of each year), could you help me with this? I tried to find the location of each point of time and replace into the y1, but it was "error". This is my code to find locations: p = datenum(2007,01,01):365:datenum(2016,12,31); I have read many questions of finding y value when having x value, there are answers to use interp1 or find x index and replace to y function, but it didn't work. I am new to Matlab and still learning. Thank you very much!
댓글 수: 0
답변 (1개)
Pawel Jastrzebski
2018년 4월 11일
편집: Pawel Jastrzebski
2018년 4월 11일
Consider the following example:
% RANDOM DATA
startDate = datetime(2018,01,01);
endDate = datetime(2018,04,01);
xTimeSpan = startDate:days(1):endDate;
yData = rand(1,length(xTimeSpan)).*randi([25,75],1,length(xTimeSpan));
% calculationg moving mean
wSize = 10; % window size
mMean = movmean(yData,wSize,'omitnan','Endpoints','shrink');
% find the specific start-end dates (in your case beginning/end of year)
% i.e
StartRangeDate = datetime(2018,01,15);
EndRangeDate = datetime(2018,02,15);
% condition vector
cond = (xTimeSpan == StartRangeDate) | (xTimeSpan == EndRangeDate);
% values for moving mean in your range
yStartEndRange = mMean(cond);
figure
plot(xTimeSpan,yData);
hold on
plot(xTimeSpan,mMean);
plot(xTimeSpan(cond),yStartEndRange,'or')
The output:
You'll see that some of the functions that you need (i.e moving average ) if not all are already available in Matlab so all you have to do is read up the documentation to understand how to use them.
참고 항목
카테고리
Help Center 및 File Exchange에서 Financial Data Analytics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!