class Stock def initialize (initial_price = 100, up = 1.04574) @initial_price = initial_price @up = up @down = 1/up end def calculateStock (n) Array.new(n + 1) {|i| @initial_price * (@up**( n - i))*(@down**i)} end def calculateOption (n, t = 0, strike = 100, r = 1.0005, call = -1) q = (r - @down) / (@up - @down) q1 = 1- q stock_price_n = calculateStock (n) option_price_n = stock_price_n.map { |i| [(i - strike)*call, 0].max } array_length = n + 1 (t..(n-1)).each{ |index| array_length = array_length - 1 option_price = calculateStock (array_length - 1).map { |i| [(i - strike)*call, 0].max } option_price_n = Array.new(array_length) {|i| [(option_price_n[i] * q + option_price_n[i+1] * q1)/r, option_price[i]].max } } option_price_n end end stock = Stock.new #print stock.calculateStock (0) #print stock.calculateStock (1) #print stock.calculateStock (2) print stock.calculateOption (10) #print stock.calculateOption (5) #print stock.calculateOption (6)
↧
Ruby function for Option value calculation
↧