I am trying to get density estimates for the log of stock prices in R. I know I can plot it using plot(density(x))
. However, I actually want values for the function.
I'm trying to implement the kernel density estimation formula. Here's what I have so far:
a <- read.csv("boi_new.csv", header=FALSE)
S = a[,3] # takes column of increments in stock prices
dS=S[!is.na(S)] # omits first empty field
N = length(dS) # Sample size
rseed = 0 # Random seed
x = rep(c(1:5),N/5) # Inputted data
set.seed(rseed) # Sets random seed for reproducibility
QL <- function(dS){
h = density(dS)$bandwidth
r = log(dS^2)
f = 0*x
for(i in 1:N){
f[i] = 1/(N*h) * sum(dnorm((x-r[i])/h))
}
return(f)
}
QL(dS)
Any help would be much appreciated. Been at this for days!
You can pull the values directly from the
density
function:Alternatively, if you really want to write your own kernel density function, here's some code to get you started:
Set the points
z
andx
range:Now we'll add the points to a graph
Put Normal density's around each point:
and add the curves to the plot:
Finally, calculate the complete estimate:
This corresponds to
The plots above give: