Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate periods since 200-period high of a stock

I would like to calculate the number of periods that have elapsed since the 200 period high of a univariate time series. For example, here's the closing price of SPY:

require(quantmod)
getSymbols("SPY",from='01-01-1900')
Data <- Cl(SPY)

Now, I can find the 200-period highs of this series using the Lag function in quantmod:

periodHigh <- function(x,n) {
    Lags <- Lag(x,1:n)
    High <- x == apply(Lags,1,max)
    x[High]
}
periodHigh(Data, 200)

But now I'm stuck. How do I merge this back onto the original series (Data) and calculate, for each point in the series, how many periods have elapsed since the previous n-period high?

like image 622
Zach Avatar asked Feb 24 '23 01:02

Zach


1 Answers

This little function returns a list with:

  • high the index number of high dates
  • recentHigh the index number of the most recent high day
  • daysSince the number of days since the last high
  • data an xts object with only the high days. Useful for plotting.

The code:

daysSinceHigh <- function(data, days){
  highs <- days-1+which(apply(embed(data, days), 1, which.max)==1)
  recentHigh <- max(highs)
  daysSince <- nrow(data) - recentHigh
  list(
    highs=highs,
    recentHigh = recentHigh,
    daysSince = daysSince,
    data=data[highs, ])
}       

The results:

daysSinceHigh(Data, 200)$daysSince
[1] 90

plot(Data)
points(daysSinceHigh(Data, 200)$data, col="red")

enter image description here

like image 180
Andrie Avatar answered Feb 26 '23 15:02

Andrie