-1

Suppose these are the returns (1000 rows):

1-a
2-b
3-c

I want to calculate adjusted volatility: drop first return calculate realized volatility, then drop the second one and calculate the realized volatility and etc. if you have n returns you will have n realized volatility.

Volatility1 = b*b+c*c
Volatility2 = a*a+c*c
Volatility3 = a*a+b*b

I can handle it with for loop, but is there any other way?

Soheil
  • 954
  • 7
  • 20

2 Answers2

1

You can efficiently calculate it by sum(x*x)-x*x

#dummy data
x <- rnorm(1000)
#vectorized
f1 <- function(x) sum(x*x)-x*x
#for loop 
f2 <- function(x){
    n <- length(x)
    rv <- rep(NA, n)
    s <- x*x
    for(i in 1:n)
    {rv[i]=sum(s[-i])}
    rv
}
rbenchmark::benchmark(f1(x), f2(x))[1:3]
   test replications elapsed
1 f1(x)          100    0.0
2 f2(x)          100    3.1
Khashaa
  • 7,293
  • 2
  • 21
  • 37
0

Does it make sense? Maybe the function is wrong, but the structure seems to work.

Is volatility standard deviation?

            x <- rnorm(1000, sd=2)
            vol <- sapply(2:length(x), function(i) {
                sd(x[0:i])
            })
incitatus451
  • 163
  • 1
  • 6