<?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>Ad hoc Geek &#187; actionscript</title>
	<atom:link href="http://www.adhocgeek.com/tag/actionscript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.adhocgeek.com</link>
	<description>Approaching geekery in an ad hoc and improvisational manner.</description>
	<lastBuildDate>Fri, 30 Sep 2011 09:43:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Binomial Option Pricing with Alchemy</title>
		<link>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-alchemy/</link>
		<comments>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-alchemy/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 14:30:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[alchemy]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[financial engineering]]></category>
		<category><![CDATA[mathematics]]></category>
		<category><![CDATA[option pricing]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=146</guid>
		<description><![CDATA[Yet another version of the binomial option pricing algorithm (sorry), but this time I&#8217;m using Alchemy! I have to admit to not entirely understanding how Alchemy works, but I understand enough C to write a simple pricer in it. Here&#8217;s the relevant C-code (which is, in part, copied from Mike Chambers&#8217; stringecho.c sample) : #include [...]]]></description>
			<content:encoded><![CDATA[<p>Yet another version of the binomial option pricing algorithm (sorry), but this time I&#8217;m using <a href="http://labs.adobe.com/wiki/index.php/Alchemy">Alchemy</a>!</p>
<p>I have to admit to not entirely understanding how Alchemy works, but I understand enough C to write a simple pricer in it. Here&#8217;s the relevant C-code (which is, in part, copied from <a href="http://www.mikechambers.com/blog/">Mike Chambers&#8217;</a> stringecho.c sample) :</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;math.h&gt;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Header file for AS3 interop APIs</span>
<span style="color: #339933;">#include &quot;AS3.h&quot;</span>
&nbsp;
<span style="color: #993333;">static</span> AS3_Val getPrice<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #339933;">*</span> self<span style="color: #339933;">,</span> AS3_Val args<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">double</span> N<span style="color: #339933;">,</span> T<span style="color: #339933;">,</span> S<span style="color: #339933;">,</span> K<span style="color: #339933;">,</span> v<span style="color: #339933;">,</span> r<span style="color: #339933;">,</span> price<span style="color: #339933;">;</span>
    AS3_ArrayValue<span style="color: #009900;">&#40;</span> args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;DoubleType, DoubleType, DoubleType, DoubleType, DoubleType, DoubleType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>N<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>T<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>S<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>K<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>v<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>r<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #993333;">double</span> dt <span style="color: #339933;">=</span> T<span style="color: #339933;">/</span>N<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//one time step</span>
&nbsp;
    <span style="color: #993333;">double</span> u <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span> <span style="color: #339933;">+</span> v<span style="color: #339933;">*</span>sqrt<span style="color: #009900;">&#40;</span>dt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//up-tick</span>
    <span style="color: #993333;">double</span> d <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span> <span style="color: #339933;">-</span> v<span style="color: #339933;">*</span>sqrt<span style="color: #009900;">&#40;</span>dt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//down-tick</span>
    <span style="color: #993333;">double</span> p <span style="color: #339933;">=</span> <span style="color:#800080;">0.5</span> <span style="color: #339933;">+</span> r<span style="color: #339933;">*</span>sqrt<span style="color: #009900;">&#40;</span>dt<span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//risk-neutral probability of up-tick</span>
    <span style="color: #993333;">double</span> df <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">/</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">+</span>r<span style="color: #339933;">*</span>dt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//discount factor over 1 time step, dt</span>
&nbsp;
    <span style="color: #993333;">double</span><span style="color: #339933;">*</span> optionValues <span style="color: #339933;">=</span> malloc<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>N<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">double</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">//populate the tree (for N-steps there will be N+1 values)</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span> j<span style="color: #339933;">;</span>
    <span style="color: #993333;">double</span> ST<span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> N<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> 
    <span style="color: #009900;">&#123;</span>
        ST <span style="color: #339933;">=</span> S <span style="color: #339933;">*</span> pow<span style="color: #009900;">&#40;</span>u<span style="color: #339933;">,</span> i<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> pow<span style="color: #009900;">&#40;</span>d<span style="color: #339933;">,</span> N<span style="color: #339933;">-</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        optionValues<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>ST <span style="color: #339933;">&gt;</span> K<span style="color: #009900;">&#41;</span><span style="color: #339933;">?</span> ST <span style="color: #339933;">-</span> K <span style="color: #339933;">:</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">//now work backwards to get expected </span>
    <span style="color: #666666; font-style: italic;">//option value at each previous stage</span>
    <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span>N<span style="color: #339933;">;</span> i <span style="color: #339933;">&gt;=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>j<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j<span style="color: #339933;">&lt;</span>i<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            optionValues<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>p<span style="color: #339933;">*</span>optionValues<span style="color: #009900;">&#91;</span>j<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">-</span>p<span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>optionValues<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>df<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    price <span style="color: #339933;">=</span> optionValues<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    free<span style="color: #009900;">&#40;</span>optionValues<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> AS3_Number<span style="color: #009900;">&#40;</span>price<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//define the methods exposed to ActionScript</span>
    <span style="color: #666666; font-style: italic;">//typed as an ActionScript Function instance</span>
    AS3_Val getPriceMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span> NULL<span style="color: #339933;">,</span> getPrice <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// construct an object that holds references to the functions</span>
    AS3_Val result <span style="color: #339933;">=</span> AS3_Object<span style="color: #009900;">&#40;</span> <span style="color: #ff0000;">&quot;getPrice: AS3ValType&quot;</span><span style="color: #339933;">,</span> getPriceMethod <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Release</span>
    AS3_Release<span style="color: #009900;">&#40;</span> getPriceMethod <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// notify that we initialized -- THIS DOES NOT RETURN!</span>
    AS3_LibInit<span style="color: #009900;">&#40;</span> result <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// should never get here!</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>It&#8217;s been a long time since I used C in anger though, so it&#8217;s entirely possible I&#8217;m using malloc and free badly here! If so, please let me know.</p>
<p>Using the compile SWC in a flex project is incredibly simple, here&#8217;s the relevant exerpt :</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">import</span> cmodule.<span style="color: #006600;">binomial_pricer</span>.<span style="color: #006600;">CLibInit</span>;
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> calc_Click<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #0066CC;">start</span>:<span style="color: #0066CC;">Number</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #0066CC;">time</span>;
    <span style="color: #000000; font-weight: bold;">var</span> result:<span style="color: #0066CC;">Number</span>;
    <span style="color: #000000; font-weight: bold;">var</span> loader:CLibInit = <span style="color: #000000; font-weight: bold;">new</span> CLibInit<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">var</span> lib:<span style="color: #0066CC;">Object</span> = loader.<span style="color: #006600;">init</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span>=<span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> repetitions.<span style="color: #006600;">value</span>; i++<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
        result = lib.<span style="color: #006600;">getPrice</span><span style="color: #66cc66;">&#40;</span>    steps.<span style="color: #006600;">value</span>, 
                            timeToExpiry.<span style="color: #006600;">value</span>, 
                            spot.<span style="color: #006600;">value</span>,
                            strike.<span style="color: #006600;">value</span>,
                            volatility.<span style="color: #006600;">value</span>,
                            <span style="color: #0066CC;">rate</span>.<span style="color: #006600;">value</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>                                
    price.<span style="color: #0066CC;">text</span> = result.<span style="color: #0066CC;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;            
    <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #0066CC;">end</span>:<span style="color: #0066CC;">Number</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #0066CC;">time</span>;
    averageTime.<span style="color: #0066CC;">text</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>end-<span style="color: #0066CC;">start</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">/</span>repetitions.<span style="color: #006600;">value</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #0066CC;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;ms&quot;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>And the finished result, which is about 8x (!) faster than the pixel bender version (on my machine at least) :</p>
<p><object width="400" height="360" data="/flash/AlchemyBinomialPricer/AlchemyBinomialPricer.swf" type="application/x-shockwave-flash"><param name="name" value="AlchemyBinomialPricer" /><param name="bgcolor" value="#ffffff" /><param name="align" value="middle" /><param name="src" value="/flash/AlchemyBinomialPricer/AlchemyBinomialPricer.swf" /><param name="quality" value="high" /></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-alchemy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binomial Option Pricing with Pixel Bender</title>
		<link>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-pixel-bender/</link>
		<comments>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-pixel-bender/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 11:13:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[financial engineering]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[mathematics]]></category>
		<category><![CDATA[option pricing]]></category>
		<category><![CDATA[pixel bender]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=134</guid>
		<description><![CDATA[Pixel Bender has been around for a little while now and it&#8217;s a very cool idea, promising incredible speed improvements by allowing developers to make the most of multi-core processors and GPUs. It seems as though it was designed primarily for Adobe image manipulation software, but, since images are just arrays of bytes it can [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://labs.adobe.com/technologies/pixelbender/">Pixel Bender</a> has been around for a little while now and it&#8217;s a very cool idea, promising incredible speed improvements by allowing developers to make the most of multi-core processors and GPUs. It seems as though it was designed primarily for Adobe image manipulation software, but, since images are just arrays of bytes it can also be used to speed up any parallelisable code you might have within Flash.</p>
<h3>A fast intro to Pixel Bender</h3>
<p>The main unit of operation in pixel bender is the kernel. Generally, each kernel will take a source image and calculate the value of a single pixel in the output image. i.e. for every pixel in your source image, a single kernel instance will be run which can use that whole image to calculate the value of a single pixel (although you won&#8217;t usually want it to look at the whole image &#8211; the less dependent it is on other pixels, the faster it can run).</p>
<p>The kernel language is intended to be fast and as such is fairly simplistic. A simple kernel which converts every pixel in the source image to black would be written as follows :</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>languageVersion <span style="color: #339933;">:</span> <span style="color:#800080;">1.0</span><span style="color: #339933;">;&gt;</span>
&nbsp;
kernel Gothify
<span style="color: #339933;">&lt;</span>   namespace <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;com.example&quot;</span><span style="color: #339933;">;</span>
    vendor <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;Example.com&quot;</span><span style="color: #339933;">;</span>
    version <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    description <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;Fills every pixel in the source image with black&quot;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span>        
    input image4 source<span style="color: #339933;">;</span>
    output pixel4 result<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #993333;">void</span> evaluatePixel<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        result <span style="color: #339933;">=</span> pixel4<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color:#800080;">1.0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The developer&#8217;s guide says to use pixel4(0,0,0,0), but since the last value is the alpha channel, that just ends up with a <em>transparent</em> black image. It also doesn&#8217;t include the input image4, and while this may do something in photoshop, it&#8217;s not going to give you any output in the pixel bender IDE.</p>
<p>Now, an image is basically just an array of pixels, and, within pixel bender, a 4-channel pixel (a pixel4 type) is just a vector of floats. We can use <em>any</em> values within a pixel4, limited only by the bounds of a standard float size. So, we could change the evaluatePixel function above to the following and it wouldn&#8217;t make any difference to the output image :</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> evaluatePixel<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    result <span style="color: #339933;">=</span> pixel4<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color:#800080;">1500.67</span><span style="color: #339933;">,-</span><span style="color:#800080;">45.0</span><span style="color: #339933;">,-</span><span style="color:#800080;">32.333</span><span style="color: #339933;">,</span><span style="color:#800080;">515.47</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>It&#8217;s only the values between 0.0 and 1.0 that can change the output colour, anything above 1.0 is at maximum and anything below 0.0 is at minimum. This means we can use pixel bender to operate on any array of floating point values as long as we&#8217;re happy for it to operate on pixel sized chunks of data in isolation (the pixel bender graph language does allow chaining of kernels, but this isn&#8217;t available to us in the flash player, so I&#8217;m going to ignore it for now).</p>
<h3>Parallelising the Binomial Option Pricing Algorithm</h3>
<p>There&#8217;s a short, fairly readable paper <a href="http://saahpc.ncsa.illinois.edu/papers/Ganesan_paper.pdf">here</a> [Ganesan, Chamberlain, Buhler] which gives some ideas for how to parallelise the algorithm. I&#8217;m only going to implement the scheme which is probably best illustrated by their fig. 2. This requires me to pass to each kernel the input image (array of option values at time T), the risk-neutral probability of an up-tick and the discount factor over one time step.<br />
I&#8217;ll then have to call the resulting kernel (or array of kernels, depending on how you think of it), N-1 times to get the final option price.</p>
<p>The kernel I wrote ended up like this :</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>languageVersion <span style="color: #339933;">:</span> <span style="color:#800080;">1.0</span><span style="color: #339933;">;&gt;</span>
&nbsp;
kernel BinomialOptionPricer
<span style="color: #339933;">&lt;</span>   namespace <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;com.adhocgeek&quot;</span><span style="color: #339933;">;</span>
    vendor <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;Ad hoc Geek&quot;</span><span style="color: #339933;">;</span>
    version <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    description <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;Calculates the one step binomial option price&quot;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span>
    input image3 src<span style="color: #339933;">;</span>
    output pixel3 dst<span style="color: #339933;">;</span>
&nbsp;
    parameter <span style="color: #993333;">float</span> p<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//risk-neutral probability of an up-tick</span>
    parameter <span style="color: #993333;">float</span> df<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//discount factor over one time step</span>
&nbsp;
    <span style="color: #993333;">void</span> evaluatePixel<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        pixel3 down <span style="color: #339933;">=</span> sampleNearest<span style="color: #009900;">&#40;</span>src<span style="color: #339933;">,</span> outCoord<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pixel3 up <span style="color: #339933;">=</span> sampleNearest<span style="color: #009900;">&#40;</span>src<span style="color: #339933;">,</span> outCoord<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> float2<span style="color: #009900;">&#40;</span><span style="color:#800080;">1.0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #993333;">float</span> V <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>p<span style="color: #339933;">*</span>up.<span style="color: #202020;">x</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span><span style="color:#800080;">1.0</span><span style="color: #339933;">-</span>p<span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>down.<span style="color: #202020;">x</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>df<span style="color: #339933;">;</span>
&nbsp;
        dst <span style="color: #339933;">=</span> pixel3<span style="color: #009900;">&#40;</span>V<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Using the Pixel Bender Filter in Actionscript</h3>
<p>This is actually incredibly easy. Flash 10 gives us a new class called the <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/Shader.html">Shader</a> which represents a Pixel Bender kernel. You can use this with the new ShaderJob class to trigger a set of kernel operations on any vector or byte array that you&#8217;ve created. I&#8217;m not going to try and write a tutorial, so here&#8217;s the final actionscript code I wrote (you should notice it&#8217;s quite similar to the previous version):</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #66cc66;">&#91;</span>Embed<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;BinomialOptionPricer.pbj&quot;</span>, mimeType=<span style="color: #ff0000;">&quot;application/octet-stream&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> BinomialOptionPricer:<span style="color: #000000; font-weight: bold;">Class</span>;
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> getPrice<span style="color: #66cc66;">&#40;</span>  N:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Number of steps</span>
                                    T:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Time to expiry (in years)</span>
                                    S:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Spot price of underlying</span>
                                    K:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Option strike</span>
                                    v:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Volatility of underlying</span>
                                    r:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//risk-free rate</span>
                                    NUMOPTIONS:<span style="color: #0066CC;">Number</span> 
                                 <span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">var</span> dt:<span style="color: #0066CC;">Number</span> = T<span style="color: #66cc66;">/</span>N; <span style="color: #808080; font-style: italic;">//one time step</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> u:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span> + v<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//up-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> d:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span> - v<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//down-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> p:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0.5</span> + r<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">*</span>v<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//risk-neutral prob. of up-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> df:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>+r<span style="color: #66cc66;">*</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//discount factor over 1 time step, dt</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> optionValues:Vector.<span style="color: #66cc66;">&lt;</span>Number<span style="color: #66cc66;">&gt;</span> = <span style="color: #000000; font-weight: bold;">new</span> Vector.<span style="color: #66cc66;">&lt;</span>Number<span style="color: #66cc66;">&gt;</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">//Populate the fake pixels array </span>
    <span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span>, j:<span style="color: #0066CC;">int</span>, ST:<span style="color: #0066CC;">Number</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>j=<span style="color: #cc66cc;">0</span>; j <span style="color: #66cc66;">&lt;</span> NUMOPTIONS; j++<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>i=<span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> N+<span style="color: #cc66cc;">1</span>; i++<span style="color: #66cc66;">&#41;</span> 
        <span style="color: #66cc66;">&#123;</span>
            ST = spot.<span style="color: #006600;">value</span> <span style="color: #66cc66;">*</span> <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">pow</span><span style="color: #66cc66;">&#40;</span>u, i<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">pow</span><span style="color: #66cc66;">&#40;</span>d, N-i<span style="color: #66cc66;">&#41;</span>;
            optionValues.<span style="color: #0066CC;">push</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>ST <span style="color: #66cc66;">&gt;</span> K<span style="color: #66cc66;">&#41;</span>? ST - K : <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
            optionValues.<span style="color: #0066CC;">push</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
            optionValues.<span style="color: #0066CC;">push</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #808080; font-style: italic;">//work backwards to get expected option value at each previous stage</span>
    <span style="color: #000000; font-weight: bold;">var</span> sj:ShaderJob;
    <span style="color: #000000; font-weight: bold;">var</span> shader:Shader = <span style="color: #000000; font-weight: bold;">new</span> Shader<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> BinomialOptionPricer<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> as ByteArray<span style="color: #66cc66;">&#41;</span>;
    shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">src</span>.<span style="color: #006600;">input</span> = optionValues;
    shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">src</span>.<span style="color: #0066CC;">height</span> = NUMOPTIONS;
    shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">p</span>.<span style="color: #006600;">value</span> = <span style="color: #66cc66;">&#91;</span>p<span style="color: #66cc66;">&#93;</span>;
    shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">df</span>.<span style="color: #006600;">value</span> = <span style="color: #66cc66;">&#91;</span>df<span style="color: #66cc66;">&#93;</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>i=N; i <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">0</span>; i--<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
        shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">src</span>.<span style="color: #0066CC;">width</span> = i+<span style="color: #cc66cc;">1</span>;
        sj = <span style="color: #000000; font-weight: bold;">new</span> ShaderJob<span style="color: #66cc66;">&#40;</span>shader, optionValues, i+<span style="color: #cc66cc;">1</span>, NUMOPTIONS<span style="color: #66cc66;">&#41;</span>;
        sj.<span style="color: #0066CC;">start</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> optionValues<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>; 
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Points to note are where I&#8217;ve embedded the kernel in the actionscript itself and where I&#8217;ve added the ability to run the calculation multiple times in parallel (simulating running the calculation for many different options at once). Each line in the source &#8220;image&#8221; represents a different option (although they&#8217;re all using the same source data at the moment).</p>
<p>Here (if you have Flash Player 10 installed) is the resulting swf (view source enabled, of course) :</p>
<p><object width="400" height="360" data="/flash/PixelBenderPricer/PBBinomialPricer.swf" type="application/x-shockwave-flash"><param name="name" value="PBBinomialPricer" /><param name="bgcolor" value="#ffffff" /><param name="align" value="middle" /><param name="src" value="/flash/PixelBenderPricer/PBBinomialPricer.swf" /><param name="quality" value="high" /></object></p>
<p>It&#8217;s slightly faster than the straight actionscript version, but not by a great deal, where it really shines is in calculating multiple options at once. There&#8217;s an interesting non-linear relationship between the number of lines in the source &#8220;image&#8221; and the speed of this particular algorithm. I might graph it at some point&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-pixel-bender/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binomial Option Pricing in Actionscript</title>
		<link>http://www.adhocgeek.com/2009/09/binomial-option-pricing-in-actionscript/</link>
		<comments>http://www.adhocgeek.com/2009/09/binomial-option-pricing-in-actionscript/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 12:20:33 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[financial engineering]]></category>
		<category><![CDATA[mathematics]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=125</guid>
		<description><![CDATA[The binomial option pricing model is one of the simplest pricing models to understand and code. I&#8217;m not going to go into an explanation of the model itself, as that would take more time than I&#8217;m willing to expend, however I think it&#8217;s always useful to have example code lying around and I&#8217;m quite happy [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://en.wikipedia.org/wiki/Binomial_options_pricing_model">binomial option pricing model</a> is one of the simplest pricing models to understand and code. I&#8217;m not going to go into an explanation of the model itself, as that would take more time than I&#8217;m willing to expend, however I think it&#8217;s always useful to have example code lying around and I&#8217;m quite happy for some of it to lie around on my website.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> getPrice<span style="color: #66cc66;">&#40;</span>  N:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Number of steps</span>
                            T:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Time to expiry (in years)</span>
                            S:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Spot price of underlying</span>
                            K:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Option strike</span>
                            v:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Volatility of underlying</span>
                            r:<span style="color: #0066CC;">Number</span> <span style="color: #808080; font-style: italic;">//risk-free rate </span>
                         <span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> dt:<span style="color: #0066CC;">Number</span> = T<span style="color: #66cc66;">/</span>N; <span style="color: #808080; font-style: italic;">//one time step</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> u:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span> + v<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//up-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> d:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span> - v<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//down-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> p:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0.5</span> + r<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">*</span>v<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//risk-neutral prob. of up-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> df:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>+r<span style="color: #66cc66;">*</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//discount factor over 1 time step, dt</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> optionValues:<span style="color: #0066CC;">Array</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Array</span><span style="color: #66cc66;">&#40;</span>N+<span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">//populate the tree (for N-steps there will be N+1 values)</span>
    <span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span>, j:<span style="color: #0066CC;">int</span>, ST:<span style="color: #0066CC;">Number</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>i=<span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> N+<span style="color: #cc66cc;">1</span>; i++<span style="color: #66cc66;">&#41;</span> 
    <span style="color: #66cc66;">&#123;</span>
        ST = spot.<span style="color: #006600;">value</span> <span style="color: #66cc66;">*</span> <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">pow</span><span style="color: #66cc66;">&#40;</span>u, i<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">pow</span><span style="color: #66cc66;">&#40;</span>d, N-i<span style="color: #66cc66;">&#41;</span>;
        optionValues<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span>ST <span style="color: #66cc66;">&gt;</span> K<span style="color: #66cc66;">&#41;</span>? ST - K : <span style="color: #cc66cc;">0</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">//now work backwards to get expected option value at each previous stage</span>
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>i=N; i <span style="color: #66cc66;">&gt;</span>= <span style="color: #cc66cc;">0</span>; i--<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">for</span><span style="color: #66cc66;">&#40;</span>j=<span style="color: #cc66cc;">0</span>; j<span style="color: #66cc66;">&lt;</span>i; j++<span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#123;</span>
            optionValues<span style="color: #66cc66;">&#91;</span>j<span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">*</span>optionValues<span style="color: #66cc66;">&#91;</span>j+<span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span> + <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>-p<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">*</span>optionValues<span style="color: #66cc66;">&#91;</span>j<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">*</span>df;
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> optionValues<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>; 
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>What I&#8217;ve written is slightly different from some of the examples you might see (though exactly what Wikipedia suggests) &#8211; I don&#8217;t bother building up an array of stock prices since each value in the final array can be calculated with a simple formula. This means that I&#8217;ve removed a couple of loops from the calculation and (roughly) halved the execution time. I&#8217;m also assuming that we&#8217;re pricing a vanilla call option and that the risk-free rate is discretely compounded, though it would be fairly trivial to replace the call payoff function ((ST > K)? ST &#8211; K : 0) with any kind of external payoff function and to replace the discrete discount factor with a continuous one (1+rt becomes e<sup>rT</sup>, essentially). In the end, with enough time steps, these kinds of changes make only a little difference though.</p>
<p>Have a play :</p>
<p><object width="400" height="360" data="/flash/BinomialOptionPricer/OptionPricer.swf" type="application/x-shockwave-flash"><param name="name" value="OptionPricer" /><param name="bgcolor" value="#ffffff" /><param name="align" value="middle" /><param name="src" value="/flash/BinomialOptionPricer/OptionPricer.swf" /><param name="quality" value="high" /></object></p>
<p>And for comparison, here&#8217;s a Black-Scholes pricer :</p>
<p><object width="400" height="360" data="/flash/BlackScholesPricer/BlackScholesPricer.swf" type="application/x-shockwave-flash"><param name="name" value="BlackScholes" /><param name="bgcolor" value="#ffffff" /><param name="align" value="middle" /><param name="src" value="/flash/BlackScholesPricer/BlackScholes.swf" /><param name="quality" value="high" /></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/09/binomial-option-pricing-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>VAR, COVAR and COREL in Actionscript</title>
		<link>http://www.adhocgeek.com/2009/08/var-covar-and-corel-in-actionscript/</link>
		<comments>http://www.adhocgeek.com/2009/08/var-covar-and-corel-in-actionscript/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 11:07:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[covariance]]></category>
		<category><![CDATA[mathematics]]></category>
		<category><![CDATA[statistics]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=119</guid>
		<description><![CDATA[Someone was asking whether or not it&#8217;s possible to call Excel functions from a Flex project because they needed to use VAR, COVAR and COREL. The short answer is, of course, no (at least not to my knowledge, and, even if it were possible, I don&#8217;t think it&#8217;s something you really want to encourage). A [...]]]></description>
			<content:encoded><![CDATA[<p>Someone was asking whether or not it&#8217;s possible to call Excel functions from a Flex project because they needed to use VAR, COVAR and COREL. The short answer is, of course, no (at least not to my knowledge, and, even if it were possible, I don&#8217;t think it&#8217;s something you really want to encourage). A better answer would explain that these functions aren&#8217;t especially complex and that an Actionscript implementation is fairly straightforward. The wikipedia page on <a href="http://en.wikipedia.org/wiki/Covariance">covariance</a> is a little daunting if you&#8217;ve never really thought about what these functions entail (or have forgotten), but essentially it boils down to this :</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> corel<span style="color: #66cc66;">&#40;</span>X:<span style="color: #0066CC;">Array</span>, Y:<span style="color: #0066CC;">Array</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">//correlation coeff between two random variables X and Y is defined as :</span>
    <span style="color: #808080; font-style: italic;">//correlation(X,Y) = covar(X,Y)/(sqrt(Var(X)) * sqrt(Var(Y)))</span>
    <span style="color: #808080; font-style: italic;">//</span>
    <span style="color: #808080; font-style: italic;">//var(X) = covar(X,X);</span>
    <span style="color: #808080; font-style: italic;">//covar(X,Y) = E((X-xm)(Y-ym)); where xm, ym are the population means.</span>
    <span style="color: #b1b100;">return</span> covar<span style="color: #66cc66;">&#40;</span>X, Y<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">/</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>covar<span style="color: #66cc66;">&#40;</span>X, X<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> covar<span style="color: #66cc66;">&#40;</span>Y, Y<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> covar<span style="color: #66cc66;">&#40;</span>X:<span style="color: #0066CC;">Array</span>, Y:<span style="color: #0066CC;">Array</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">//Sample covariance is Sum((X-xm)(Y-ym))/n-1</span>
    <span style="color: #808080; font-style: italic;">//where n is the sample size and xm &amp; ym are sample means.</span>
    <span style="color: #808080; font-style: italic;">//I'll assume that X and Y are the same size...</span>
    <span style="color: #000000; font-weight: bold;">var</span> total:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0</span>;
    <span style="color: #000000; font-weight: bold;">var</span> xm:<span style="color: #0066CC;">Number</span> = average<span style="color: #66cc66;">&#40;</span>X<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">var</span> ym:<span style="color: #0066CC;">Number</span> = <span style="color: #66cc66;">&#40;</span>X == Y<span style="color: #66cc66;">&#41;</span>? xm : average<span style="color: #66cc66;">&#40;</span>Y<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span>=<span style="color: #cc66cc;">0</span>; i<span style="color: #66cc66;">&lt;</span>X.<span style="color: #0066CC;">length</span>; i++<span style="color: #66cc66;">&#41;</span>
        total += <span style="color: #66cc66;">&#40;</span>X<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>-xm<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #66cc66;">&#40;</span>Y<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>-ym<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">return</span> total<span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span>X.<span style="color: #0066CC;">length</span> - <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>; 
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> average<span style="color: #66cc66;">&#40;</span>X:<span style="color: #0066CC;">Array</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">//Sample mean or average = Sum(X)/(sample size)</span>
    <span style="color: #000000; font-weight: bold;">var</span> total:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #b1b100;">each</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> x:<span style="color: #0066CC;">Number</span> <span style="color: #b1b100;">in</span> X<span style="color: #66cc66;">&#41;</span>
        total += x;
    <span style="color: #b1b100;">return</span> total<span style="color: #66cc66;">/</span>X.<span style="color: #0066CC;">length</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Of course, it&#8217;s not quite that simple &#8211; my covar won&#8217;t return the same value as COVAR in Excel, because Excel uses the biased estimator (i.e. it divides by n rather than (n-1)), but this cancels out when calculating the correlation coefficient, and correcting covar to the biased estimator is trivial (multply by (n-1)/n). Personally, I think Excel is wrong for defaulting to the biased estimator for COVAR, especially since VAR uses the unbiased one (and, as I&#8217;ve written in the comments, VAR(X)=COVAR(X,X)).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/08/var-covar-and-corel-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Actionscript Date Lunacy</title>
		<link>http://www.adhocgeek.com/2009/08/actionscript-date-lunacy/</link>
		<comments>http://www.adhocgeek.com/2009/08/actionscript-date-lunacy/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 14:41:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dates]]></category>
		<category><![CDATA[formatting]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=100</guid>
		<description><![CDATA[I really hate the Actionscript Date class. Mostly because of the way it deals with local time offsets. When I create a new date instance, I generally don&#8217;t care about the local time zone settings. I&#8217;ll care about them when I have to combine it with other dates, sure, but at the time I set [...]]]></description>
			<content:encoded><![CDATA[<p>I <em>really</em> hate the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Date.html">Actionscript Date class</a>. Mostly because of the way it deals with local time offsets. When I create a new date instance, I generally don&#8217;t care about the local time zone settings. I&#8217;ll care about them when I have to combine it with other dates, sure, but at the time I set that value I want it to <em>stay</em> that value. The AS date class thinks otherwise.</p>
<p>Say I have a number of milliseconds from epoch (1 Jan 1970) which I want to use to create a specific date so I can use a DateFormatter to output the result, then you&#8217;d think that the following would be fine :</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> myDate:<span style="color: #0066CC;">Date</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1250766979000</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">var</span> df:DateFormatter = <span style="color: #000000; font-weight: bold;">new</span> DateFormatter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
df.<span style="color: #006600;">formatString</span> = <span style="color: #ff0000;">&quot;YYYY-MM-DD JJ:NN:SS&quot;</span>;
<span style="color: #000000; font-weight: bold;">var</span> stringDate:<span style="color: #0066CC;">String</span> = df.<span style="color: #006600;">format</span><span style="color: #66cc66;">&#40;</span>myDate<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p><small>(Let&#8217;s gloss over the batshit-insane need for a DateFormatter class and the actual formatString itself &#8211; JJ for 0-23 hour time, really?)</small></p>
<p>But no. In my area, we&#8217;re currently in daylight savings mode, so the Flash player decides that this date must be modified accordingly, and if you format it with the code above you&#8217;ll get &#8220;2009-08-20 12:16:19&#8243;, whereas it should be &#8220;2009-08-20 11:16:19&#8243; (you can try and calculate this yourself if you&#8217;re feeling particularly bored). This sounds fairly trivial to deal with until you realise that, short of writing your own DateFormatter, there&#8217;s no way to output the actual, formatted UTC date and time (ignoring the unformattable toUTCString() method).</p>
<p>To do that, you have to take this approach :</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> myDate:<span style="color: #0066CC;">Date</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1250766979000</span><span style="color: #66cc66;">&#41;</span>;
myDate.<span style="color: #0066CC;">setTime</span><span style="color: #66cc66;">&#40;</span>myDate.<span style="color: #0066CC;">getTime</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + myDate.<span style="color: #006600;">timezoneOffset</span> <span style="color: #66cc66;">*</span> <span style="color: #cc66cc;">60</span> <span style="color: #66cc66;">*</span> <span style="color: #cc66cc;">1000</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">var</span> df:DateFormatter = <span style="color: #000000; font-weight: bold;">new</span> DateFormatter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
df.<span style="color: #006600;">formatString</span> = <span style="color: #ff0000;">&quot;YYYY-MM-DD JJ:NN:SS&quot;</span>;
<span style="color: #000000; font-weight: bold;">var</span> stringDate:<span style="color: #0066CC;">String</span> = df.<span style="color: #006600;">format</span><span style="color: #66cc66;">&#40;</span>myDate<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Which, to me at least, seems mental, because we haven&#8217;t really created a UTC date there &#8211; we&#8217;ve actually had to modify the milliseconds since epoch due to the local timezone settings. If I change the time settings on my computer, the output of this will still change! It&#8217;s possible I&#8217;ve lived too long in Microsoft-land, but the equivalent code in C# seems a million times better and far more predictable :</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">DateTime dat <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DateTime<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">1970</span>, <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> TimeSpan<span style="color: #008000;">&#40;</span>12507669790000000L<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> stringDate <span style="color: #008000;">=</span> dat<span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;yyyy-MM-dd HH:mm:ss&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Yes, miraculously, dates can format themselves in C#! There&#8217;s no need for a superfluous DateFormatter class. The only reason this code might look a litte overinflated is that dates in C# have a wider range, so I&#8217;ve had to convert the milliseconds since Unix epoch to 10&#8242;s of nanoseconds since 0001-1-1 00:00:00.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/08/actionscript-date-lunacy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flex widget communication PoC</title>
		<link>http://www.adhocgeek.com/2009/05/widget-comms-poc/</link>
		<comments>http://www.adhocgeek.com/2009/05/widget-comms-poc/#comments</comments>
		<pubDate>Fri, 29 May 2009 15:11:26 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[messaging]]></category>
		<category><![CDATA[widgets]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=14</guid>
		<description><![CDATA[Problem : How do you get several distinct Flex widgets on a page to communicate? By distinct here I mean that each widget is a separate embedded SWF file, i.e. they don&#8217;t share the same Application. There are actually several ways to do this, and an appropriate choice really depends on the kind of data [...]]]></description>
			<content:encoded><![CDATA[<p>Problem : How do you get several distinct <a href="http://www.adobe.com/products/flex/">Flex</a> widgets on a page to communicate?</p>
<p>By distinct here I mean that each widget is a separate embedded SWF file, i.e. they don&#8217;t share the same Application.</p>
<p>There are actually several ways to do this, and an appropriate choice really depends on the kind of data you want to share and when. What I needed was real-time communication; say I have one widget that searches for a particular resource (in my case they&#8217;re bonds), when the user selects a resource, that widget should propagate the selection to all the others on the page. It was also a requirement that the number and identity of the widgets on the page be an unknown &#8211; i.e. I can&#8217;t assume that there will always be exactly three widgets called Fred, Bob and Jane.</p>
<p>Not being a Flex expert, my first thought was to use a <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/net/SharedObject.html">SharedObject</a>. This seemed like a good idea since apparently they &#8220;offer real-time data sharing between multiple client SWF files&#8221;, which is exactly what I want. However, this is only possible if you&#8217;re using Flash Media Server. I don&#8217;t really need that round-trip to the server each time and I don&#8217;t need to communicate between multiple clients, just among SWF files on the same page at a single client. I also don&#8217;t have Flash Media Server. I did toy around briefly with a polling solution using local SharedObjects though. The server SWF would contain something like this :</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> syncSharedObject<span style="color: #66cc66;">&#40;</span>sharedText:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">var</span> so:<span style="color: #0066CC;">SharedObject</span> = <span style="color: #0066CC;">SharedObject</span>.<span style="color: #0066CC;">getLocal</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;test&quot;</span>, <span style="color: #ff0000;">&quot;/&quot;</span>, <span style="color: #000000; font-weight: bold;">false</span><span style="color: #66cc66;">&#41;</span>;
    so.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">sharedText</span>= sharedText;
    so.<span style="color: #0066CC;">flush</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>And the client SWF would contain code to poll the SharedObject periodically to check for updates (I&#8217;m not going to show the boilerplate code that sets up the Timer instance):</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> syncSharedText<span style="color: #66cc66;">&#40;</span>event:TimerEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">var</span> so:<span style="color: #0066CC;">SharedObject</span> = <span style="color: #0066CC;">SharedObject</span>.<span style="color: #0066CC;">getLocal</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;test&quot;</span>, <span style="color: #ff0000;">&quot;/&quot;</span>, <span style="color: #000000; font-weight: bold;">false</span><span style="color: #66cc66;">&#41;</span>;
    sharedText = so.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">sharedText</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Simple! But also fairly braindead. This is a pull architecture &#8211; the clients aren&#8217;t notified when the data has changed, so they have to keep looking at it (say every half second), which creates some annoying overhead &#8211; each widget interested in &#8220;sharedText&#8221; would have to poll the SharedObject and that could be a lot of widgets looking at one piece of data. Of course, this gets worse if we need to pass around lots of different pieces of data!</p>
<p>So, back to the drawing board and a little more reading, after which I discovered <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/net/LocalConnection.html">LocalConnection</a>. This seems to do pretty much everything I need, but it&#8217;s definitely more complex to get up and running with. What I want is one widget to act as a server and notify all the other widgets about changes to relevant data, however I can&#8217;t designate a specific widget as the server because I don&#8217;t know if it will always be present. A simple solution would be to let the first widget to load grab the publisher/server functionality and all subsequently loaded widgets would then be subscribers/clients (I decided to call the class MessageManager, and, since it will need to raise events, it extends EventDispatcher) :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
</pre></td><td class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">//constructor (I'm not going to write out all the class definition code)</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> MessageManager<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">target</span>:IEventDispatcher=<span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">//Generate a locally unique ID.</span>
    <span style="color: #0066CC;">this</span>.<span style="color: #006600;">subscriberID</span>= UIDUtil.<span style="color: #006600;">createUID</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #0066CC;">try</span>
    <span style="color: #66cc66;">&#123;</span>
        <span style="color: #808080; font-style: italic;">//First we try to connect as the server.</span>
        conn = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">LocalConnection</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        conn.<span style="color: #0066CC;">connect</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Server&quot;</span><span style="color: #66cc66;">&#41;</span>;
        conn.<span style="color: #006600;">client</span> = <span style="color: #0066CC;">this</span>;
        isServer = <span style="color: #000000; font-weight: bold;">true</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">//initialise the subscriber cache.</span>
        subscribers = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Object</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
    <span style="color: #0066CC;">catch</span> <span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">e</span>:<span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
        <span style="color: #808080; font-style: italic;">//The server probably already exists; register ourselves with it.</span>
        isServer = <span style="color: #000000; font-weight: bold;">false</span>;
        conn = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">LocalConnection</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        conn.<span style="color: #0066CC;">connect</span><span style="color: #66cc66;">&#40;</span>subscriberID<span style="color: #66cc66;">&#41;</span>;
        conn.<span style="color: #006600;">client</span> = <span style="color: #0066CC;">this</span>;
        conn.<span style="color: #0066CC;">send</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Server&quot;</span>, <span style="color: #ff0000;">&quot;registerSubscriber&quot;</span>, <span style="color: #0066CC;">this</span>.<span style="color: #006600;">subscriberID</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #0066CC;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">target</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> registerSubscriber<span style="color: #66cc66;">&#40;</span>subscriberID:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">!</span>subscribers<span style="color: #66cc66;">&#91;</span>subscriberID<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>
         subscribers<span style="color: #66cc66;">&#91;</span>subscriberID<span style="color: #66cc66;">&#93;</span> = <span style="color: #000000; font-weight: bold;">true</span>;
<span style="color: #66cc66;">&#125;</span></pre></td></tr></table></div>

<p>There are a fair few assumptions in this code (there&#8217;s no real error handling, for a start), but it works well enough for a PoC. It may seem a little confusing to use the same class for both publisher and subscriber interfaces, and it would be entirely feasible to separate them out, but I didn&#8217;t consider that necessary for such a small scale test.</p>
<p>With the publisher and subscribers loaded and registered, I now need to be able to send a message. I created a MessageManagerEvent class which extends Event with an additional data property, this contains the &#8220;message&#8221; to be passed around (a fairly common pattern &#8211; the <a href="http://www.adobe.com/devnet/flex/samples/flex_store/">Flex store</a> sample application uses something similar but calls it ObjectDataEvent). For a widget to then update all other widgets, it just needs to create a MessageManagerEvent and call the MessageManager.sendMessage method. sendMessage determines whether the current instance of MessageManager is the server or a subscriber and either sends a single message to notify the server or iterates over the subscribers collection notifying each one in turn. I created a simple application to demonstrate this in action and included two of them below (you should be able to view source on either) :</p>
<p><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="MessageManagerTest01" width="200" height="75" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"><param name="movie" value="/flash/MessageManagerTest/MessageManagerTest.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#869ca7" /><param name="allowScriptAccess" value="sameDomain" /><embed src="/flash/MessageManagerTest/MessageManagerTest.swf" quality="high" bgcolor="#869ca7" width="200" height="75" name="MessageManagerTest01" align="middle" play="true" loop="false" quality="high" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"></embed></object></p>
<p>Just enter some text into either box and you should see it copied across to the other application.</p>
<p><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="MessageManagerTest02" width="200" height="75" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"><param name="movie" value="/flash/MessageManagerTest/MessageManagerTest.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#869ca7" /><param name="allowScriptAccess" value="sameDomain" /><embed src="/flash/MessageManagerTest/MessageManagerTest.swf" quality="high" bgcolor="#869ca7" width="200" height="75" name="MessageManagerTest02" align="middle" play="true" loop="false" quality="high" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"></embed></object></p>
<p>If you refresh the page a few times, you may notice the &#8220;SERVER&#8221; and &#8220;SUBSCRIBER&#8221; labels flip back and forth between the widgets, depending on which one loads first. If you open a new copy of this entire page, the new instances should both be saying &#8220;SUBSCRIBER&#8221; (assuming you keep this page open). Even more interesting is that if you open a copy of this page in <em>another browser entirely</em>, you may find that those say &#8220;SUBSCRIBER&#8221; as well, and that text is propagated to them from the original browser instance! (I&#8217;ve noticed this works between FireFox and IE so far, YMMV, of course).</p>
<p>A few points to note :</p>
<ul>
<li>You can use more complex objects as messages, but each widget must have a reference to that type compiled in, otherwise it won&#8217;t deserialise correctly.</li>
<li>Any type used as a message must have a default constructor, or at least a constructor with default parameters.</li>
<li>This is far from being a usable implementation, since it doesn&#8217;t account for the possibility of the server or any subscriber dying. Ideally there would be a mechanism for a subscriber to take over the server role if the server is removed, though this would probably require use of a SharedObject to persist the subscriber list.</li>
</ul>
<p><b>Update</b></p>
<p>What I&#8217;ve done here was for my benefit really &#8211; a learning exercise. What Blitz Agency has done <a href="http://labs.blitzagency.com/?p=650">here</a> is something on another level altogether. Under the hood it&#8217;s all still LocalConnection based though.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/05/widget-comms-poc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

