6.7.2013

Reactive benefits with commodity option barrier events

Reactive programming offers many advantages over traditional imperative techniques when handling information streams like commodity market data. In this and several follow up posts I want to demonstrate some of the advantages I've found using these techniques. I'll be demonstrating this with c# and the Reactive Extensions framework.

Reactive Programming

What is reactive programming? From Wikipedia:

"reactive programming is a programming paradigm oriented around data flows and the propagation of change." en.wikipedia.org/wiki/Reactive_programming

Spreadsheet calculations are a great example of reactive techniques. If you are unfamiliar and want to know more look at the Wikipedia article or follow along in this series as I demonstrate some of the advantages.

Barrier options on commodity futures

I'm going to use barrier options to demonstrate the value of reactive programming. From Wikipedia:

a barrier option is an exotic derivative typically an option on the underlying asset whose price breaching the pre-set barrier level either springs the option into existence or extinguishes an already existing option. en.wikipedia.org/wiki/Barrier_option

If you aren't familiar with finance, an option is easy to think of as an insurance policy. One purpose is to protect a future purchase from major price changes. Imagine if you could buy insurance to cover the cost of gas if it rose above an extreme level, say $8/gallon.

To protect against major price swings you may need to pay a hefty premium. One way to reduce the premium is to purchase a barrier option. One way a barrier can work is to cancel the insurance policy. Say you are worried about gas rising above $8 a gallon but you doubt it will rise about $12. You might be willing to pay a reduced premium in exchange for the small chance that gas will breach $12 a gallon causing the policy to be canceled. Barriers in this case reduce the seller's risk and hence reduce premium.

If a breach occurs you might want to find out ASAP to mitigate the risk. This is the scenario I will use to demonstrate reactive techniques.

Traditional imperative approach

First I'll start with an imperative approach that is pretty common to come across.

Note: Most of the following code can be found in a more complete fashion here https://github.com/g0t4/blog-samples/tree/master/reactive/src.

Quote client

Many APIs that provide quotes in c# have been around a while and therefore use an event based interface:

var client = new FuturesQuoteClient();
client.Quotes += OnQuote;

Simply attach an OnQuote handler to process quotes.

Active barrier options by contract

In this example I'm going to assume there is a "cache" of options that gets updated periodically. The details of this are irrelevant.

_ActiveBarrierOptionsByContract = GetActiveBarrierOptionsByContract();

OnQuote handler

Here is an example of the OnQuote handler. I tried to leverage extracted methods and LINQ to show even in an imperative fashion, the code can be concise and clean (at least in my opinion):

private void OnQuote(object sender, FuturesQuote quote)
{
    var contract = ContractFromQuote(quote);
    if (IsValidContract(contract))
    {
        return;
    }
    IEnumerable<CommodityBarrierOption> activeBarrierOptionsForContract;
    if (!_ActiveBarrierOptionsByContract.TryGetValue(contract, out activeBarrierOptionsForContract))
    {
        return;
    }
    activeBarrierOptionsForContract
        .Where(option => BarrierIsBreached(option, quote))
        .Where(NoticeNotAlreadySent)
        .ToList()
        .ForEach(option => NotifyTheHumans(option, quote));
}

When the quote arrives, we parse the contract with ContractFromQuote. If the contract isn't valid we ignore the quote. When you interface with an external API there are going to be things you want to transform. This is part of your "Anti-Corruption layer" if you are familiar with domain driven design.

Without going into the details of options on futures, suffice to say the contract describes what type of gas (say regular versus premium) and when you will be buying it (a month). I'm really simplifying this as the location would matter too.

If _ActiveBarrierOptionsByContract doesn't contain the contract, we ignore the quote. We only care about quotes for contracts that we insured.

Next, we check each option to see if the BarrierIsBreached and if NoticeNotAlreadySent. If these conditions are met we'll NotifyTheHumans.

This example ignores any performance considerations. I'll address those in subsequent posts.

Refactoring towards reactive

Now let's refactor to incorporate reactive patterns. Starting imperative means the reactive solution will be somewhat "tainted" but will suffice to move us in the reactive direction.

Reactive benefit: decouple handler from source transforms

The imperative solution makes it difficult to decouple transforms and filters from handlers. Instead of receiving all FuturesQuotes, we only want to know about quotes with valid contracts. We could create new events and wire up conditions to trigger them. However, leveraging the reactive framework makes this possible with much less typing and in a much more expressive fashion.

Observables

First we have to wrap the FuturesQuote event to produce an observable. Think of this as a stream of FuturesQuotes:

