10

Rの株価の対数の密度推定値を取得しようとしています。を使用してプロットできることはわかっていplot(density(x))ます。ただし、実際には関数の値が必要です。

カーネル密度推定式を実装しようとしています。これが私がこれまでに持っているものです:

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)

どんな助けでも大歓迎です。何日もこれにいました!

4

1 に答える 1

20

density関数から直接値を取得できます。

x = rnorm(100)
d = density(x, from=-5, to = 5, n = 1000)
d$x
d$y

あるいは、本当に独自のカーネル密度関数を作成したい場合は、次のコードを使用して開始できます。

  1. ポイントzx範囲を設定します。

    z = c(-2, -1, 2)
    x = seq(-5, 5, 0.01)
    
  2. 次に、ポイントをグラフに追加します

    plot(0, 0, xlim=c(-5, 5), ylim=c(-0.02, 0.8), 
         pch=NA, ylab="", xlab="z")
    for(i in 1:length(z)) {
       points(z[i], 0, pch="X", col=2)
    }
     abline(h=0)
    
  3. 各ポイントの周りに正規密度を配置します。

    ## Now we combine the kernels,
    x_total = numeric(length(x))
    for(i in 1:length(x_total)) {
      for(j in 1:length(z)) {
        x_total[i] = x_total[i] + 
          dnorm(x[i], z[j], sd=1)
      }
    }
    

    曲線をプロットに追加します。

    lines(x, x_total, col=4, lty=2)
    
  4. 最後に、完全な見積もりを計算します。

    ## Just as a histogram is the sum of the boxes, 
    ## the kernel density estimate is just the sum of the bumps. 
    ## All that's left to do, is ensure that the estimate has the
    ## correct area, i.e. in this case we divide by $n=3$:
    
    plot(x, x_total/3, 
           xlim=c(-5, 5), ylim=c(-0.02, 0.8), 
           ylab="", xlab="z", type="l")
    abline(h=0)
    

    これはに対応します

    density(z, adjust=1, bw=1)
    

上記のプロットは次のようになります。

ここに画像の説明を入力してください

于 2013-01-27T20:08:49.843 に答える