braverock / PerformanceAnalytics

211 stars 105 forks source link

VaR.r historical VaR not working with weights #169

Closed st501351 closed 2 years ago

st501351 commented 2 years ago

VaR.r historical VaR not working with weights

Sorry, not really a github-er. I would fix this if I could. Sorry if I am not understanding everything.

Expected behavior

Minimal, reproducible example

works as expected

VaR(edhec,method = "historical") 

crashes

VaR(edhec,weights = rep(1/ncol(edhec),ncol(edhec)), method = "historical")

Does this fix it?

I think the fix is just to change line 464 from

historical = { rVaR = VaR.historical(R=R,p=p) %*% weights } # note that this is weighting the univariate calc by the weights

to

historical = { rVaR = VaR(R=R,p=p) %*% weights } # note that this is weighting the univariate calc by the weights
braverock commented 2 years ago

I can confirm that the current code is broken, but your patch is incorrect.

R core made a change to how %*% works with non matrix inputs. The output of VaR.historical is a data.frame, not a matrix, so no longer works with %*% in more recent version of R.

historical = { rVaR = VaR.historical(R=R,p=p) %*% weights } # note that this is weighting the univariate calc by the weights

should probably be:

historical = { rVaR = as.matrix(VaR.historical(R=R,p=p)) * weights } # note that this is weighting the univariate calc by the weights

now, as the comment here notes, this is just a straight weighted multiplication. It isn't terribly useful to really get at risk contribution. The component methods for the other VaR methods will give estimates that have more value in making inferences about VaR.

st501351 commented 2 years ago

Oh that's an odd change. Was that 4.0? Agreed on substance, just curious about getting it working.

braverock commented 2 years ago

well, I committed a fix, so if you used e.g. remotes::install_github('braverock/PerformanceAnalytics') that should give you the latest and greatest. We'll probably also do a CRAN release sometime this quarter to get some of the latest functionality on e.g. robust betas and the usual small bugfixes like this one into the released package.