matrix - Generate lattice paths in R -


for example, if have lattice looks this:

          133.1          /        121       /  \     110   108.9    /  \  /   100   99    \  /  \     90    89.1       \  /        81          \           72.9 

where lattice starts @ 100 , either goes factor 1.1 , goes down factor 0.9. lattice has 3 periods in goes or down. clear matrix filled in more periods.

the lattice in matrix form looks this:

     [,1] [,2] [,3]  [,4] [1,]  100  110  121 133.1 [2,]   na   90   99 108.9 [3,]   na   na   81  89.1 [4,]   na   na   na  72.9 

i'm working in r. code generate lattice matrix follows:

#parameters s0 <- 100 #price @ t0 u <- 1.1 #up factor d <- 0.9 #down factor n <- 3 #number of periods  #matrix prices prices <- matrix(data=na, nrow=(n+1), ncol=(n+1)) prices[1,1] <- s0  #fill matrix for(column in 2:(n+1)){    for(row in 1:(column-1)){      prices[row,column] <- u*prices[row,column-1];   }    prices[column,column] <- d*prices[column-1,column-1]; } 

i create code generates matrix possible paths through lattice. example, this:

     [,1] [,2] [,3]  [,4] [1,]  100  110  121 133.1 [2,]  100  110  121 108.9 [3,]  100  110   99 108.9 [4,]  100  110   99  89.1 [5,]  100   90   99 108.9 [6,]  100   90   99  89.1 [7,]  100   90   81  89.1 [8,]  100   90   81  72.9 

i've been struggling piece of code hours now, appreciated! in advance! :)

each path of length n corresponds sequence of , down movements: have enumerate sequences. if have sequences of length n-1, matrix u, sequences of length n can obtained

rbind(    cbind( u,  .9 ),    cbind( u, 1.1 )  ) 

you can put in function, , call n times.

n <- 4   <- 1.1 down <- .9 m <- reduce(    function(u,v) rbind( cbind( u, ), cbind( u, down ) ),    rep(na,n),    100 ) t(apply(m, 1, cumprod)) #  [1,] 100 110 121 133.1 146.41 #  [2,] 100  90  99 108.9 119.79 #  [3,] 100 110  99 108.9 119.79 #  [4,] 100  90  81  89.1  98.01 #  [5,] 100 110 121 108.9 119.79 #  [6,] 100  90  99  89.1  98.01 #  [7,] 100 110  99  89.1  98.01 #  [8,] 100  90  81  72.9  80.19 #  [9,] 100 110 121 133.1 119.79 # [10,] 100  90  99 108.9  98.01 # [11,] 100 110  99 108.9  98.01 # [12,] 100  90  81  89.1  80.19 # [13,] 100 110 121 108.9  98.01 # [14,] 100  90  99  89.1  80.19 # [15,] 100 110  99  89.1  80.19 # [16,] 100  90  81  72.9  65.61 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -