1
$\begingroup$

I have a dataset of S&P500 returns. How can I calculate the value of $F(X ⩽ x)$. My code is as below:

library(quantmod) # Loading quantmod library
getSymbols("^GSPC", from = as.character(Sys.Date()-365*16)) # SPX price date for 16 yrs

SPX <- dailyReturn(GSPC)
SPX_ecdf <- ecdf(as.numeric(SPX)) # dropping xts class

How do I calculate the probability of my data to be, let's say $\le -0.025$ ?

$\endgroup$
  • 3
    $\begingroup$ did you try quantile function? or i might have misunderstood and SPX_ecdf(-0.025) would be fine $\endgroup$ – berkorbay Sep 6 '16 at 19:43
  • 2
    $\begingroup$ If you just need point estimates, you don't need to convert it to the ECDF. You can just use mean(SPX <= -.025) to get the empirical probability. $\endgroup$ – Forgottenscience Sep 6 '16 at 21:20
1
$\begingroup$

quantile() does the opposite of what you want. You could bootstrap probabilities in a loop:

   pseq <- seq(0.001,1, by=0.001)
   quantile(yourdatahere, pseq)
  Quantiles[which(abs(Quantiles - (-0.025)) == min(abs(Quantiles - (-0.025))))]

This is a shitty inefficient verbose code but it works. ecdf() works too but I can't figure out how to force that data type to anything else.

$\endgroup$
1
$\begingroup$

You need to count the number of observations that are smaller than the threshhold. then divided it by the total number of observations. For example, you have a series of 250 returns, 50 of them is smaller than 1%,all other data is greater than 1%, than the empirical cumulative distribution function at 1% is 50/250.

$\endgroup$
1
$\begingroup$

This is what you do:

sum(SPX <= -0.025) / length(SPX)
## [1] 0.02536052

This works because TRUE is internally 1 and FALSE is 0.

Even shorter (as mentioned in the comments by @Forgottenscience):

mean(SPX <= -.025) 
## [1] 0.02536052

You could also use the Empirical Cumulative Distribution Function (as mentioned by @berkorbay) but I think this is overkill in this case:

SPX_ecdf(-0.025)
## [1] 0.02536052
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.