# How to find local peaks/valleys in a series of data?

Here is my experiment:

I am using the findPeaks function in the quantmod package:

I want to detect "local" peaks within a tolerance 5, i.e. the first locations after the time series drops from the local peaks by 5:

aa=100:1
bb=sin(aa/3)
cc=aa*bb
plot(cc, type="l")
p=findPeaks(cc, 5)
points(p, cc[p])
p


The output is

[1] 3 22 41


It seems wrong, as I am expecting more "local peaks" than 3...

Any thoughts?

-
I don't have this package. Can you describe the numerical routine being used? –  AdamO Feb 16 '12 at 17:36
The full source code for findPeaks appears in my reply, @Adam. BTW, the package is "quantmod". –  whuber Feb 16 '12 at 19:02
Cross posted on R-SIG-Finance‌​. –  Joshua Ulrich Feb 17 '12 at 13:12
Luna, it may be time to look back to earlier responses that were given to you, and start upvoting/accepting answers, no? –  chl Feb 28 '12 at 21:43

The source of this code is obtained by typing its name at the R prompt. The output is

function (x, thresh = 0)
{
pks <- which(diff(sign(diff(x, na.pad = FALSE)), na.pad = FALSE) < 0) + 2
if (!missing(thresh)) {
pks[x[pks - 1] - x[pks] > thresh]
}
else pks
}


The test x[pks - 1] - x[pks] > thresh compares each peak value to the value immediately succeeding it in the series (not to the next trough in the series). It uses a (crude) estimate of the size of the slope of the function immediately after the peak and selects only those peaks where that slope exceeds thresh in size. In your case, only the first three peaks are sufficiently sharp to pass the test. You will detect all the peaks by using the default:

> findPeaks(cc)
[1]  3 22 41 59 78 96

-