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?
This little function returns a list with:
high
the index number of high datesrecentHigh
the index number of the most recent high daydaysSince
the number of days since the last highdata
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With