# How to calculate Empirical Cumulative Probability in R

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$ ?

• did you try quantile function? or i might have misunderstood and SPX_ecdf(-0.025) would be fine – berkorbay Sep 6 '16 at 19:43
• 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. – Forgottenscience Sep 6 '16 at 21:20

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.

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.

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