问题
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