# R: Finding peaks on a stock price chart

I would like to do is what I thought to be a simple task: find the locations of peaks for a certain stock, and mark those peaks on a chart.

I was surprised by a lack of appropriate examples on the internet. For example, description of findPeaks function from quantmod package does not even explain what the second argument (thresh) represent. Could somebody please explain?

So, this is what I managed to do:

library(quantmod)
APL <- getSymbols("AAPL", src = "yahoo", auto.assign = FALSE)

aapl.price <-AAPL$AAPL.Close p <- findPeaks(aapl.price, 10) plot(aapl.price, type = 'l') points(aapl.price[p],index(aapl.price)[p], col = "red")  This comes up: Obviously, there are different ways to define the peaks, but by any means the output here is not what one would want to see. Could somebody please provide any guidance? Also, please let me know if this is best done using some other package ## 1 Answer As you mentioned, there are different ways to define peaks. One method is implemented in function streaks in package PMwR. The function will look for phases of up or down movements that are not interrupted by countermoves of a specified size. The peaks and troughs are then the extreme points of those phases. Here is an example: library("quantmod") library("zoo") library("PMwR") AAPL <- getSymbols("AAPL", src = "yahoo", auto.assign = FALSE) aapl.price <- window(as.zoo(AAPL$AAPL.Close),
start = as.Date("2010-1-1"))

plot(aapl.price)

streaks <- streaks(aapl.price)
streaks
##        start        end state     return
## 1 2010-01-04 2010-02-04  <NA> -0.1026120
## 2 2010-02-04 2012-09-19    up  2.6558188
## 3 2012-09-19 2013-04-19  down -0.4437687
## 4 2013-04-19 2015-02-23    up  1.3839397
## 5 2015-02-23 2016-05-12  down -0.3207519
## 6 2016-05-12 2018-10-03    up  1.5688512
## 7 2018-10-03 2019-01-03  down -0.3872969
## 8 2019-01-03 2020-02-12    up  1.3011464
## 9 2020-02-12 2020-03-13  down -0.1504585

abline(v = streaks\$end)


(Disclosure: I am the maintainer of PMwR.)