I need to calculate the rolling downside standard deviation (252 days) of a time series with some data points missing.
First I thought of omitting the NAs with na.omit but since there is a lot of missing data, sometimes I'd calculate the downside standard deviation of way more than an actual year. So I defined my own function which turns out to be horribly runtime inefficient
data and output are xts time series.
My function:
sdDown<-function(x){
x<-x[!is.na(x)]
x<-x[x<0]
sdDown<-sd(x)
return(sdDown)
}
The actual calculation:
for(i in 1:ncol(data){
output[,i]<-rollapply(data[,i],252,sdDown)
}
A small sample of my data
2018-12-10 -1.20716203625699e-05 0.00040860164054784
2018-12-11 -4.59711501867298e-06 -5.5395807804004e-05
2018-12-12 -2.89544033163936e-06 -2.32695864665396e-05
2018-12-13 -4.6540811777524e-06 -4.09242194254659e-05
2018-12-14 -7.16508767049928e-06 -8.54853569873006e-05
2018-12-17 NA -0.000128077030929201
2018-12-18 -3.61378565521999e-06 2.4336464937079e-05
2018-12-19 -7.69458973030011e-06 -6.82301653554002e-05
2018-12-20 -7.90225954459822e-06 NA
2018-12-21 -6.248451592999e-06 -8.99672163515997e-05
2018-12-24 -0.0274338890319172 -0.000100111303817201
2018-12-25 NA NA
2018-12-26 NA NA
2018-12-27 -0.0210028378713459 -0.0484345012551812
2018-12-28 -4.4543361913201e-06 3.97861322771901e-05
2018-12-31 0.00854680934643593 -5.73227948577303e-05
It does calculate the correct results, however it is horribly runtime inefficient. Is there a more runtime efficient way to do this?
Thanks in advance! Please let me know if the question is phrased poorly.
Greetings Max