且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将收益分成许多时间序列的分位数

更新时间:2023-02-27 08:48:08

我已经创建了一个函数 GetQuantile 来完成这项工作(但可能不是以一种优雅的方式).

I have made a function GetQuantile which does the work (but maybe not in an elegant way).

GetQuantile<-function(x,q,n){
  # Extract the nth quantile from a time series
  #
  # args:
  #   x = xts object
  #   q = quantile of xts object
  #   n = nthe quantile to extract
  #
  # Returns:
  #   Returns an xts object of quantiles

  # TRUE / FALSE depending on the quantile we are looking for
  if(n==1) # first quantile
    test<-xts((coredata(x[,])<c(coredata(q[,2]))),order.by = index(x))
  else if (n== dim(q)[2]-1) # last quantile
    test<-xts((coredata(x[,])>=c(coredata(q[,n]))),order.by = index(x))
  else # else
    test<-xts(  (coredata(monthly.returns[,])>=c(coredata(q[,n]))) &
                (coredata(monthly.returns[,])<c(coredata(q[,(n+1)])))  ,order.by = index(x))
  # replace NA by FALSE
  test[is.na(test)]<-FALSE
  # we only keep returns for which we need the quantile
  x[test==FALSE]<-NA
  return(x)
}

通过这个函数,我可以得到一个 xts,其中包含我想要的分位数和 NA 的所有月度回报.有了这个 xts,我可以做一些事情,比如计算每个分位数等的平均值..

with this function I can have an xts with all the monthly returns of the quantile I want and NA everywhere else. With this xts I can do some stuff like computing the mean for each quantile ect..

monthly.returns.stock.Q1<-GetQuantile(stocks.returns,stocks.quantile,1)
rowMeans(monthly.returns.stock.Q1,na.rm = TRUE)