function [peaks,troughs] = findpeaksandtroughs(u,size)
% - u is the (e.g. unemployment) time series under investigation
% - size is the minimal size of a swing to qualify as a peak or trough
% - peaks is a dummy time series that indicate identified peaks with 1
% - troughs is a dummy time series that indicate identified troughs with 1
% Note: As the function is initially intended for unemployment time series, a
% "peak" here is a low value of u
% (c) Stephane Dupraz, Emi Nakamura, Jon Steinsson 2019
T =length(u);
peaks =zeros(T,1);
troughs =zeros(T,1);
% Initial Conditions
candidate =1;%t=1 is our first candidate for a peak or a trough
if u(1)__=u(candidate)
if u(t)>=u(candidate)+size % u has increased by more than x since our candidate for peak
peaks(candidate)=1; %our candidate is a peak indeed
lookingfor ='trough';% we now look for a trough
candidate =t;% t is the first candidate for such a trough
end
end
end
if strcmp(lookingfor,'trough')% if we are looking for a trough
if u(t)>u(candidate)
candidate=t;% our candidate for a trough becomes t
else % u(t)<=u(candidate)
if u(t)<=u(candidate)-size % u has decreased by more than x since our candidate for trough
troughs(candidate)=1; %our candidate is a trough indeed
lookingfor ='peak';% we now look for a peak
candidate =t;% t is the first candidate for such a peak
end
end
end
end
% Final call
if strcmp(lookingfor,'trough')
troughs(candidate)=1;
end
if strcmp(lookingfor,'peak')
peaks(candidate)=1;
end
end
__