R: Проблемы с областью при создании для l oop внутри функции - PullRequest
0 голосов
/ 11 апреля 2020

Приведенный ниже код работает так, как задумано, когда функция create_table удалена и выполняется только команда для l oop. Однако, когда я включаю функцию, я получаю сообщение об ошибке «объект« я »не найден». Я считаю, что проблема связана с тем, что я являюсь глобальным, а не локальным, поскольку, когда я определяю i глобально, функция запускается, но дельта-переменная не повторяется.

Как я могу переписать функцию, чтобы и дельта, и переменные вызова перебирались для каждого l oop?

  k <- 40; tt<-(91/365); d <- 0; v <- .3; r <- .08; s0<- 40; s <-c(40.5,39.25,38.75,40,40)


create_table <-function(s0,s,k,v,r,tt,d){
  #calculate initial values
  put <- 100*bsput(s0,k,v,r,tt,d)
  delta <-100*data.frame(greeks(bsput(s0,k,v,r,tt,d)))[2,]
  investment <- s0*delta+put

  #define starting states
  interest <- 0; cap_gain <- 0; profit <-0

  #create 0th column and put it into a dataframe
  df<-(rbind.data.frame(s0,put,delta,investment,interest,cap_gain,profit))

  #for loop computes the other four rows of the table
  for (i in s){
    #time to expiration increases by one day each loop
    tt <- (tt - 1/365)

    #yesterday's total is previous value of the position, used to calculate capital gains
    #it computes the previous days stock, delta & put  
    yesterday_total <- s0*delta-put
    put <- 100*bsput(i,k,v,r,tt,d)
    s0 <- i

    #captial gain computes the change in stock*delta and the difference between consecutive days calls
    cap_gain <- -(yesterday_total - (s0*delta -put))
    delta <- 100*data.frame(greeks(bsput(i,k,v,r,tt,d)))[2,]

    #calculate intrest paid by multiplying daily intrest rate by previous days investment
    interest <- -(exp(r/365)-1)*investment 
    investment <- delta*i-put
    profit <- cap_gain + interest

    #compile resutls into a single column and combine with previous columns
    c <- rbind.data.frame(i,put,delta,investment,interest,cap_gain, profit)
    colnames(c)<- i
    df <- cbind(df,c)
  }
  rownames(df) <- c("Stock", "Put", 
                    "Delta", "Investment",
                    "Interest", "Capital gains", 
                    "Daily profit")
  colnames(df) <-c("0","1","2","3","4","5")
  t <- kable(round(df,2))
  return(t)
  }


create_table(s0,s,k,v,r,tt,d)

Ошибка при использовании create_table ():

Error in eval(x[[z91k25]]) : object 'i' not found 
...