Take the 2-minute tour ×
Cross Validated is a question and answer site for people interested in statistics, machine learning, data analysis, data mining, and data visualization. It's 100% free, no registration required.

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:

plot(cc, type="l")
p=findPeaks(cc, 5)
points(p, cc[p])

The output is

[1] 3 22 41

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

Any thoughts?

share|improve this question
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

2 Answers 2

up vote 3 down vote accepted

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
share|improve this answer

I agree with whuber's response but just wanted to add that the "+2" portion of the code, which attempts to shift the index to match the newly found peak actually 'overshoots' and should be "+1". for instance in the example at hand we obtain:

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

when we highlight these found peaks on a graph (bold red): enter image description here

we see that they are consistently 1 point away from the actual peak.


pks[x[pks - 1] - x[pks] > thresh]

should be pks[x[pks] - x[pks + 1] > thresh] or pks[x[pks] - x[pks - 1] > thresh]

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.