Skip to content

Building a multi-threaded Monte Carlo stock price calculator in Silverlight using F#

August 1, 2011

Introduction.

In this post I’m going to demonstrate how to build a simple Monte Carlo stock pricer. I’m going to take advantage of F#’s Async library to parallelise the pricer. Thanks to Keith for reviewing some of the financial explanation, and to Jose for a quick code review!

Stock pricing background.

Before talking about the stock pricing theory, a few definitions:

  • Volatility σ, is a measure for variation of price of a financial instrument over time,
  • Growth rate μ, is the rate at which a stock price has increased/decreased within a specific period of time,

Using measures of volatility and growth rate of a stock price we can, using some model, get an estimate for the value of a stock price at some point in the future. How do we do this? We can conduct a log normal random walk (otherwise know as Geometric Brownian motion with drift). This formula shows how we can calculate the change in stock price at a timestep t within our each of our random walks:

Formula for the discrete time version of geometric brownian motion
Formula for the discrete time version of geometric brownian motion

Note that ε is a normally distributed random number with mean 0 and standard deviation of 1.

What we are aiming to calculate are a number of random walks that our stock price could potentially follow:

Ten lognormal random walks showing possible paths a stock price could follow Ten lognormal random walks showing possible paths a stock price could follow

What do we do once we have run these random walks? Well we can take the mean price from each random walk  for some point in time. As well as calculating the mean, we can also calculate the standard deviation. The lower the stddev, the more accurate our mean stock price is likely to be.

(note: the data output from our random walks can be used to value derivatives where the underlying value is the stock in question)

Design

I’m going to split up my design into three layers, the Silverlight view, the (imperative) ViewModel code and (more functional) Statistics and Pricing modules. Note that this follows the MVVM design pattern.

Implementation

Lets start with the functional parts of the code base, here is the main function which conducts the random walks asynchronusly and returns the stddev and mean:

Note that as well as running each random walk asynchronously, the function is an asynchronous itself, this will help us out later when we are dealing with running calculations asynchronously to the UI thread.

note that you can find an implementation of NormsInv on my previous post: https://ashleyaberneithy.wordpress.com/2011/07/20/normsinv-function-in-f/

The next step is to have a look at the view model code, I’ve written two view model types, the first one is called StockPricerViewModel, and it’s responsibility is to control the main UI. It exposes properties such as vol (for volatility) and drift (for growth rate). It also exposes a collection of type CalculationResultViewModel.

For each calculation run by the user, a new instance of the CalculationResultViewModel is created, and once it’s RefreshResult function has been run will update it’s mutable members with the results (i.e the mean and stddev) of the stock price calculation, here is what that class looks like:

Testing

Here is a UI that I made eariler, which is now bound to the view model layer:

Silverlight UI for our stock pricer
Silverlight UI for our stock pricer

As you can see from the data grid at the bottom of the UI the user can run multiple calculations and the .net threadpool which underpins F# Async library will nicely queue calculations up.

If we open up task manager whilst calculations are in flight, we can see that most of the CPU is being used to perform our random walks:

CPU usage whilst performing the Monte Carlo simulation
CPU usage whilst performing the Monte Carlo simulation

Conclusions

We can use Silverlight and F# in interesting way to deliver industry standard pricing tools to users desktop machines through a web browser.

Advertisements
4 Comments leave one →
  1. January 4, 2013 11:07 am

    Instead of Async.Parallel [ for i in 0 .. iterations -> async {return SOMETHING()}] |> Async.RunSynchronously use Array.Parallel.map (fun _ -> SOMETHING()) [| 0 .. iterations |]
    It’s not just shorter, it’s many times faster and uses less memory.

  2. January 4, 2013 2:53 pm

    Good point Gustavo – Will make a change to the code :)

  3. Paul permalink
    May 23, 2013 8:59 pm

    Hi,
    Thanks for putting this up. Very interesting. Would you consider putting the entire solution up? I’d be interested to see the Silverlight aspect and how you got it working.

    Thanks
    Paul

  4. Paul permalink
    May 23, 2013 9:01 pm

    Hi
    Thanks for putting this up. Would you consider putting the entire solution code up? The Silverlight aspect looks very cool.

    Thanks
    Paul.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: