Put returns into quantiles for many time series

点点圈 提交于 2020-01-05 21:11:12

问题


I have a xts object of monthly returns (one column is a time series for one instrument). I want to know the quantile for each return, each month. I have my own set of instruments prices from a local database but I can reproduce with getSymbols.

I used quantile on stock returns to get the boundaries of my quantile. Then I tried to use cut to divide my returns into quantile but I am stuck there.

Ideally I should have a time series of monthly quantile for each instrument.

require(quantmod)
stocks <- c("GOOG","MSFT","AAPL","T","F","FB","GE","WMT","BA","BAC")
dataEnv <- new.env()
getSymbols(stocks, env=dataEnv)
stocks.prices <- do.call(merge, lapply(stocks,
  function(x) Cl(to.monthly(dataEnv[[x]], name=x))))

stocks.returns <- ROC(stocks.prices, n=1, type="discrete", na.pad=TRUE)
stocks.quantile <- t(apply(stocks.returns, 1, FUN=quantile, probs=seq(0,1,by=0.20), na.rm=TRUE))
stocks.cut <- t(apply(stocks.returns, 1, FUN=cut, breaks=stocks.quantile, include.lowest=TRUE))

回答1:


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)
}

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)


来源:https://stackoverflow.com/questions/34137554/put-returns-into-quantiles-for-many-time-series

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!