Skip to content

Instantly share code, notes, and snippets.

@MichaelChirico
Created November 22, 2016 16:48
Show Gist options
  • Save MichaelChirico/05ba611f70ff8c57388d945f570a31dd to your computer and use it in GitHub Desktop.
Save MichaelChirico/05ba611f70ff8c57388d945f570a31dd to your computer and use it in GitHub Desktop.
testing quantiles
set.seed((1234))
library(data.table)
annual_data <- data.table(year=1991:2000,ret=rnorm(200),group=1:20)
annual_data[ , decile2 := funchir::create_quantiles(ret, 10), by = year]
yearly_deciles <- annual_data[,data.table(t(quantile(ret,probs=seq(from=.1, to = 1, length.out=10)))),by=year]
find_decile <- function(thisReturn,year,decile_table){
for(i in 2:ncol(decile_table)){
if(thisReturn<decile_table[year==year,i,with=F])
return(i-1)
}
}
annual_data[,decile:=find_decile(ret,year,yearly_deciles),by=c("group","year")]
annual_data[decile2 != decile]
# year ret group decile2 decile
# 1: 1992 0.2774292 2 9 8
# 2: 1995 0.4291247 5 6 8
# 3: 1996 0.5060559 6 7 8
# 4: 1997 -0.5747400 7 5 3
# 5: 1998 -0.5466319 8 6 3
# ---
# 165: 1994 0.4878146 14 8 7
# 166: 1995 2.1680325 15 10 9
# 167: 1997 0.6202102 17 8 3
# 168: 1998 -0.9659032 18 4 2
# 169: 1999 0.1626547 19 5 2
yearly_deciles
# year 10% 20% 30% 40% 50%
# 1: 1991 -1.2669623 -0.5999266 -0.4072242 -0.25117543 -0.1845911
# 2: 1992 -1.0054121 -0.6756371 -0.5181029 -0.47506832 -0.3580541
# 3: 1993 -1.1159853 -0.9060696 -0.7802718 -0.54810474 -0.3904718
# 4: 1994 -1.0956894 -0.7108254 -0.5016240 -0.22207968 -0.1411094
# 5: 1995 -1.0578154 -0.7201759 -0.2622917 0.01037561 0.2644080
# 6: 1996 -0.9884248 -0.4601983 -0.1232194 0.13221742 0.3774111
# 7: 1997 -1.2589292 -1.1354080 -1.1122516 -0.73735143 -0.5428747
# 8: 1998 -1.3582227 -1.0931034 -0.9832290 -0.82849022 -0.6351068
# 9: 1999 -0.6562070 -0.5319529 -0.3022577 -0.08572049 0.1988380
# 10: 2000 -1.1614805 -0.8992200 -0.5346564 -0.42043523 -0.2577377
# 60% 70% 80% 90% 100%
# 1: -0.02913816 0.218218814 0.7280088 1.1370174 1.704329
# 2: -0.14191268 0.059556665 0.2532393 0.3892011 2.548991
# 3: -0.21349855 0.237197769 0.9977136 1.6454666 2.058162
# 4: 0.20422286 0.468056999 0.6523721 0.7603787 1.001513
# 5: 0.46297992 0.868859228 1.0498477 1.8488146 2.168033
# 6: 0.50283913 0.581529012 0.7243151 1.4036260 1.983732
# 7: -0.28351943 0.557424862 0.7299899 1.6493214 1.678206
# 8: -0.46633500 0.002370059 0.1903998 0.9271660 3.043766
# 9: 0.29694436 0.556340728 0.7473556 1.0085816 1.605910
# 10: -0.04456651 0.049496996 0.3386886 1.5360169 2.415835
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment