Binomial Option Pricing in Actionscript
2009
The binomial option pricing model is one of the simplest pricing models to understand and code. I’m not going to go into an explanation of the model itself, as that would take more time than I’m willing to expend, however I think it’s always useful to have example code lying around and I’m quite happy for some of it to lie around on my website.
private function getPrice( N:Number, //Number of steps T:Number, //Time to expiry (in years) S:Number, //Spot price of underlying K:Number, //Option strike v:Number, //Volatility of underlying r:Number //risk-free rate ):Number { var dt:Number = T/N; //one time step var u:Number = 1 + v*Math.sqrt(dt); //up-tick var d:Number = 1 - v*Math.sqrt(dt); //down-tick var p:Number = 0.5 + r*Math.sqrt(dt)/(2*v); //risk-neutral prob. of up-tick var df:Number = 1/(1+r*dt); //discount factor over 1 time step, dt var optionValues:Array = new Array(N+1); //populate the tree (for N-steps there will be N+1 values) var i:int, j:int, ST:Number; for (i=0; i < N+1; i++) { ST = spot.value * Math.pow(u, i) * Math.pow(d, N-i); optionValues[i] = (ST > K)? ST - K : 0; } //now work backwards to get expected option value at each previous stage for (i=N; i >= 0; i--) { for(j=0; j<i; j++) { optionValues[j] = (p*optionValues[j+1] + (1-p)*optionValues[j])*df; } } return optionValues[0]; }
What I’ve written is slightly different from some of the examples you might see (though exactly what Wikipedia suggests) – I don’t bother building up an array of stock prices since each value in the final array can be calculated with a simple formula. This means that I’ve removed a couple of loops from the calculation and (roughly) halved the execution time. I’m also assuming that we’re pricing a vanilla call option and that the risk-free rate is discretely compounded, though it would be fairly trivial to replace the call payoff function ((ST > K)? ST – K : 0) with any kind of external payoff function and to replace the discrete discount factor with a continuous one (1+rt becomes erT, essentially). In the end, with enough time steps, these kinds of changes make only a little difference though.
Have a play :
And for comparison, here’s a Black-Scholes pricer :
Comment