本文介绍了将收益分成许多时间序列的分位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个每月回报的 xts 对象(一列是一种工具的时间序列).我想知道每个月的每个回报的分位数.我从本地数据库有自己的一组工具价格,但我可以使用 getSymbols 进行复制.

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.

我在股票收益上使用了 quantile 以获得我的分位数的边界.然后我尝试使用 cut 将我的回报分成分位数,但我被困在那里.

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

推荐答案

我已经创建了一个函数 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)

这篇关于将收益分成许多时间序列的分位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 15:47