Tag Archives: wpf

Dynamic D3 with Knockout.js

A couple of things happened recently that prompted me to write this blog post. Firstly, I’ve been playing around with HTML5/javascript based user interfaces and data visualisation. Secondly, I watched a fascinating presentation from UX guru Brett Victor, making me wonder if it was possible to create an interactive, data-drawing app like the one he demonstrates, purely with Javascript. There are 2 well established JS frameworks that we could combine to help us here: Knockout.js and D3. But can we make them work well together?
Continue reading Dynamic D3 with Knockout.js

Kinect SDK with F#

Just what do you think you're doing, Dave?
Just what do you think you're doing, Dave?
I finally got around to taking a look at the Kinect SDK the other day, partly because I was interested to see how the API looked from F#. Unfortunately getting it going turned out to be more of a pain than I was expecting.

The first bit was easy: I’m “lucky” enough to have one of the older Xboxes, which meant I’d had to get a Kinect with separate power, which is the one required by the SDK. Now all I needed was a Windows machine to develop on.
Continue reading Kinect SDK with F#

Public static fields gone from F# 2.0

There have been quite a few changes in F# version 2.0, which shipped as the first “official” version of the language as part of Visual Studio 2010. Most of the changes are detailed in various release notes on Don Syme’s blog and other places, but unfortunately one of the more significant changes passed me by, and turned out to be quite significant in the context of WPF development: public static fields are no longer supported. But what does this mean?

The change

The change itself is simple: static fields can no longer be public. Static fields can still be created, but they must be private.

In pre-2.0 versions of F# it was possible to declare a static field on a type like this:

type MyType() =
    static val mutable public MyProperty : int

Resulting in a type containing a static field, as you’d expect:

    .field public static int32 MyProperty

The code now generates the compiler error:

error FS0881: Static 'val' fields in types must be mutable, private and marked with the '[<DefaultValue>]' attribute. They are initialized to the 'null' or 'zero' value for their type. Consider also using a 'static let mutable' binding in a class type.

Notice that there are already some gnarly aspects to the definition of the property; notably the use of the [<DefaultValue>] attribute, which indicates that the field is un-initialized. This gives us a hint that there might be some inherent problems.

Why do we even need them?

In a word or three: WPF dependency properties.

The recommended way of implementing dependency properties in other .NET languages is to use public static fields, e.g. in C#:

    public static readonly DependencyProperty MyPropertyProperty =
          "MyProperty", typeof(int), typeof(MyType)); 

This is one of the few places where C# is terser than F#. Here we can declare and define the value in one line (ish), whereas F# requires a separate declaration of the field (as above) then initialisation in the static constructor (static do).

Why was it removed?

I got the answer from the horse’s mouth. Don Syme said that:

We deliberately removed the ability to create public static fields in Beta2/RC, because of issues associated with initialization of the fields (i.e. ensuring the “static do” bindings are run correctly, and if they are run, then they are run for the whole file, in the right order, with no deadlocks or uninitialized access when initialization occurs from multiple threads).

You can imagine how this would be a problem; there would need to be a way of ensuring that whichever static field was accessed it caused the static constructor to run, which may itself access static fields. All pretty nasty. In fact, Don mentioned that C# suffers from much the same synchronisation issues, but just tends to be used in a way that means it’s less likely to be noticed!

The alternative

At least in theory it’s possible to create a type that uses static properties rather than static fields to store its registered DependencyProperty information.

type Foo () =
    inherit FrameworkElement()
    static mutable private _myPropertyInternal : DependencyProperty 
    static member this.MyProperty with get () = _myPropertyInternal

Whether or not this works depends very much on how calling code accesses DependencyProperty information. If it uses reflection to access the field directly it will obviously fail. But if it uses a more robust/flexible method then it should be OK. Empirically it seems that the WPF framework code itself does the latter, for instance, when it’s instantiating objects from XAML, and it works properly independently of how it’s implemented.

The conclusion

