Andrei
Andrei

Reputation: 3

Creating a vector of mobile variances of a time series

I am trying to create a vector of 50 trading days variances of a time series. With the following for cycle (which works fine for the mean) I am getting a vector of "NULL":

for(i in 1:1742){
  TSLA$mean50[i] = mean(TSLA$rendimenti[i:i+49])
}

for(i in 1:1742){
  TSLA$var50[i] = as.numeric(var(TSLA$rendimenti[i:i+49]))
}

This is what my XTS data looks like

For some reasons if I add values manually (by replacing the index i with a specific value) the code works perfectly fine.

Upvotes: 0

Views: 22

Answers (1)

slowowl
slowowl

Reputation: 694

for(i in 1:1742){
  TSLA$mean50[i] = mean(TSLA$rendimenti[i:(i+49)])
}

for(i in 1:1742){
  TSLA$var50[i] = as.numeric(var(TSLA$rendimenti[i:(i+49)]))
}

Upvotes: 1

Related Questions