Flow and Statelessness

Computers are becoming too complicated to program efficiently with the imperative languages we are all familiar with (C, Java, R, Python and Javascript etc.).

The heirs to the throne are warm blooded, more user friendly and smarter.

When you begin to learn a functional language such as Haskell however there are some oddities that you need to get used to.

With one exception, procedural code is frowned upon. Haskell will execute code when it chooses.

That means code describes a series of transformations, declaring variables and recording state becomes redundant.

Functional programs are more or less stateless.

Cue hifalutin philosophising - but apart from all that the implementation of flow and transformations in code is elegant.

Let's say we want to find value at risk (VaR) for a certain price history.

These are the steps:

1) Take a chunk of prices (the lookback could be 5 years for example)

2) Sample by a set horizon period (for example monthly)

3) Calculate returns

4) Order

5) Pick xth percentile largest loss (for example 95th)

The code could take many forms.

An attempt might look like

a = chunk(prices);

b = sample(a);

c = returns(b)

d = order(c)

result = pick(d)

or perhaps,

pick(order(returns(sample(chunk(prices)))))

Naturally reading inside out.

However, the transformational flow approach looks like

prices->chunk()->sample()->returns()->order()->pick()

or if you prefer to read right to left

pick()<-order()<-returns()<-sample()<-chunk()<-prices

Perhaps prices is not fixed, but updates in real time. I.e. it is itself a flow, you could imagine that the program now updates VaR in near real time.

Maybe you want to incorporate data from several sources also? (aka signals)

pick()<-order()<-returns()<-sample()<-chunk()<-combine()<~prices~vols

Take a look at Elm for a very nice implementation.

I coded up a basic Javascript implementation here.

Some day all code will be as easy to read as this. Perhaps even Excel spreadsheet functions will jump on the band wagon at some stage.