Finding a maximum/minimum

4 views (last 30 days)
Wildman
Wildman on 22 Sep 2015
Edited: Matt J on 24 Sep 2015
Dear all,
I got a matrix (31225x1) which consists of closing price values (each row is one working day, so one closing price value in each row).
Now, at time "t", I want to find the maximum (minimum) which is determined as the most recent closing price (so nearest to time "t") that is greater (less) than the "c" previous closing prices (so before time "t"), where "c"=[5 10 25 50];.
I'm struggling with getting it working (efficiently) with the "max" and "min" functions. Does somebody has a suggestion how to do this?
Kind regards, Wildman

Answers (1)

Matt J
Matt J on 22 Sep 2015
Edited: Matt J on 22 Sep 2015
Something like this perhaps
%%fake data
cvals=[5, 10,25,50];
Prices=[0;sort(rand(31225,1));1]*100; %fake prices
N=length(Prices);
days=1:N;
t=days(1:end-1)+rand(1,N-1);
tic;
%%algorithm
T=toeplitz(Prices,[Prices(1),nan(1,49)]);
Tmin=cummin(T,2); Tmin=Tmin(:,cvals);
Tmax=cummax(T,2); Tmax=Tmax(:,cvals);
[~, ~, bin]=histcounts(t,days);
%
%This might be a better way to compute 'bin':
% bin=interp1(days,t,'previous');
minvals=Tmin(bin,:); %the result
maxvals=Tmax(bin,:);
toc;
  7 Comments
Wildman
Wildman on 23 Sep 2015
Thanks for your time again!
bin=floor(t-1);
If I change the part "t" in "t-1" (otherwise it also takes the current closing price in consideration) the code seems to find the correct maximum value where the value is greater than the "c" previous values.
However I'm not sure what the code does when taking a minimum value. In some cases it seems to take the "minimum" value of the "c" next values after that "minimum" (it needs to take the most recent closing price that is less than the "c" previous closing prices) and in other cases it seems a bit random which value it takes?
Matt J
Matt J on 24 Sep 2015
Edited: Matt J on 24 Sep 2015
You'll need to attach a .mat file with an illustration of what's going wrong on actual data. As you can see from the code, the min. operation operates on the very same data, T, as the max. operation. No reason you shouldn't be getting analogous behavior. If you look at the rows of T, you will see that they represent the stream of previous Prices starting from a given day T and extending back a further c=1,2,...49 days.
If you think the max. operation is working to your needs, however, you could just apply the same maximization steps to -Prices. In other words, flip the sign of the Prices and then flip the sign of maxvals correspondingly, minvals=-maxvals.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!