Search code examples
rdataframequantmod

volatility calculation using quantmod in R


Update post with solution from Joshua; first to set the ticket and download using quantmod and then to calculate the spike.

augen_spike<-function(x,n=20){
  prchg<-diff(x)
  lgchg<-diff(log(x))
  stdevlgchg<-rollapplyr(lgchg,n,sd)
  stdpr<-lag(x*stdevlgchg)
  spike<-prchg/stdpr
  return(spike)
}

require(quantmod)
ticker<-"AAPL"
x<-getSymbols(ticker,auto.assign=FALSE)
spike<-augen_spike(Ad(x))
tail(spike)

  AAPL.Adjusted
2024-01-22     0.8620206
2024-01-23     0.4673772
2024-01-24    -0.2433463
2024-01-25    -0.1188073
2024-01-26    -0.6315797
2024-01-29    -0.6953803

I am working with the below code:

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
  stdpr<-c(NA,stdpr[-length(stdpr)])
  spike<-prchg/stdpr
  return(spike)
}

Application example:

require(quantmod)
getSymbols("RIVN")
spike<-augenSpike(as.vector(RIVN$RIVN.Adjusted))
RIVN$spike<-spike
tail(spike,5)

> tail(spike,5)
[1] -0.7975099 -0.2885007 -1.7847045 -1.7714723 -0.3163372

Instead of manually changing the code if I were to use a new stock ticker, nothing seems to return using the below snippet:

ticker<-"BABA"
getSymbols(ticker)
tail(ticker,5)
spike<-augenSpike(as.vector(ticker[,5]
tail(spike)

tail(spike)
Error: unexpected symbol in:
"
tail"

Appreciate if you can take a look and tell me what went wrong? Million thanks for ur help.


Solution

  • Use auto.assign = TRUE in your getSymbols() call to return the data as an R object. In the code below, x contains the data for ticker. And you can use the Ad() function in quantmod to get the adjusted close column instead of using the column number.

    library(quantmod)
    ticker <- "RIVN"
    x <- getSymbols(ticker, auto.assign = FALSE)
    spike <- augenSpike(as.vector(Ad(x)))
    tail(spike)
    ## [1] -0.7975099 -0.2885007 -1.7847045 -1.7714723 -0.4984712  1.1262579
    

    Also, I would rewrite your augenSpike() function to take advantage of xts functionality. Then you don't need the as.vector() call.

    augen_spike <-
    function(x, n = 20) {
        prchg <- diff(x)
        lgchg <- diff(log(x))
        stdevlgchg <- rollapplyr(lgchg, n, sd)
        stdpr <- lag(x * stdevlgchg)
        spike <- prchg/stdpr
        return(spike)
    }
    tail(augen_spike(Ad(x)))
    ##            RIVN.Adjusted
    ## 2024-01-12    -0.7975099
    ## 2024-01-16    -0.2885007
    ## 2024-01-17    -1.7847045
    ## 2024-01-18    -1.7714723
    ## 2024-01-19    -0.4984712
    ## 2024-01-22     1.1262579