Pages

Sunday, October 2, 2011

Jeff Augen Volatility Spike Code in R

[Update: I have updated this so the number of days used for standard deviation can be passed as a parameter, you can find the code at Trading Mean Reversion with Augen Spikes ]

Jeff Augen has written many excellent books on options trading, including The Volatility Edge in Options Trading in which he presents a novel way of looking at a securities price movement as a function of its recent standard deviation. 


I believe it's a very useful way at looking at price moves, so implemented the following which I believe matches as it was described in the book.


slideapply <- function(x, n, FUN=sd) {
    v <- c(rep(NA, length(x)))


    for (i in n:length(x) ) {
     v[i] <- FUN(x[(i-n+1):i])
    }
    return(v)
}


augenSpike <- function(x, n=20) {
    prchg <- c(NA, diff(x))
    lgchg <- c(NA, diff(log(x)))
    stdevlgchg <- slideapply(lgchg, n, sd)
    stdpr <- x * stdevlgchg
    #shuffle things up one
    stdpr <- c(NA, stdpr[-length(stdpr)])
    spike <- prchg / stdpr
    return(spike)
}

An example of how to use it with quantmod:


getSymbols('SPY')

sp <- SPY['2010/2011']
asp <- augenSpike(as.vector(Cl(sp)))
sp$spike <- asp
barplot(sp['2011']$spike, main="Augen Price Spike SPY 2011", xlab="Time Daily", ylab="Price Spike in Std Dev")


Which gives the following chart
If you want to verify it has been implemented correctly (and I won't hold it against you), I used the following which is based on the example data he gave in the book. You will need the slideapply function from above which will apply a function to a subset of a vector along a sliding window.



aub <- data.frame(c(47.58, 47.78, 48.09, 47.52, 48.47, 48.38, 49.30, 49.61, 50.03, 51.65, 51.65, 51.57, 50.60, 50.45, 50.83, 51.08, 51.26, 50.89, 50.51, 51.42, 52.09, 55.83, 55.79, 56.20))
colnames(aub) <- c('Close')
aub$PriceChg <- c(NA, diff(aub$Close))
aub$LnChg <- ROC(aub$Close)
aub$StDevLgChg<-slideapply(aub$LnChg, 20, sd)
aub$StdDevPr <- aub$Close * aub$StDevLgChg


pr <- aub$StdDevPr
pr <- c(NA, pr[-length(pr)])


aub$Spike <- aub$PriceChg / pr
aub



Which for me at least gives the same data as printed. Let me know if you find it useful or find any errors. 




No comments:

Post a Comment