So the conclusion is “wontfix”: the behaviour is by design. Unfortunately it has the effect that it’s no longer possible to create a type with an identical IL “signature” in both F# and C#. It seems a bit of a shame, but I guess the trade-off is that we’re protected against insiduous initialisation issues, so it will probably turn out to be the right thing in the long term.

A WPF custom control in F#

In the world of WPF with its powerful templating support, you’re much less likely to need to build a custom control from scratch than you are with legacy Windows GUI frameworks. For the vast majority of scenarios it’s possible to take an existing control and modify its appearance and behaviour to get what you need. However it is still possible and sometimes necessary to build something in code. The other day I was looking at creating one – using F# of course – and realised that a skeleton control serves as a good example of the kind of cross-paradigm features the language offers. They’re the kind of things that make it possible to use functional F# with inherently imperative .NET languages and frameworks like WPF.
Continue reading A WPF custom control in F#

FormatException in WPF DataBinding

While working on some F#/C# WPF code the other day, I kept hitting a fatal FormatException when running under the debugger. Annoyingly, the app would quit with:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.

But it worked fine when started from Expression Blend, or when run using Start Without Debugging in Visual Studio. Let’s take a closer look…
Continue reading FormatException in WPF DataBinding

Visualising Black-Scholes option pricing using F# and WPF

The other day I was looking for an example of some code relevant to finance that I could use as a test for experimenting with Windows Presentation Foundation (WPF) and F#. I decided I could use a simple Black-Scholes option pricer combined with WPF to easily visualise how the option inputs affect the value and greeks. For example, given all the usual Black-Scholes assumptions, and a non-zero interest rate, you’d expect the value of an at-the-money call option to increase as time to expiry increases, whereas a put option would decrease in value.

Calculating option values using F#

The first thing you need is an approximation to the cumulative normal distribution. I used the Abromowitz and Stegun approximation, which should give us enough precision. It’s fairly concise to implement in F#:

let ncdf x =
  let b1 =  0.319381530
  let b2 = -0.356563782
  let b3 =  1.781477937
  let b4 = -1.821255978
  let b5 =  1.330274429
  let p  =  0.2316419
  let c  =  0.39894228
  match x with
  | x when x >= 0.0 ->
    let t = 1.0 / (1.0 + p * x)
    (1.0 - c * Math.Exp( -x * x / 2.0)* t * (t*(t*(t*(t*b5+b4)+b3)+b2)+b1))
  | _ ->
    let t = 1.0 / (1.0 - p * x)
    (c * Math.Exp( -x * x / 2.0)* t * (t*(t*(t*(t*b5+b4)+b3)+b2)+b1))

The CDF should be near 0 for low values, around 0.5 for zero, and near 1 for high values. Let’s check:

> [-5.0; 0.0; 5.0] |> List.map ncdf;;
val it : float list = [2.871049992e-07; 0.500000001; 0.9999997129]

Looks good.

Now let’s put it to use by implementing the option pricing formula for call options:

let call strike spot (rate:float) (now:float) (expiry:float) (vol:float) =
    let exp = expiry-now
    let d1 = (Math.Log(spot/strike) + ((rate+(vol*vol)/2.0)*exp))/(vol * Math.Sqrt(exp))
    let d2 = d1 - (vol * (Math.Sqrt(exp)))
    (spot * ncdf d1) - (strike * Math.Pow(Math.E, -rate*exp)*(ncdf d2)), ncdf d1

Notice that the function returns a tuple of (value,delta). Give that the greeks are available analytically we may as well return them at the same time as the value.

We can poke this a bit to check that it’s doing the right thing. A call option that’s way in-the-money (i.e. spot > strike) near to expiry, has a lot of intrinsic value:

> call 10.0 100.0 0.0 0.0 0.1 0.5;;
val it : float * float = (90.0, 1.0)

An at-the-money call option should have a delta close to 0.5 at expiry:

> call 10.0 10.0 0.0 0.0 0.1 0.5;;
val it : float * float = (0.6301280626, 0.5315064031)

All seems fine.

So lets see what we can do about visualising these relationships.

Using WPF with F#

