MATLAB: Percentage of up days every 12 days

for loop

Hello I have a data of stock prices and I am trying to write a code that calculate the pecentage of up days for the past 12 day.
equation as follow:
SPY= (number of times the closing price was up/ period)*100
thanks

Best Answer

Assuming your data are daily stock prices, you can use Y = diff(X,1,dim) to compute the difference across the n_th dimention of your data. If your data is a vector, you just need the 1st input.
Y will have 1 less data point than X since Y(1) is the result of X(2)-X(1).
Then look for positive values in Y. If Y(n) is positive that means the stock from X(n+1) increased from the previous day on X(n).
The rest should be straightforward.