Home > Software engineering >  'x' has to be an array of at least two dimensions
'x' has to be an array of at least two dimensions

Time:12-17

I have been trying to price knock-in and knock-out options, but I have a problem I can't seem to solve: when coding the knock-in option, with the code:

knockInOptionMC <- function( Type = c('Call','Put'), Type2 = c('Down In', 'Up In'), P, T., r, K, B){
 
  if(Type2 == 'Down In'){
    knockedIn <- P < B
  }else{
    knockedIn <- P > B
  }
  
  alive <- colSums(knockedIn) == 1
  PT <- tail(P,1)
  
  if(Type == 'Call'){
    payoff <- ( PT > K ) * (alive) * ( PT - K )
  }else{
    payoff <- ( PT < K ) * (alive) * ( K - PT )
  }
  
  simulatedPayoff <- exp( -r * T. ) * payoff
  return( mean(simulatedPayoff) )
  
}

knockInOptionMC('Put','Down In', P, T., r, K = 105 , B = 105)

I get no error, but when I try to do the same thing for the knock out, with the following code:

knockOutOptionMC <- function( Type = c('Call','Put'), Type2 = c('Down Out', 'Up Out'), P, T., r, K, B){
  
  if(Type2 == 'Down Out'){
    knockedOut <- P < B
  }else{
    knockedOut <- P > B
  }
  
  alive <- colSums(knockedOut) == 0
  PT <- tail(P,1)
  
  if(Type == 'Call'){
      payoff <- ( PT > K ) * (alive) * ( PT - K )
    }else{
      payoff <- ( PT < K ) * (alive) * ( K - PT )
    }
  
  simulatedPayoff <- exp( -r * T. ) * payoff
  return( mean(simulatedPayoff) )
  
}

knockOutOptionMC( 'Put','Up Out', T., r, K = 105, B = 95 )

I get the error 'x' has to be an array of at least two dimensions in the object colsums. why why why do I get the error since they're basically the same thing? thank you sm

CodePudding user response:

The error likely comes from the colSums() line - which needs its argument to be two-dimensional to have columns.

The core of the problem is not in the function, but how you call them:

knockInOptionMC ('Put', 'Down In', P, T., r, K = 105, B = 105)
knockOutOptionMC('Put', 'Up Out',     T., r, K = 105, B = 95 )

So you are likely passing a two-dimensional variable P in the first case, but missing it in the second, and pass a one-dimensional T. instead.

Chances are that the function run successfully in case 2 because you have the missing variables defined in the parent environment.

  •  Tags:  
  • r
  • Related