You’d be forgiven for thinking that the XAML markup language is the only way to construct user interfaces in WPF. Indeed, if you want to avoid writing code it’s the way to go. But unfortunately it’s not possible to use F# as the code-behind XAML files, so you’re forced to use C#. And it’s also not as dynamic or immediate as it could be; involving the usual write, compile, run iteration. We can do better in F# using scripts and F# interactive (FSI).

The key is to construct the WPF object model imperatively, rather than declaratively with XAML. Yeah, I know this is normally the opposite of what you’d want to do.

For instance, here’s some code to create a Canvas. Note the use of a construction expression to both create the object and set some of it’s properties. This is just syntactic sugar which helps to make the object look slightly less mutable than it actually is:

    let c = new Canvas(Name="Canvas", Width=250.0, Height=250.0)
    c.Background <- SolidColorBrush(Color.FromRgb(228uy,228uy,228uy))

We can use the WPF canvas panel to enable us to explicitly place points (or rather, Rectangles) on our plot, it uses absolute locations rather than the implied flow layout of the other containers (Grid, StackPanel etc). Putting this together, we can write a function which will take a parent Panel, and a list of (x,y) tuples and create a plot:

let plot (panel:Panel) (pts:(double * double) list) =
    let bgc = new Canvas(Name="Canvas", Width=300.0, Height=300.0)
    let c = new Canvas(Name="Canvas", Width=250.0, Height=250.0)
    c.SetValue(Canvas.LeftProperty, 25.0)
    c.SetValue(Canvas.TopProperty, 25.0)
    c.Background <- SolidColorBrush(Color.FromRgb(228uy,228uy,228uy))
    let x,y = pts |> List.unzip
    let xmin,xmax = x |> List.min, x |> List.max
    let ymin,ymax = y |> List.min, y |> List.max
    let xscale = c.Width / (xmax-xmin)
    let yscale = c.Height / (ymax-ymin)
    |> List.map (fun pt ->
        let p = new Rectangle(Width=2.0,Height=2.0)
        p.Stroke <- new SolidColorBrush(Color.FromRgb(0uy,0uy,0uy))
        p.SetValue( Canvas.LeftProperty, (fst pt - xmin) * xscale)
        p.SetValue( Canvas.TopProperty, c.Height - (snd pt - ymin) * yscale)
    |> List.iter (fun rect ->
        ignore <| c.Children.Add rect)
    ignore <| bgc.Children.Add (fst (makeYScale ymin ymax))
    ignore <| bgc.Children.Add (fst (makeXScale xmin xmax))
    ignore <| bgc.Children.Add c
    ignore <| panel.Children.Add bgc

The function returns nothing (unit in F# parlance) and performs a side-effecting modify of the passed Panel. I've omitted the makeXScale and makeYScale functions, as they're a bit gnarly, and don't really serve to demonstrate anything in particular.

Now we need to create some data to plot. We can do this in many ways, but one thing I looked at was creating a set of call option values with varying time to expiry. I thought this could use a floating point sequence, but it generated a deprecation warning, so I decided to do it long hand instead. This function returns a list of (time,value) tuples, where time range from rfrom to rto in num steps and value is calculated using the passed function f.

let varyExpiry f num rfrom rto =
    List.init num (fun n ->
        let s = rfrom + ((float n/float num) * (rto-rfrom))
        float s, fst <| f 10.0 10.0 0.05 0.0 s 0.5 )

We can pass the resulting list directly to our plot function, but first we need to create a window to display it in:

let w = new Window(Name="Plot",Width=500.0,Height=500.0)
let wp = new WrapPanel()
w.Content <- wp
w.Visibility <- Visibility.Visible

Executing this code in FSI will display a blank window (probably behind your active window if you're within Visual Studio). Then we can add the plot to the graph:

plot wp (varyExpiry call 100 10.0 100.0)

Voila! Obviously the plot is very, very basic, but it's an interesting experiment, and it does makes it extremely easy to plot functions interactively in almost the same way as you can with applications like Excel and MatLab. Pretty powerful.

Call option values for varying expiries
Call option values for varying expiries
Call and put option values for varying expiries
Call and put option values for varying expiries