<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>voyce &#187; Finance</title>
	<atom:link href="http://www.voyce.com/index.php/category/finance/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.voyce.com</link>
	<description>Programming and debugging tidbits</description>
	<lastBuildDate>Sat, 03 Jul 2010 12:40:51 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Generating and plotting random numbers</title>
		<link>http://www.voyce.com/index.php/2009/11/24/generating-and-plotting-random-numbers/</link>
		<comments>http://www.voyce.com/index.php/2009/11/24/generating-and-plotting-random-numbers/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 23:44:55 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=562</guid>
		<description><![CDATA[An example of generating random numbers in F# and visualising their distribution using the WPF charting control.]]></description>
			<content:encoded><![CDATA[<p>For a while now I&#8217;ve been planning to write a blog post about pricing financial instruments using Monte Carlo techniques in F#. As part of this I needed to generate normally distributed random numbers, and while putting together the code to do it I realised it was interesting enough to warrant its own post.</p>
<p>I&#8217;m making use of a few F#/.NET idioms to make the process easier. For instance, sequences (.NET&#8217;s <code>IEnumerable</code>) are used as the source of uniformly distributed random numbers. Also, to verify that the resulting numbers are actually normally distributed, we can easily use existing WPF/silverlight controls to visualise the values direct from within Visual Studio, in a manner similar to <a href="http://www.voyce.com/index.php/2009/06/26/black-scholes-option-pricing-using-fsharp-and-wpf/">this previous post</a> &#8211; but without having to write the plotting code ourselves.<br />
<span id="more-562"></span></p>
<h3>Implementation</h3>
<p>So firstly, we create the random number stream:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> rr <span style="color: #000080;">=</span> System<span style="color: #000080;">.</span><span style="color: #505090;">Random</span><span style="color: #000080;">&#40;</span>System<span style="color: #000080;">.</span><span style="color: #505090;">DateTime</span><span style="color: #000080;">.</span><span style="color: #505090;">Now</span><span style="color: #000080;">.</span><span style="color: #505090;">Minute</span><span style="color: #000080;">&#41;</span>
<span style="color: #06c; font-weight: bold;">let</span> rands <span style="color: #000080;">=</span> seq <span style="color: #000080;">&#123;</span> <span style="color: #06c; font-weight: bold;">while</span> <span style="color: #06c; font-weight: bold;">true</span> <span style="color: #06c; font-weight: bold;">do</span> <span style="color: #06c; font-weight: bold;">yield</span> rr<span style="color: #000080;">.</span><span style="color: #505090;">NextDouble</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#125;</span></pre></div></div>

<p>As you can see <code>rands</code> is an infinite sequence. As such, you should be wary of the &#8220;eager&#8221; functions from the Seq module that attempt to consume the entire sequence at once, they&#8217;ll obviously cause a problem here. Also notice that I&#8217;ve picked a somewhat dubious seed for the random number generator, as this is only for demonstration purposes.</p>
<p>In order to obtain normally distributed random numbers I&#8217;m using the <a href="http://en.wikipedia.org/wiki/Box–Muller_transform">Box-Muller</a> transform. I started off with an implementation transcribed from VBA (from <a href="http://www.amazon.com/gp/product/0470319585?ie=UTF8&#038;tag=wwwvoycecom-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0470319585">Wilmott</a><img src="http://www.assoc-amazon.com/e/ir?t=wwwvoycecom-20&#038;l=as2&#038;o=1&#038;a=0470319585" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> et al) &#8211; yes, yes, I know &#8211; but of course this used mutable references. Not nice. So I reworked it a little to use <code>Seq.pick</code>, which takes items from the sequence while a predicate returns <code>None</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> boxMuller <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #000080;">&#40;</span>x,dist<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span> 
        rands
        <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">pick</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> x <span style="color: #000080;">-&gt;</span>
            <span style="color: #06c; font-weight: bold;">let</span> x <span style="color: #000080;">=</span> <span style="color: #c6c;">2.0</span> <span style="color: #000080;">*</span> x <span style="color: #000080;">-</span> <span style="color: #c6c;">1.0</span>
            <span style="color: #06c; font-weight: bold;">let</span> y <span style="color: #000080;">=</span> <span style="color: #c6c;">2.0</span> <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#40;</span>Seq<span style="color: #000080;">.</span><span style="color: #505090;">take</span> <span style="color: #c6c;">1</span> rands<span style="color: #000080;">&#41;</span> <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">hd</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">-</span> <span style="color: #c6c;">1.0</span>
            <span style="color: #06c; font-weight: bold;">match</span> <span style="color: #000080;">&#40;</span>x <span style="color: #000080;">*</span> x <span style="color: #000080;">+</span> y <span style="color: #000080;">*</span> y<span style="color: #000080;">&#41;</span> <span style="color: #06c; font-weight: bold;">with</span>
                <span style="color: #000080;">|</span> dist <span style="color: #06c; font-weight: bold;">when</span> dist <span style="color: #000080;">&lt;</span> <span style="color: #c6c;">1.0</span> <span style="color: #000080;">-&gt;</span> Some <span style="color: #000080;">&#40;</span>x,dist<span style="color: #000080;">&#41;</span>
                <span style="color: #000080;">|</span> dist <span style="color: #000080;">-&gt;</span> None
            <span style="color: #000080;">&#41;</span> 
    x <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Sqrt</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">-</span><span style="color: #c6c;">2.0</span> <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Log</span><span style="color: #000080;">&#40;</span>dist<span style="color: #000080;">&#41;</span> <span style="color: #000080;">/</span> dist<span style="color: #000080;">&#41;</span></pre></div></div>

<p>It&#8217;s not particularly efficient as we&#8217;re consuming two uniform numbers to generate one normal one &#8211; hence the additional Seq.take within the pick. Of course we could change the function to return the 2 generated numbers as an extra element in the tuple.</p>
<p>Next, let&#8217;s generate some numbers, and get them in a suitable form to display:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> makeData <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span>
    Seq<span style="color: #000080;">.</span><span style="color: #505090;">init</span> <span style="color: #c6c;">100000</span> boxMuller
    <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">countBy</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> d <span style="color: #000080;">-&gt;</span> 
        <span style="color: #06c; font-weight: bold;">let</span> d <span style="color: #000080;">=</span> decimal d
        Math<span style="color: #000080;">.</span><span style="color: #505090;">Round</span><span style="color: #000080;">&#40;</span>d, <span style="color: #c6c;">1</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">sortBy</span> fst</pre></div></div>

<p>We initialise a sequence with an arbitrary amount of numbers (100000, enough to get a good distribution, hopefully), then use <code>Seq.countBy</code> to do a naive grouping that allows us to see how the numbers are distributed, i.e. counting how many numbers fit in each 0.10 bucket. We then sort the output by bucket. </p>
<h3>Visualisation</h3>
<p>Now we can display what we&#8217;ve got. We can create a simple WPF object-model using imperative code, including the very useful chart control from the WpfToolkit. The chart control enables us to add a series and set our <code>seq&lt;decimal * float&gt;</code> directly as the series ItemsSource, which is the standard way to specify the items for a collection control. If you specify the tuple <code>Item1</code> and <code>Item2</code> properties for the bindings, WPF will be able to access the data from each element, and that&#8217;s all you need.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> series <span style="color: #000080;">=</span> 
        ColumnSeries<span style="color: #000080;">&#40;</span>
            IndependentValueBinding <span style="color: #000080;">=</span> Data<span style="color: #000080;">.</span><span style="color: #505090;">Binding</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Item1&quot;</span><span style="color: #000080;">&#41;</span>,
            DependentValueBinding <span style="color: #000080;">=</span> Data<span style="color: #000080;">.</span><span style="color: #505090;">Binding</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Item2&quot;</span><span style="color: #000080;">&#41;</span>,
            ItemsSource <span style="color: #000080;">=</span> makeData <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> chart <span style="color: #000080;">=</span> Chart<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    chart<span style="color: #000080;">.</span><span style="color: #505090;">Series</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> series
    Window<span style="color: #000080;">&#40;</span>
        Name<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Plot&quot;</span>,
        Title<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Normally distributed random numbers&quot;</span>,
        Width<span style="color: #000080;">=</span><span style="color: #c6c;">900.0</span>,
        Height<span style="color: #000080;">=</span><span style="color: #c6c;">700.0</span>,
        Content<span style="color: #000080;">=</span>chart,
        Visibility<span style="color: #000080;">=</span>Visibility<span style="color: #000080;">.</span><span style="color: #505090;">Visible</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>Here&#8217;s the resulting output:<br />
<img src="http://www.voyce.com/wp-content/uploads/2009/11/dist-300x233.png" alt="dist" title="dist" width="300" height="233" class="alignleft size-medium wp-image-576" />As I&#8217;ve mentioned before, this is a fantastically immediate way of doing numerical development in Visual Studio. You can enter all of this code directly into F# interactive within VS, iterate, and quickly see the effect that your changes have. It&#8217;s just as interactive as using the graph features in Excel, and the resulting code is much more easily reusable.</p>
<p><span style="visibility:hidden"> XD5RRV3XDNHN </span><br />
<script type="text/javascript" src="http://www.assoc-amazon.com/s/link-enhancer?tag=wwwvoycecom-20&#038;o=1">
</script><br />
<noscript><br />
    <img src="http://www.assoc-amazon.com/s/noscript?tag=wwwvoycecom-20" alt="" /><br />
</noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/11/24/generating-and-plotting-random-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ending the love affair with Excel</title>
		<link>http://www.voyce.com/index.php/2009/07/08/ending-the-love-affair-with-excel/</link>
		<comments>http://www.voyce.com/index.php/2009/07/08/ending-the-love-affair-with-excel/#comments</comments>
		<pubDate>Wed, 08 Jul 2009 22:30:17 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Excel]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=171</guid>
		<description><![CDATA[It's a well known fact that the financial services industry (where I mean banks, hedge funds, pension providers, fund managers etc) is deeply in love with Excel. But what is it about the Excel ecosystem that makes it so appealing, and how can we move seamlessly to a more robust, maintainable platform?]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_214" class="wp-caption alignleft" style="width: 160px"><a href="http://72.47.193.211/wp-content/uploads/2009/07/spreadsheets_mug.png"><img src="http://www.voyce.com/wp-content/uploads/2009/07/spreadsheets_mug-150x150.png" alt="I heart spreadsheets" title="I heart spreadsheets" width="150" height="150" class="size-thumbnail wp-image-214" /></a><p class="wp-caption-text">I heart spreadsheets</p></div>It&#8217;s a well known fact that the financial services industry (where I mean banks, hedge funds, pension providers, fund managers etc) is deeply in love with Excel. But what is it about the Excel ecosystem that makes it so appealing?</p>
<p>Unfortunately, given the ever-increasing focus on accountability and scalability in these domains, Excel is also an increasingly inappropriate platform for delivery of this sort of functionality. How can organisations ease the transition away from this environment to something more easily manageable, while retaining it&#8217;s positive benefits?</p>
<p><span id="more-171"></span></p>
<blockquote><p>Disclaimer: These are my own views and not those of my employer. The scenarios I describe are fictitious and not based on actual practices at my place of employment. Any similarity to actual events and behaviours is coincidental.
</p></blockquote>
<p>I see two main aspects of Excel&#8217;s operation that prove valuable in general, and in finance in particular: visibility and immediacy.</p>
<h3>Visibility</h3>
<p>From an end user&#8217;s point of view, one of the most positive aspects of Excel is it&#8217;s transparency. Even in an environment where complex processing goes on inside a plugin &#8211; say, an Excel user defined function (UDF) packaged as an XLL &#8211; it&#8217;s still only in the scope of a single function call in a single cell. You continue to get good visibility of the inputs and outputs from the function.</p>
<p>You can also get a good higher-level view of how the different parts of the calculation fit together. Either by inspection, editing the formula to quickly see which cells it references, or by using the formula auditing toolbar to get an overlay of dependent and precedent functions, you can see roughly how various parts of the calculation fit together.</p>
<p>This, combined with the logical separation of functionality into separate worksheets, gives you the impression of understandability.</p>
<p>The problem is that it&#8217;s just that &#8211; an impression &#8211; there is no structure enforced by the worksheet separation, you&#8217;re free to link between them as you see fit, and this can result in an extremely complex and virtually indecipherable &#8220;flow&#8221; of calculation within a workbook.</p>
<h3>Immediacy</h3>
<p>Luckily, to offset the complexity we have another important aspect of Excel&#8217;s usability: it&#8217;s immediacy.</p>
<p>Trading users can very quickly modify calculation trees to perform ad-hoc additional calculations such as applying spreads, and to gauge the effect of market moves on their portfolio, i.e. &#8220;what-if&#8221; scenarios.</p>
<p>Structuring users can fairly easily &#8211; given an existing set of functional pieces &#8211; assemble a model to price a complex new trade type. Although this is a much less common use case now that the demand for getting new structured products to market quickly has essentially vanished.</p>
<p>As well as this type of gross modification, it&#8217;s also possible to just repeatedly re-evaluate some small part of the calculation to quickly determine how it is affected by other changes.</p>
<p>The immediacy of the Excel environment, combined with the use of the Visual Basic for Applications (VBA) scripting language, enables both business and IT users to rapidly build out new sheets to perform ad-hoc tasks. Rapid application development, or RAD as it&#8217;s known, is all well and good for performing some transient, ad-hoc calculation for limited use, but unfortunately these tools have the habit of becoming indispensable parts of an organisation&#8217;s workflow. That&#8217;s when you start to see serious problems with scalability and maintainability.</p>
<h3>The problem?</h3>
<p>So the fundamental tension here is that exactly the same features which make Excel useful to traders, structurers, etc., also make it highly unsuitable for use in these environments. You really don&#8217;t want traders to be able to subtley alter the flow of the calculation, as much as they might like to. Excel should really be a read-only view on some underlying trade data source and calculation engine, but this isn&#8217;t always how it&#8217;s implemented.</p>
<p>You also want to provide some flexibility &#8211; the ability to experiment, explore and examine &#8211; but within certain constraints and without compromising future requirements. Being able to price a trade is a good start, but you will subsequently need to book it easily, re-value it reliably and potentially risk manage a large portfolio of them.</p>
<h3>Moving away from Excel</h3>
<p>Many houses provide underlying quant analytics implemented in C++, with a native C++ interface and a variety of other (sometimes auto-generated) wrappers that make it accessible in other environments. Ideally, the amount of actual functionality in these wrapper layers should be kept to an absolute minimum. It should be commodity code that can be regenerated as and when required.</p>
<p>However, even if this is the case, unless you have the ability in the underlying code to fan-out the processing you will still be constrained by the operating system process limits, e.g. 4gb address space.</p>
<p>The common alternative to hosting pricing and risk management within Excel is to write new dedicated applications to perform the calculations and (hopefully) provide a means to inspect and troubleshoot it.</p>
<p>Unfortunately these systems are built by teams who aren&#8217;t particularly familiar with the way the front office uses Excel. It&#8217;s often the case that spreadsheet development teams and systems development teams don&#8217;t interact; the former tend to be based on the trading desk while the latter are in another part of the building.</p>
<p>So the end result can end up being systems that work in a way developers feel comfortable with, rather than the way business users would like them to work. This can make the system seem like a black box to it&#8217;s users. And to make it worse these are the users who are accustomed to Excel&#8217;s high levels of transparency.</p>
<p>Although the system may be enforcing the fact that trade value is strictly a function of the trade, market and static data, having some transparency can still be valuable in giving skilled users confidence in the underlying calculation. They can apply their not-inconsiderable intuitive abilities to quickly gauge the correctness or otherwise of the valuation. It can help the quants move away from their native Excel/Matlab-style iterative development environment. And when groups need to work together to reconcile differences, everyone can benefit.</p>
<p>The problem? This amount of transparency has to be built into the system or the quant library pretty much from the ground up.</p>
<h3>Solutions</h3>
<p>One possible approach is to make your system a general purpose calculation engine. This has some appeal, but you have to be careful about sacrificing performance for generality. You might be tempted to try exactly matching the semantics of Excel&#8217;s calculation and type system. This can be a nightmare, with all sorts of limitations and nasty edge cases. For example, the fact that errors are a simple numeric value with no facility to carry extra information is crippling, and also the lack of support for objects as first class values in the type system.</p>
<p>However you choose to implement your calculation engine, ensure that it&#8217;s loosely coupled enough to be run out-of-process or across machine boundaries without code changes.</p>
<p>Here are some bullet-point takeaways for easing the transition:</p>
<ol>
<li><strong>Provide a means for users to examine intermediate calculations, and surface it in the UI.</strong><br />
This will give your intermediate and end users confidence in the calculations
</li>
<li><strong>Provide a means to capture and re-play valuations, including all their inputs and outputs.</strong><br />
	This will assist in reconciling valuations, and in passing snapshots around between groups.
</li>
<li><strong>Provide the ability to drive the system programatically.</strong><br />
	Along with persistent valuations, this will help in regression testing
</li>
</ol>
<p>I hope this post has served to give you some insights into the potential challenges of moving users away from Excel into more robust systems, why some of those users may be reluctant to move, and how you can help to ease the transition. And of course, let me know via the comments if you&#8217;ve got any observations on the subject.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/07/08/ending-the-love-affair-with-excel/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