private static IObservable<FuturesQuote> FuturesQuotesSource(FuturesQuoteClient client)
{
    return Observable
        .FromEvent<FuturesQuoteClient.QuoteHanlder, FuturesQuote>(h => client.Quotes += h, h => client.Quotes -= h);
}

This creates the observable:

var client = new FuturesQuoteClient();
FuturesQuotesSource(client)

We now have a stream of FuturesQuotes.

Transform

The Reactive Extensions provides LINQ operators that work on observables. In the example above we parse the contract into a local variable, instead we could create a new type QuoteWithContract and store both the quote and the parsed contract:

public class QuoteWithContract
{
    public FuturesQuote Quote { get; set; }
    public CommodityContract Contract { get; set; }

    public QuoteWithContract(FuturesQuote quote)
    {
        Quote = quote;
        Contract = ContractFromQuote(quote);
    }

    ...
}

Now we can apply the Select LINQ operator to transform our stream from FuturesQuote to QuoteWithContract:

var client = new FuturesQuoteClient();
FuturesQuotesSource(client)
    .Select(q => new QuoteWithContract(q))

Filter

The other thing we want to ensure is that the contract was valid, we can do this with the Where LINQ operator:

FuturesQuotesSource(client)
    .Select(q => new QuoteWithContract(q))
    .Where(IsValidContract)

private static bool IsValidContract(QuoteWithContract quote)
{
    return quote.Contract != null;
}

I like extracting method conditions to increase readability of the stream composition. We now have a stream of only quotes with a valid contract.

Reactive benefit: Thinking in streams

At this point we could Subscribe to the quotes stream and execute our imperative code:

private void OnQuote(QuoteWithContract quote)
{
    IEnumerable<CommodityBarrierOption> activeBarrierOptionsForContract;
    if (!_ActiveBarrierOptionsByContract.TryGetValue(quote.Contract, out activeBarrierOptionsForContract))
    {
        return;
    }
    activeBarrierOptionsForContract
        .Where(option => BarrierIsBreached(option, quote.Quote))
        .Where(NoticeNotAlreadySent)
        .ToList()
        .ForEach(option => NotifyTheHumans(option, quote.Quote));
}

But why not keep with the concept of a stream and re-frame our solution as producing a stream of barrier breach notices! To do this I've taken the above code and extracted this method that can take a quote and create the resulting breach notices:

private IEnumerable<BarrierBreachNotice> BarrierBreachNotices(QuoteWithContract quote)
{
    IEnumerable<CommodityBarrierOption> options;
    if (!_ActiveBarrierOptionsByContract.TryGetValue(quote.Contract, out options))
    {
        return Enumerable.Empty<BarrierBreachNotice>();
    }
    return options
        .Where(option => BarrierIsBreached(option, quote.Quote))
        .Select(option => new BarrierBreachNotice(option, quote));
}

public class BarrierBreachNotice
{
    public BarrierBreachNotice(CommodityBarrierOption option, QuoteWithContract quote)
    {
        Option = option;
        Quote = quote;
    }

    public CommodityBarrierOption Option { get; set; }
    public QuoteWithContract Quote { get; set; }
}

Now we can transform a stream of quotes, along with our active barrier options "cache", into a stream of BarrierBreachNotice. We'll use the SelectMany operator as each quote could generate more than one notice:

FuturesQuotesSource(client)
    .Select(q => new QuoteWithContract(q))
    .Where(IsValidContract)
    .SelectMany(BarrierBreachNotices)

And we want to avoid duplicate notices:

FuturesQuotesSource(client)
    .Select(q => new QuoteWithContract(q))
    .Where(IsValidContract)
    .SelectMany(BarrierBreachNotices)
    .Where(NoticeNotAlreadySent)

Reactive benefit: Descriptive subscriptions

Our original goal was to notify the humans:

FuturesQuotesSource(client)
    .Select(q => new QuoteWithContract(q))
    .Where(IsValidContract)
    .SelectMany(BarrierBreachNotices)
    .Where(NoticeNotAlreadySent)
    .Subscribe(NotifyTheHumans);

private void NotifyTheHumans(BarrierBreachNotice notice)
{
    ...
}

This subscription is much less work, no awkward += on an event and object sender overhead, a simple call to Subscribe!

Notice how easy it is to continue the idea of a stream. Transforms and filters are very easy to use to partition event handling into an ordered, composable pipeline. This is one of the extremely powerful aspects of reactive programming abstractions.

Next up

Next I want to discuss testing, further thinking in streams, performance and other considerations and how reactive programming techniques apply.





comments powered by Disqus