Effacer les filtres
Effacer les filtres

Getting corresponding y values from moving average graph when having x values

4 vues (au cours des 30 derniers jours)
Ngoc Nguyen
Ngoc Nguyen le 11 Avr 2018
Commenté : Ngoc Nguyen le 25 Avr 2018
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!

Réponses (1)

Pawel Jastrzebski
Pawel Jastrzebski le 11 Avr 2018
Modifié(e) : Pawel Jastrzebski le 11 Avr 2018
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.

Catégories

En savoir plus sur Financial Data Analytics dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by