<?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>Hack the market</title>
	<atom:link href="http://www.puppetmastertrading.com/blog/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.puppetmastertrading.com/blog</link>
	<description>algorithmic trading experiences</description>
	<lastBuildDate>Sat, 20 Nov 2010 14:46:57 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.1</generator>
		<item>
		<title>into a pool, darkly</title>
		<link>http://www.puppetmastertrading.com/blog/2010/11/20/into-a-pool-darkly/</link>
		<comments>http://www.puppetmastertrading.com/blog/2010/11/20/into-a-pool-darkly/#comments</comments>
		<pubDate>Sat, 20 Nov 2010 14:20:43 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[market structure]]></category>
		<category><![CDATA[strategy development]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=1241</guid>
		<description><![CDATA[This past spring I was compelled to rejoin what one of my former partners had longingly referred to as &#8220;civilization.&#8221; The process of rejoining the civilized was itself of note in an environment so changed as to be unrecognizable, but I&#8217;ll skip that for now.  Instead I have some observations on the interesting spot in [...]]]></description>
			<content:encoded><![CDATA[<div class="wp-caption alignright" style="width: 290px"><a href="http://www.flickr.com/photos/jochenabitz/2264923623/"><img class="   " src="http://puppetmastertrading.com/images/poolAtNight.jpg" alt="" width="280" height="188" /></a><p class="wp-caption-text">photo credit: Jochen Abitz @flickr</p></div>
<p>This past spring I was compelled to rejoin what one of my former partners had longingly referred to as &#8220;civilization.&#8221; The process of rejoining the <em>civilized </em>was itself of note in an environment so changed as to be unrecognizable, but I&#8217;ll skip that for now.  Instead I have some observations on the interesting spot in which I&#8217;ve found myself: writing <a title="Wiki: Dark Pools of Liquidity" href="http://en.wikipedia.org/wiki/Dark_pool" target="_blank">dark pool</a> aware algos from the inside.  That is, I&#8217;m working for a block trading &#8216;dark pool&#8217; working on the team that develops their quantitative strategies.</p>
<p>While still within the world of algorithmic trading, this is a substantial change from what I&#8217;d been doing before and has proven a rich ground for learning, in particular about market structure.  The biggest aspect of the change &#8211; besides being civilized &#8211; is the change of perspective from the prop trader to, effectively, an execution trader.  As a prop trader you are looking to identify and execute trading opportunities.  Seeking alpha.  Instead, as an execution trader you receive orders and need to execute them with some highly customized sets of constraints.  You want to get things done over some time frame with some appropriate balance of aggressiveness and stealth.  Liquidity seeking.  The &#8216;what&#8217; has already been decided for you; it&#8217;s the &#8216;how&#8217; you need to worry about.  Thus, there&#8217;s some loss of &#8216;agency&#8217; in going from the former role to the latter and this corresponds precisely and inversely with the notion of agency trading.</p>
<p>Going from alpha-seeking to seeking-liquidity is a change of perspective, but the blocking and tackling are constant.  In the end, you&#8217;re trading &#8211; managing orders and positions and deluges of market data and analytics; familiar, fun stuff.</p>
<p>What I&#8217;ve found most interesting is the new perspective I&#8217;m afforded on market structures.</p>
<p><span id="more-1241"></span><strong>the default structure of a market is a social network</strong></p>
<p>My first job on wall st was on a muni desk in the mid 90&#8242;s; there was no exchange and market structure was effectively a social network.  Since then, I&#8217;ve always worked around exchange-traded instruments: futures, equities, and options on either.  Exchanges have a lot to be said for them.  We&#8217;ve seen the results of too much <a title="perfect crime" href="http://www.puppetmastertrading.com/blog/2009/11/02/perfect-crime/" target="_blank">creativity</a> and too little oversight in the magnificently free world away from exchanges.  But exchange-traded instruments haven&#8217;t been standing still.  While futures markets have exploded volume-wise and imploded as players have collapsed into one another through consolidations, US equity markets have fragmented pretty wildly.  This equity fragmentation has been especially interesting for its effects on market structure alongside the parallel &#8216;rise of the machines&#8217; in the form of high-frequency trading.</p>
<p>Equity markets have fragmented in accordance with <a title="SEC's Reg ATS" href="http://sec.gov/rules/final/34-40760.txt" target="_blank">Reg ATS</a> which provides guidelines on how Alternative Trading Systems (ATS) must behave in order to stay in good standing with the relevant authorities.  While the number of exchanges has grown slowly, ATSes have risen and fallen like city eateries over the past decade.  The interesting thing about Reg ATS is that while it covers lots of requirements, it also allows quite a bit of latitude in the determination of the microstructure of the ATS.</p>
<p><strong>market structure machines</strong></p>
<p>One, perhaps fanciful, view of dark pools is that they collectively represent a crucible in which market structures are being actively mutated and evolved.  Some experiments yield value, meet a real need and are adopted and copied while others fizzle out or perhaps even look to skirt the rules a bit.  Outside of the pools, you have all sorts of market participants always eager to glean any advantage they might from any information leakage &#8211; intentional or otherwise &#8211; from within the dynamic ATS ecology.  This is where gaming can come into play.  But, according to me, the most interesting game is played-out in the making of the very definitions of the pools themselves and how they interact with external parties.</p>
<p>Here again, we see the fundamental distinction between roles that trading entities can play.  ATSes are commercial entities; just as any broker dealer can determine if it will do principal trading or remain purely agency, ATSes can decide how they will seek to bring volumes to their venue and they can adjust their offerings at any time.  Keeping up with these changing microstructures can be a full-time job and handily explains the existence of  so-called &#8216;Smart&#8217; Order Routers (SORs), dark &#8216;aggregation&#8217; algos and such offerings as Rosenblatt&#8217;s excellent <a title="LTBL" href="http://www.rblt.com/lettherebelight.aspx" target="_blank">Let There Be Light</a> (LTBL) series.  If everybody is constantly changing their prices and adjusting their rules, it&#8217;s very non-trivial to figure out where something can best get done at any given moment in time.</p>
<p>It&#8217;s possible and illuminating to consider a venue itself as something of a trade (&#8220;value proposition&#8221;) wherein the venue is trying to add value to the overall marketplace and/or their own flow trading operations.  A market-maker or high-frequency shop might require a steady diet of deliciously uninformed retail order flow to manage their inventories.  A firm which possessed such a flow might trade against it themselves (&#8220;internalization&#8221;), might &#8220;cross&#8221; it against other client orders and might &#8220;preference&#8221; it to other interested parties like our market-maker.  They might do some combination of all three.</p>
<p>Thus, based on their motivations and goals, dark pools will self-organize in a multitude of ways as they try to meet these needs and satisfy their target constituencies.  Dark pools arose to meet a number of needs amongst financial market participants, including block trading, flow trading, utility and branding &amp; marketing purposes.  Block trading has been around forever and used to be a point-to-point social network wherein brokers simply knew which brokers specialized in blocks or might happen to have a relevant block handy.  A lot like the old muni desk.  This model was replaced by the current pioneers of &#8216;dark pool&#8217; block trading venues.  But by far the biggest dark pools from a volume perspective are those created by, yes, market-makers or hft shops for internalization purposes and large broker dealers for internalization and crossing purposes: flow trading.</p>
<p>A telling measure of the nature of a given venue is its average trade size.  Large sizes are done by block traders, whilst most flow is done in smaller sizes.  Some dark pools have average trade sizes that are even smaller than those on the &#8216;lit&#8217; exchanges.</p>
<p><strong>structural topologies, too</strong></p>
<p>Given the different motivations of the various  constituencies providing and utilizing dark venues, it&#8217;s clear that to  really understand a pool&#8217;s character, one must understand the  motivations of those providing it.  You can change the microstructure in  any number of different ways, but in the end a market remains fundamentally a social network.</p>
<p>One final aspect of market structure which I&#8217;m only now coming to appreciate for its full worth is the <em>topology</em> of market structures.  When you view the flows of orders, etc from the perspective of a venue, routing becomes a surprisingly significant part of your considerations.  When you add-in the fact that there are many inter-relations amongst all these flows, it changes the nature of markets themselves.  You can wind up with all sorts of convoluted situations stemming from &#8216;topological&#8217; considerations.  Venue A doesn&#8217;t take traffic from B, but does from C and E; B wants to get to A and has a relationship with E.  Is there now a route from B to E?  It&#8217;s complicated and it&#8217;s an area in which it&#8217;s hard to find published research.  After all, it is dark.</p>
<p><strong>into a pool, darkly</strong></p>
<p>Plunging into this environment has been quite the fun dunk as all of the aforementioned acts as the background against which my algos must now play.  This has fundamentally enriched my view of the equity markets.  Apart market structure considerations, there have been other lessons as well.</p>
<p>The problem of trading in size is one that I simply hadn&#8217;t had to worry about before.  That is, when sizes are denoted as significant percentages (or multiples!) of a given name&#8217;s Average Daily Volume (ADV), trading takes on a very different character.  When you&#8217;re looking to trade <em>in size </em>in this sense, even your analytical interests will change.   Never before have historical volume curves looked so meaningful!</p>
<p>Another nicety has been that algorithmic &#8216;execution-quality&#8217; trading, as a practice, is vastly better documented than the alpha-seeking variety, so it&#8217;s possible to learn from a very richly developed, quantitatively rigorous, body of knowledge and publication.  From a learning perspective, I&#8217;ve dropped into a target-rich environment.</p>
<blockquote><p>&#8220;Y&#8217;know, watching government regulators trying to keep up  with the world    is my favorite sport.&#8221; &#8211; character L. Bob Rife in  Neal Stephenson&#8217;s <a title="Wiki: Snow Crash" href="http://en.wikipedia.org/wiki/Snow_Crash" target="_blank">Snow Crash</a>.</p></blockquote>
<p>From a regulatory perspective also, it&#8217;s an <a title="Traders Magazine: End of the Line?" href="http://www.tradersmagazine.com/issues/20_298/sec-mary-schapiro-robert-greifeld-dark-pools-ats-104351-1.html?pg=1" target="_blank">interesting</a> environment. As I&#8217;ve argued <a title="It's not about microstructure" href="http://www.puppetmastertrading.com/blog/2009/08/07/its-not-about-microstructure/" target="_blank">before</a> (notably &#8211; before I started working for a dark pool), while these are areas that need to be regulated, they are not even close to the real sources of today&#8217;s serious financial issues.  Thus, much of the very animated talk about microstructure &#8211; principally regarding HFTs and dark pools is at best misguided and probably diversionary.</p>
<p>I&#8217;m finding the dark illuminating.</p>
<p>&#8211;</p>
<p>The opinions expressed  here may or may not be my own by the time you read them, but are most certainly NOT those of my employer.<em> </em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2010/11/20/into-a-pool-darkly/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>head in the clouds</title>
		<link>http://www.puppetmastertrading.com/blog/2010/04/21/head-in-the-clouds/</link>
		<comments>http://www.puppetmastertrading.com/blog/2010/04/21/head-in-the-clouds/#comments</comments>
		<pubDate>Wed, 21 Apr 2010 23:10:29 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[back-testing]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=1219</guid>
		<description><![CDATA[or: scaling with elastic map-reduce Between a rapidly evolving compute environment in which cores are multiplying like springtime rabbits, and a business domain in which the fecundity of market data is making those same rabbits look downright prudish, we are always looking for ways to scale our efforts.  There are three levels at which this [...]]]></description>
			<content:encoded><![CDATA[<p><strong><img class="alignright" src="/images/headintheclouds.jpg" alt="" width="200" height="259" />or: scaling with elastic map-reduce</strong></p>
<p>Between a rapidly evolving compute environment in which cores are multiplying like springtime rabbits, and a business domain in which the fecundity of market data is making those same rabbits look downright prudish, we are always looking for ways to scale our efforts.  There are three levels at which this can be typically done:</p>
<ul>
<li>&#8220;below the processor&#8221; with things like CUDA or FPGAs,</li>
<li>&#8220;amongst the cores&#8221; with things like TBB, Cilk, &amp;tc, or</li>
<li>&#8220;in the cloud&#8221; (or grid) with things likes Amazon&#8217;s EC2 and its bewildering and fast-growing coterie of associated technologies and products</li>
</ul>
<p>Today we&#8217;ll look at a simple example which we implement on top of Hadoop and then deploy into Amazon&#8217;s cloud to get a back-of-the envelope feel for what kind of scaling we might expect to gain &#8211; and at what costs &#8211; from using this smorgasboard of technologies.</p>
<p><span id="more-1219"></span></p>
<p><strong>&#8216;smorgasboard&#8217; is being generous</strong></p>
<p>Probably the hardest thing whenever you look at some new set of technologies is just getting your bearings.  Amazon&#8217;s stack is complex and very much of a moving target, so I&#8217;ll start by providing a bit of a taxonomy of the beasties we&#8217;ll need to at least familiarize ourselves with in order to get anything done.</p>
<p>First, there&#8217;s the family of <a title="AWS" href="http://aws.amazon.com/" target="_blank">Amazon&#8217;s Web Services</a> (AWS).  This has been around for a good few years, so some parts of it are quite mature and well documented and understood where others are bleeding edge with an emphasis on bleeding.  All of them can be played with quite easily by simply signing up (this involves providing a credit card, so head&#8217;s up).  I can&#8217;t think of any more interesting family of technologies, so if you think there&#8217;s any possibility these technologies might help you scale, then I encourage you to sign up and give it a spin.  Very interesting stuff.</p>
<p>Anyway, within AWS we&#8217;ll play with Elastic Compute Cloud (EC2), Elastic MapReduce (EMR), Simple Storage Service (S3) and Elastic Block Storage (EBS).</p>
<p>EC2 provides you with direct access to Amazon&#8217;s racks of humming servers in the cloud.  Thanks to the miracles of modern virtualization technologies, an entire machine can be bundled up as an image file &#8211; an Amazon Machine Image (AMI &#8211; think of an OS&#8217;s DVD but with software that you specify, configured as you please). Once bundled into an AMI, your computer can be &#8216;installed&#8217; onto any number of machines within the cloud.  Nifty.</p>
<p>Such machines can be bought for long term use (at quite affordable rates), or they can be used on an as-needed basis for an hourly charge.  Hence the &#8216;Elastic&#8217; in EC2.  They can also be managed programmatically, and until recently, this was pretty much the only way to develop jobs in the cloud.</p>
<p>Each machine that you use in EC2 has some local storage associated with it, but this is not persistent across sessions.  Once your instance goes down, the data is all gone.  To get around this and to provide an all-around storage solution, AWS provides S3 which is, to me, an overly-simplified distributed file system which is something of a pain to use.  It is also limited to file sizes of 5G which I find to be a significant annoyance.  The good news is that S3 seems to be both highly durable and reasonably performant.</p>
<p>A more recent entry in the AWS world of storage is the EBS facility.  Here, you can create arbitrary sized &#8220;disks&#8221; in the cloud which can be attached directly to your computer nodes just as though they were local disks.  Very handy.  They don&#8217;t have the same level of durability as S3 as they&#8217;re not distributed, but I haven&#8217;t had any difficulties with them and they&#8217;re very useful for putting together AMIs within the cloud.</p>
<p>Finally, EMR brings the Hadoop implementation of Google&#8217;s marvelous distributed map-reduce model into the AWS cloud.  If you haven&#8217;t read about map-reduce, well perhaps you should &#8211; it&#8217;s really powerful.  <a title="Hadoop" href="http://hadoop.apache.org/" target="_blank">Hadoop</a> is an open-source implementation of it done in Java and seems quite nice though it&#8217;s under very active development, so the APIs are still very much a work in progress.  Be prepared to change your code.  Even though it&#8217;s written in Java, any language can be used to implement your own applications, and it seems as though both ruby and python are used pretty extensively along with java and c/c++.</p>
<p><strong>what map-reduce buys you</strong></p>
<p>The first thing map-reduce buys you is something of a headache as fitting your application design into the map-reduce model isn&#8217;t so obvious.  That said, it may well be worth a couple aspirin as it brings a great deal to the game.<strong> </strong></p>
<p>Consider an application we might find interesting which we&#8217;d like to place in the cloud &#8211; strategy back-testing.<strong> </strong>It seems to be a very natural fit for parallel processing as each strategy is independent of the others, so theoretically we should be able to run each one on it&#8217;s own virtual server without interdependencies.  While this is true, it&#8217;s rather easier than it sounds.  In order to implement our distributed backtesting platform, we first need to implement one that works on one node.  Fair enough.  We must then introduce a &#8220;chunker&#8221; which will break the overall set of simulations into bite-sized chunks.  We must then define an intermediate format for sending the strategies (or instructions) to each node.  And we must define an intermediate format for the results.  And then we need to implement an &#8220;assembler&#8221; which coalesces all of the results back into one result set which can be reported on or displayed etc.  And if one of the nodes fails, we have to notice it.  And if we notice that a node has failed, we need to figure out which job(s) it was responsible for and reallocate them to another node which presumably hasn&#8217;t failed&#8230;</p>
<p>And on and on.  The point is that this isn&#8217;t something that you&#8217;re going to get done in an afternoon.  Indeed, it&#8217;s unlikely that you could write a correct and complete specification of the system in an afternoon.</p>
<p>What map-reduce buys you is all of the distribution bits that I mention above.  The costs are that you will have to figure out how to model things such that they&#8217;re compliant with the map-reduce model and that the end result might not be as efficient as a hand-coded solution.  But when you can scale easily and cheaply, then raw efficiency may not be such an over-arching concern.</p>
<p><strong>scaling in the cloud with elastic map-reduce<br />
</strong></p>
<p>In order to get an idea how difficult it is to actually scale a solution, I implemented a simple program using real data and collecting some timings across a variety of  AWS/EMR configurations.<strong> </strong>To do this, I first had to code against Hadoop v18.3 which is what is supported in AWS.  (Initially I wrote it to v20.2 and was surprised at how much I had to change to back-port it to 18.3.)</p>
<p>The details of my test program aren&#8217;t important &#8211; basically counting various features from a set of heterogeneous files.  The files are approximately the same size ~1.8G and there were 10 of them, so the overall dataset is a bit over 18G.  I only do one map-reduce; I&#8217;m not chaining them together.  On a local machine &#8211; a pre-nehalem, dual-chip w/ quad-cores (8 total) xeon server with hardware raid &#8211; the process took 1068s or a touch under 18 minutes.</p>
<p>I was impressed to see that with absolutely no code changes, I was able to run the system on EMR without difficulties.  In fact, selecting the number of nodes to run against and the size of those nodes is just a matter of changing launch parameters.  Very nice.  AWS offers a variety of different specs on their servers.  I tested the classic &#8216;small&#8217; server which provides a 32-bit O/S, one core and 1.7G of memory as well as the &#8216;large&#8217; server which comes with a 64bit O/S and 2X2 cores and 7.5Gs of memory.  There are other configurations available, but I didn&#8217;t test them.  In all cases I was running centos5.4.</p>
<p>The results are tabulated and graphed below.</p>
<div class="wp-caption aligncenter" style="width: 441px"><img src="/images/emr-timings.jpg" alt="" width="431" height="181" /><p class="wp-caption-text">performance locally and in various cloud configurations </p></div>
<div class="wp-caption aligncenter" style="width: 420px"><img src="/images/emr-timings-chart.jpg" alt="" width="410" height="228" /><p class="wp-caption-text">time to complete vs. # nodes for large &amp; small nodes</p></div>
<p>Scaling isn&#8217;t exactly linear, but it is good and it is simple and it is cheap &amp; on-demand. Clearly for any given use-case, it will make sense to do tests like this to figure out what makes the most sense.  Another dimension to consider is cost.  Even partial hours count as a full hour, so putting big or many boxes against jobs that don&#8217;t take long to run isn&#8217;t cost effective.  That said, even though I fecklessly ran jobs which took as little as 10 minutes while paying for 60, the entire costs associated with developing and running the example I present here was less than $4US.</p>
<p>One thing I noticed is that the time to initialize instances seems to grow as you increase the number of nodes, though I didn&#8217;t quantify this.  In some cases, it was really quite long before real work started getting done &#8211; several minutes at least.  Getting this to work for interactive processes will take some thought and, probably, some dedicated nodes.  Another things to note is that although my local server did a fine job for itself, if we were to increase the dataset by a factor of, say 100, we&#8217;d reach a point where it simply couldn&#8217;t complete the operation whereas the cloud isn&#8217;t so strictly bounded.  It&#8217;s also pretty interesting that my local machine with 8-cores and 24G of RAM and pretty decent RAID subsystem got soundly spanked by eight of Amazon&#8217;s cheapie 1-core boxes.</p>
<p>Given that it is cheap, massively and simply scalable and not terribly difficult, one could say that if you don&#8217;t spend some time with your head in the clouds, then it&#8217;s possible you&#8217;ve got it stuck in the sand.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2010/04/21/head-in-the-clouds/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>pairs portfolio</title>
		<link>http://www.puppetmastertrading.com/blog/2010/04/08/pairs-portfolio/</link>
		<comments>http://www.puppetmastertrading.com/blog/2010/04/08/pairs-portfolio/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 15:51:48 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[back-testing]]></category>
		<category><![CDATA[dereferenced]]></category>
		<category><![CDATA[EMS Internals]]></category>
		<category><![CDATA[portfolio management]]></category>
		<category><![CDATA[strategy development]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=1175</guid>
		<description><![CDATA[People have asked me how I go about implementing a strategy in Stratbox.  While I&#8217;ve illustrated a good number of strategies running in Stratbox in these pages, I&#8217;ve never walked through a non-trivial example from conception, through design, implementation and iteration.  Today we&#8217;ll go through a reasonably complex example in total (I&#8217;ll provide source) detail. [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" src="/images/pairs.jpg" alt="" width="269" height="180" />People have asked me how I go about implementing a strategy in Stratbox.  While I&#8217;ve illustrated a good number of strategies running in Stratbox in these pages, I&#8217;ve never walked through a non-trivial example from conception, through design, implementation and iteration.  Today we&#8217;ll go through a reasonably complex example in total (I&#8217;ll provide source) detail.</p>
<p>The example I&#8217;ve chosen is, I think, very nice because it&#8217;s a portfolio-oriented strategy, which is pretty much the only kind I care to explore; it&#8217;s also based around the concept of pairs trading, which is something which most can easily relate to; and finally, it&#8217;s already public domain and yet almost certainly has some juice in it for those who care to understand it and extend it intelligently.</p>
<p>The example comes from the blog of a company, <a title="Palantir" href="http://www.palantirtech.com/" target="_blank">Palantir</a> which does (something like?) analytical / decision support software for both finance and intelligence-gathering services (quants and spooks &#8211; spooky quants?).  The specific example is <a title="Palantir: pairs trading strategy" href="http://www.palantirfinance.com/analysis-blog/?p=194" target="_blank">here</a> and is described thusly:</p>
<p><span id="more-1175"></span></p>
<blockquote><p>In this study we explore a trading strategy that isolates pairs of  instruments within a sector that are highly correlated. We enter a trade  if the price paths of these instruments diverge, going long one  instrument and short the other, with the assumption that their price  paths will converge.</p>
<p>We construct our strategy in four parts: (1) isolate the target set  of tradable instruments, (2) choose a rule for finding correlated pairs  within that set, (3) pick criteria for entering trades, and (4) test the  trading strategy.</p>
<p>&#8230;</p>
<p>For this study we want to isolate pairs of instruments whose  correlation is above a certain threshold.  At the beginning of each  quarter, we restrict our target stocks to the top 5 in the sector by  252-day correlation to the S&amp;P 500.  Then our <a href="http://www.palantirfinance.com/apps/strategy.html">Strategy</a> uses a metric that, for a given group of stocks, outputs a list of pairs  with a correlation above our target threshold of .60 over the same time  period.</p>
<p><strong>&#8230;<br />
</strong></p>
<p>Across every day and every pair in our trading list, we check the  21-day z-score (number of standard deviations from the mean) of the  difference between the two series. We classify the stocks as diverging  when the absolute value of the z-score is between 1.5 and 3.0. When this  condition is met we short the stock that is rising and long the stock  that is falling, sizing our position relative to the z-score and the  number of pairs currently trading.</p></blockquote>
<p><strong>~(sectors) ; reframing the strategy<br />
</strong></p>
<p>While I&#8217;ll implement a strategy broadly based on their description, I will use some poetic license to modify it in ways that seem to me sensible.  First, I have good experience writing equity strategies which deal with sectors and have pretty uniformly found that sectors, as defined by S&amp;P or whomever, are more trouble than they&#8217;re worth.  Instead, looking at correlation matrices and determining on that basis who should be paired, is much more fruitful in my experience.  Tr8der has some very nice posts illustrating (very prettily!) a similar point <a title="Tr8der: equity clusters 2" href="http://tr8dr.wordpress.com/2009/12/31/equity-clusters-2/" target="_blank">here</a> and <a title="Tr8der: equity clusters" href="http://tr8dr.wordpress.com/2009/12/30/equity-clusters/" target="_blank">here</a>.  (Actually, his point is a bit broader and represents an area of possibly promising development of this strategy which I won&#8217;t pursue here.)</p>
<p>So, we&#8217;re going to chunk the idea of explicitly using sectors.  Instead, we&#8217;ll simply construct, on a monthly basis (Palantir did this quarterly) a <em><strong>TrailDays</strong></em> correlation matrix from which we&#8217;ll extract the set of pairs which have a correlation greater than <em><strong>MinCorrelation</strong></em>.  On a daily basis, we will calculate the <em><strong>ZScoreDays</strong></em> z-scores of each of these pairs and sort them by absolute value, tossing those whose values are less than <em><strong>MinZScore </strong></em>or exceed <em><strong>MaxZScore</strong></em>.  Since I don&#8217;t like the idea of having an open-ended number of pairs/positions in my portfolio, I will constrain the portfolio to a maximum of <em><strong>N</strong></em> names and will <em><strong>Allocate</strong></em> $1M to the strategy.   Finally, we will look at the effect of trading an <em><strong>EvenlyWeight</strong></em>ed portfolio or a z-score weighted portfolio (as Palantir had done).</p>
<p>The initial &#8216;universe&#8217; of equities across which we will calculate our correlations will be filtered from my database of daily equity data going back to 2005 where the closing price is over $1, the average daily dollar-volume is over $50M and the data is relatively clean (few if any gaps).  This yields an initial universe of ~600 equities and ~180K pairs.</p>
<p>Assuming that we keep <em><strong>N</strong></em> above 20 or so and we keep our allocation constant at $1M, and assume execution at the close price, we should expect our results to be reasonably believable as it&#8217;s unlikely that the size we&#8217;re trading in would distort the market.  Scaling any strategy presents its own set of challenges which we&#8217;re not going to go into for this example, but an obvious direction for scaling the strategy would be to simply run it over intraday data and scale into and out of positions as conditions permit.</p>
<p>Ok, so that&#8217;s what our strategy is going to look like.  Now, how do we &#8220;make it so&#8221;?</p>
<p><strong>structure of a stratpart</strong></p>
<p>Within Stratbox, strategies are represented as composites made-up of &#8216;stratparts&#8217; each of which has its own metadata descriptor containing parameters.  Stratparts can be composed together within a strategy to enhance or modify the behavior of a strategy.  Thus, one can have a stratpart which implements the above logic paired with another stratpart which will e.g., modify the portfolio to impose beta neutrality, damp volatility or some other form of reporting or risk management.  Given that this example is already complexish, we&#8217;ll just stick to the one stratpart.</p>
<p>A stratpart has a few key elements.  One is the metadata descriptor which allows the strategy container (stratbox) to interact with it for back-testing, optimization or forward-walking purposes, or to allow a &#8216;trader&#8217; to interact with it dynamically during run-time (the so-called &#8216;gray box&#8217;).  Beyond that, it has an essentially event-driven design.  The method <strong>quote() </strong>is called when relevant (i.e., subscribed) market data arrives.  The method <strong>execution()</strong> is called when executions for orders that originated with this strategy are received.  And the method <strong>strategyEvent()</strong> is invoked on a variety of &#8216;interesting&#8217; events that the strategy implementer might care about.  None of these methods are required, so in its simplest form, a stratpart is a very simple piece of code to write.</p>
<p><strong>services in a stratpart</strong></p>
<p>Once one has complied with the minimal requirements for implementing a stratpart, one is rewarded with a variety of useful services: subscription-based market data feeds as well as a fast snapshot db and an in-memory historical db for quick correlation analyses cover market data needs.  Position management is handled at both the strategy level and at the exchange level (if you&#8217;re trading across multiple exchanges).  There is more, including performance analysis (e.g., sharpe, and its various analytic friends) and hierarchical cash allocation within and across strategies, but we won&#8217;t look at these in this example.</p>
<p><strong>implementing metadata</strong></p>
<p>So, the first thing we need to do is define our metadata.  This is done through the use of a conventionally-named static method <strong>Descriptor().<br />
</strong></p>
<pre class="brush: java; title: ; notranslate">
public static Descriptor Descriptor() {

 ArrayList&lt;Param&gt; params = new ArrayList&lt;Param&gt;();

 String cd = &quot;Unleveraged capital to apply&quot;;
 params.add(new Param(InitialBalance, cd, false, 1000000.0));

 String n = &quot;# of instruments to hold in portfolio&quot;;
 params.add(new Param(N, n, true, 20));

 String tc = &quot;Trailing days over which to calculate correlations&quot;;
 params.add(new Param(TrailDays, tc, true, 252));

 String mc = &quot;the minimum correlation of pairs to consider&quot;;
 params.add(new Param(MinCorrelation, mc, true, .75));

 String zd = &quot;trailing days over which to calc z-score&quot;;
 params.add(new Param(ZScoreDays, zd, true, 21));

 String mizs = &quot;minimum z-score&quot;;
 params.add(new Param(MinZScore, mizs, true, 1.5));

 String mazs = &quot;maximum z-score&quot;;
 params.add(new Param(MaxZScore, mazs, true, 3.0));

 String ew = &quot;evenly-weight portfolio? (or weight by z-score)&quot;;
 params.add(new Param(EvenlyWeight, ew, true, true));

 Descriptor _desc = new Descriptor
   (&quot;puppetmaster.strats.Pairs&quot;, _Desc, params);

 return _desc;
}

public Pairs(Strategy strat, Descriptor d) { super(strat, d); }
</pre>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p>Not the most interesting chunk of code, but pretty straightforward and its inclusion opens up a lot of functionality within the environment as each of these parameters can now be systematically or manually modified in-flight.  The third parameter to the Param constructor, a boolean, indicates if we want to allow the system to optimize this parameter.  Thus, the allocation/initialBalance parameter isn&#8217;t optimizable as it wouldn&#8217;t make any sense to do so.  Even so, we can (ourselves or through an allocation algorithm) modify this value to force the strategy to lighten or extend its financial footprint.  The others are fair game for optimization.</p>
<p>The constructor is also required &#8211; with that exact signature.  This is pretty much it for the &#8216;boilerplate&#8217; code required.</p>
<p><strong>&#8216;installing&#8217; the stratpart</strong></p>
<p>Now that we&#8217;ve met the minimum requirements for a stratpart, we can install it into stratbox.  This requires adding one line to your personal stratparts.xml config file.  Like so:</p>
<pre class="brush: xml; highlight: [5]; title: ; notranslate">
&lt;?xml version='1.0'?&gt;
&lt;stratParts&gt;
 &lt;descriptor class='puppetmaster.model.strategy.FwdWalker'/&gt;
 &lt;descriptor class='puppetmaster.model.strategy.StrategyPortfolio'/&gt;
 &lt;descriptor class='puppetmaster.strats.Pairs'/&gt;
 &lt;descriptor class='puppetmaster.strats.AMBO'/&gt;
 &lt;descriptor class='puppetmaster.strats.meta.AdjMeanReverter'/&gt;
 &lt;descriptor class='puppetmaster.strats.meta.AdjTrendFollower'/&gt;
 &lt;descriptor class='puppetmaster.strats.meta.Binary'/&gt;
</pre>
<p>Once we&#8217;ve informed stratbox of the new stratpart we&#8217;ve written, we can view it within our library of stratparts within the strategy wizard in stratbox:</p>
<div class="wp-caption aligncenter" style="width: 454px"><img src="/images/plib.jpg" alt="" width="444" height="481" /><p class="wp-caption-text">Our Pairs strategy in the Strategy Wizard&#39;s stratparts library</p></div>
<p>And all of the parameters we defined within our descriptor show up on the next page where we can parameterize or optimize the strategy:</p>
<div class="wp-caption aligncenter" style="width: 453px"><img src="/images/pcfg.jpg" alt="" width="443" height="554" /><p class="wp-caption-text">Configuring the Pairs stratpart within the strategy wizard</p></div>
<p>This means that the stratpart can be combined with other stratparts to create new strategies as I&#8217;ve described  and that it can partake in the rich set of functionality within the stratbox gui.  Including actually trading.  But first, we must make the strategy actually do something&#8230;</p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong>implementing event handling</strong></p>
<p>To that end, we must implement the event handling methods I&#8217;d described previously.  Since we&#8217;re not going to do any detailed execution handling in this strategy, we&#8217;ll only implement the <strong>quote()</strong> method and a subset of the events sent to the <strong>strategyEvent() </strong>method. In particular, we&#8217;ll listen to activation events (so we can initialize cleanly), changes to our descriptor and changes to our positions.</p>
<pre class="brush: java; title: ; notranslate">
/** listen for select strategyEvents */
public void strategyEvent(StrategyEvent event) {
  super.strategyEvent(event);
  switch (event.type) {
    case Activated:            _init();                 break;
    case DescriptorChanged:    _readDesc();             break;
    case PositionChanged:      _posnChange(event);      break;
  }
}
&lt;pre&gt;</pre>
<p>For quotes, we&#8217;ll just listen to the Beginning of Day (BOD) event.  If we wanted to trade intraday, we&#8217;d have to listen to tick events, but we&#8217;ll leave that for another day&#8230;</p>
<p>From a high-level, our code is pretty simple.  We determine the universe of pairs we might trade, we select from among them, we determine what our new portfolio should look like and then we trade to transition from our current state to our desired state.  That&#8217;s it.</p>
<pre class="brush: java; title: ; notranslate">
/** mkt data goes here, but we only listen for the BOD
 * (&quot;Beginning of day&quot;) event */
public void quote(Quote q) {
  if (q.type() != Quote.Type.BOD) return; // daily strat...

  try {
    List&lt;_Pair&gt; pairs = _getPairs();
    List&lt;_Pair&gt; sel = _selectPairs(pairs);
    List&lt;Position&gt; dp = (List&lt;Position&gt;)_desiredPfolio(pairs,sel);
    _Log.debug(&quot;PORTFOLIO: &quot;+dp);
    _trade(dp);
  } catch(Exception e) { _Log.error(e.getMessage(),e); }
}
</pre>
<p><strong>the messy details</strong></p>
<p>Digging into the details gets more complex, but not horrifically so, as stratbox already has basic analytics like correlation matrices, z-scores, volatility built into it.  Likewise with basic portfolio analytics and transformations. Thus, our code to trade a (pairs-based) long-short portfolio with an arbitrary number of elements is surprisingly simple:</p>
<pre class="brush: java; title: ; notranslate">
/** given a desired portfolio, trade to make it so */
void _trade(List&lt;? extends Position&gt; desiredFolio) {
  PositionRecord[] currFolio = posns();
  // Given our current portfolio (posns) and our desired state (dfolio),
  //  we generate the set of orders which will transform from the former
  //  to the latter
  //
  List&lt;Order&gt; orders = PortfolioComposer.TransformPortfolio
    (currFolio, desiredFolio, _orderF(), _strat, _strat.account());

  // place the orders for execution
  for (Order order : orders) {
    try {
      order.setType(Order.Type.MOC); // we trade at the close only
      _subscribe(order.contract());
      _execP().placeOrder(order);
    } catch (Exception e) { _Log.error(e.getMessage(), e); }
  }
}
</pre>
<p>As promised, I provide the full source listing below for those interested, but won&#8217;t over burden the discussion with a complete description of every little piece of it.</p>
<p><strong>a telling omission and some results</strong></p>
<p>Early in my career, working as a software engineer in a wall st front office technology department, I was befriended by a manager who told me he had once been a trader.  I asked him why he wasn&#8217;t a trader anymore.  He quipped:</p>
<blockquote><p>I was half of a talented trader.  I knew, in my bones, when to get into a trade.  Sadly, I was never really sure when to get out&#8230;</p></blockquote>
<p>It seems that the author of the Palantir example suffers a similar characteristic to my old friend (or is just being understandably cagey) &#8211; she specifies an entry condition, but not an exit!  Since she doesn&#8217;t impose any costs for trading, this has no big side effects, but in stratbox we do impose (pretty onerous -&gt; realistic!) costs for trading.</p>
<p>In any case, since this is just a simple example I&#8217;ve maintained the &#8216;no exit&#8217; policy and simply exit a trade once its pair goes out of the acceptable ranges for either correlation or z-score.  This has a bad effect on the strategy as you end up churning a lot of trades at the high end of the z-score range.  That is, if we set our upper boundary for z-score to be 3, then we might enter and exit a position multiple times as the z-score oscillates between, say, 2.9 and 3.1.  A more careful implementation could minimize this effect.</p>
<p>Another difference imposed by our more realistic simulation as opposed to the original example is that I&#8217;m restricting the portfolio size explicitly and explicitly limiting myself to trading a given contract within one pair as opposed to allowing a contract to trade across multiple pairs (invoking higher costs but allowing positions to offset and thus providing a neat little optimization &#8211; assuming trading costs nothing!).</p>
<p>All the same, the strategy clearly has some positive characteristics and when parameterized to take advantage of its naive exit strategy (by making the z-score low-end quite low, e.g., 0.5) takes on the character of a hedged trend-following strategy.  How so?  Well, while we are getting churned around the high-end (entry) z-scores, our profitable exits only happen once the z-scores have diminished (the prices have converged) considerably.  So we take more, smaller losses while our winners are held a bit longer.</p>
<div class="wp-caption aligncenter" style="width: 628px"><img src="/images/pairsOpt.jpg" alt="" width="618" height="260" /><p class="wp-caption-text">some Pairs results in &#39;10</p></div>
<p>Adding to my portfolio size improves things generally (and also increases the strategy&#8217;s scalability) while increasing the <em><strong>MinCorrelation </strong></em>parameter seems to hurt performance<em><strong> </strong></em>(not sure why, honestly &#8211; perhaps because if they&#8217;re very highly correlated and already diverging so strongly it may mean they&#8217;re actually diverging fundamentally).<strong> </strong>Returning to the topic of costs, each of these strategies incurred costs of over $5K for the period in question.<strong> </strong>And returning to the parameter which governs the weighting strategy employed, although I haven&#8217;t illustrated it here (as I haven&#8217;t looked at it very carefully), my initial finding is that it changed very little.  <em><strong><br />
</strong></em></p>
<p>There&#8217;s a great many areas where this strategy could be improved &#8211; that&#8217;s the fun, after all! &#8211; but hopefully even in its primitive form this example brings to light both an interesting baseline portfolio pairs strategy, while answering the question of how one goes about concretely implementing it within stratbox.</p>
<p>The entire strategy weighs-in at ~400 LOC including comments, boilerplate and individualized imports.  The source is here: <a href="/images/Pairs.java" target="_blank">Pairs.java</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2010/04/08/pairs-portfolio/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>basic economics of an algorithmic trading startup</title>
		<link>http://www.puppetmastertrading.com/blog/2010/03/02/basic-economics-of-an-algorithmic-trading-startup/</link>
		<comments>http://www.puppetmastertrading.com/blog/2010/03/02/basic-economics-of-an-algorithmic-trading-startup/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 15:45:32 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[startup]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=1104</guid>
		<description><![CDATA[or: how to quit your job to riches! Recently I had a thought-provoking email exchange with a reader of this blog.  It was with a fellow who wanted to startup an algorithmic trading business and was seeking my advice.  Its arrival was timely for me and I hope the advice I provided the aspiring entrepreneur [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.puppetmastertrading.com/blog/wp-content/uploads/2010/02/accounting.jpg"><img class="alignright size-full wp-image-1105" title="accounting" src="http://www.puppetmastertrading.com/blog/wp-content/uploads/2010/02/accounting.jpg" alt="" width="120" height="150" /></a><strong>or: how to quit your job to riches!</strong></p>
<p>Recently I had a thought-provoking email exchange with a reader of this blog.  It was with a fellow who wanted to startup an algorithmic trading business and was seeking my advice.  Its arrival was timely for me and I hope the advice I provided the aspiring entrepreneur was helpful.</p>
<p>The conversation forced me to reconsider familiar terrain from a different perspective, so I share it along with some further thoughts in the hope that it might act as something of a counter-weight to articles and blogs entreating you to &#8220;learn algo-trading!&#8221; (as though it were a fun! weekend hobby) or &#8220;make a million % trading the xyz&#8221; and more nefarious advertisements selling the trading equivalents of male-enhancement pills &amp; potions (&#8220;I turned a used bus ticket and some pocket change into $7M in 2 months trading the e-mini!&#8221;).</p>
<p>I&#8217;ve changed the writer&#8217;s name and all identifying characteristics for obvious reasons.  He wrote:<span id="more-1104"></span></p>
<blockquote><p>Hi Tito,</p>
<p>First of all I want to say I really enjoy your blog.  I particularly like your latest portfolio of strategies that updates itself intraday while running a host of strategies in simulation.</p>
<p>I saw that you left Wall Street back in 2005; I am currently at <em>[a 'money-center' bank in]</em> London and am contemplating a similiar move.  Was wondering if you have any advice or words of thought, particularly in this market/economic environment?  My dream has always been to work at a small hf or high freq shop or to start one of my own.  After several years, I finally think I have enough strategies and angles to go forward.</p>
<p>Btw, you are not at Tower Research, are you?  They have t-shirts which read &#8220;Hack Wall Street&#8221;</p>
<p>Regards,</p>
<p><em>[Sean]</em></p></blockquote>
<p>Not knowing <em>&#8216;Sean&#8217;</em> from Adam, I replied aiming to be helpful but with a characteristic dose of snark:</p>
<blockquote><p>Hi <em>[Sean]</em>,</p>
<p>Thanks for your kind words &#8211; they&#8217;re appreciated.</p>
<p>I always have advice.  Quality is the issue.  That said, even my ordinarily low standards can&#8217;t be met w/o more info about you.  (e.g., what kind of work have you been doing?, what kind of money do you have salted away (that you are willing to lose!)? etc etc).</p>
<p>But I can still make a few observations.  My first is general:</p>
<div>If you haven&#8217;t been working, directly, in a hedge fund or a hft shop, I wouldn&#8217;t recommend trying to start one on your own.  Join one, understand all aspects of the business, build a track record and contacts and only then (if at all) attempt your own gig.</div>
<p>Regarding: &#8220;particularly in this market/economic environment&#8221;  and &#8220;HFT&#8221;:</p>
<div>
<p>HFT is (wrongly, imo) currently under serious attack.  Off-market derivatives and bought politicians were used to wreck economies, but HFT has become the scapegoat.  I believe that <em>[the bank you work at]</em> has shut down their prop HFT biz and I know that <em>[another bank]</em> has.  Many others go under every day.  Whatever else this might mean, it certainly means that there will be fewer jobs and more qualified people on the street competing for them.</p>
<p>It also means there is a possibility (probably a small one) that some kind of regulatory action literally kills the field.  A tobin tax or the like would mean the end of HFT.  Which would make HFT an unfortunate business to be in&#8230;</p>
<p>Also, HFT is a *very* specialized field.  You need to have very specialized skills to really add value.  Only you can answer if you do or not.</p>
<p>Finally, a wise wall st old-timer once told me: &#8220;there are years to make a killing on your bonus and there are years to keep your job&#8230;&#8221;</p>
</div>
<p>Regarding: &#8220;a small hf&#8221;</p>
<div>
<p>Hedge funds are (mostly) a very different business from HFT shops.  The successful hf mgrs I know all aver that the game is all about raising money &#8211; managing it is very secondary (unless you&#8217;re seriously foolish or a fraud).   It also raises the question:</p>
</div>
<p>Most of all: What do you really want to do with your life?</p>
<p>Good luck to you.  Best,</p>
<p>Tito.</p>
<p>ps &#8211; I&#8217;m not sure that I&#8217;ve ever even heard of tower research&#8230;</p></blockquote>
<p>This probably wasn&#8217;t what he wanted to hear and he came back a bit piqued at my necessarily ill-targeted advice:</p>
<blockquote><p>Same clarifications if I may:1)  When I said my dream was to start my own small hf or high freq shop, I should have stated that is my long-term goal.  In the short term, I see myself working for a hedge fund first while also trading my own PA in respectable size (quant strategies, fully systematic).</p>
<p>2) I should state that I have run a $50M systematic book successfully at <em>[London bank]</em> albeit only on low frequency strategies.  I have also worked at a very large prominent electronic market making desk at <em>[London Bank]</em>.  So while this is not the same as have direct experience at a hedge fund, I dont consider myself a novice either.  However, I agree that I am not ready to start my own hf or hf shop.  My issue at the moment is I would like to focus more on the medium-to-high frequency end at the spectrum, but it appears this is not going to be possible at <em>[London Bank]</em>.</p>
<p>3)  I agree with many of the the things you stated about HF.  Just curious, do you consider yourself a HF trader?   I honestly consider myself more of a medium frequency/intraday with no overnight risk trader.  I am definitely not ultra high frequency or doing any latency arb and I think &#8220;medium frequency&#8221; is a good place to be.</p>
<p>4) Question for you:  do you consider a 6 figure PA account large enough to establish a track record in terms of hashing out if something indeed has an _actual_ out-of-sample edge?  Granted this is not alot of money, but my assertion is that this is enough to &#8220;go live&#8221; with several systems _in very small size_ with strict money management. [ie no more than 2% risk per trade, absolute max 10:1 leverage, etc]  And I am not starting from scratch; I have been in quant strategy for over 2 1/2 years and have several systems ready to go.</p>
<p>Where I am at now is that I am ready to do #4 full-time while continuing to interview with hedge funds and high freq shops.  I have the right background Electrical and Computer Engineering from <em>[top-tier American University]</em>, graduate work in time series analysis and econometrics from <em>[top-tier UK biz school]</em>, <em>[more impressive sounding experience]</em> but it is taking longer than I had hoped to make the jump to the buy side.</p>
<p>I realize you are probably thinking &#8220;hold on to your job on the sell side at all costs etc..&#8221; as it is really bad at there and may likely get worse, and while I dont disagree, at some point a person has to move towards what they want instead of living in fear forever.  Let&#8217;s just say the past couple of years in banking have not been enjoyable.</p>
<p>Sorry for ranting but hope you can understand where I am coming from&#8230;would appreciate any advice you may still have&#8230;</p>
<p>Regards,</p></blockquote>
<p><em>Sean</em> had provided some useful information with which we could do some simple math. He had a good background and some hundreds of thousands of dollars he was willing to risk on the venture. Not bad, right?&#8230; I responded:</p>
<blockquote><p>It all sounds reasonable and none of it sounds like a rant.</p>
<p>1,2  Sound good to me.</p>
<p>3 Definitely not ultra high.  Many hundreds of trades per day at most for any given strategy.</p>
<p>4  Yes, but for what?   Your (excellent) background is certainly no handicap (though many or most places require a phd for a quant position with p&amp;l), so the question as to whether you can land the job you desire is an empirical one.  Go for it!  Certainly I wouldn&#8217;t recommend that you quit your job and start trading as that immediately puts you at a very substantial disadvantage from the perspective of employers.  I empathize with the &#8220;past couple of years in banking have not been enjoyable,&#8221; but 6 figures of savings aren&#8217;t a ton if you&#8217;re used to living a banker&#8217;s lifestyle in an expensive financial center like nyc or the city.  Going to the buy-side sounds like a great idea; quitting your job? &#8211; not so much.</p>
<p>Your decision will also depend on your position in life.  If you have a family (or want to), a partner who enjoys spending money, a desire to travel, etc etc.  Quitting your job to trade your own account is certainly ballsy and if you are successful then shazam!  If not, then you may have irrevocably pushed yourself off the (successful if not enjoyable) path you&#8217;ve worked so hard to obtain; if economies really go down the tubes or bigger wars become fashionable, you could find yourself in a really funky spot.  Or you could be wildly successful and build a giant sailboat that kick&#8217;s larry ellison&#8217;s butt&#8230;</p>
<div class="wp-caption alignright" style="width: 331px"><img class=" " src="/images/larrysTri.jpg" alt="" width="321" height="214" /><p class="wp-caption-text">New Holder of the America&#39;s Cup!</p></div>
<p>Let me ask you a few questions.  What platform(s) do you intend to use?  Where will you get your data?  How will you store it?  Manage it?  For me, back in 2005 I thought I&#8217;d just head on out there, buy some spiffy product and be off and trading.  I was profoundly wrong about that.  Retail level platforms are crap.  Seriously unusable.  (My info on this may be dated, I admit &#8211; hence my questions to you <img src='http://www.puppetmastertrading.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> )  I don&#8217;t think you can afford an institutional platform with 6figures in the bank unless you are *immediately* profitable and burning through half your wad in a few months will impose stress that&#8217;s altogether more serious than whatever ridiculous nonsense I imagine you have to put up with at <em>[London bank]</em> these days.  Building your own platform isn&#8217;t so easy and is quite time-consuming.  Worse than that, it causes you to have to focus on a lot of things that are *not* central to your primary aim.</p>
<p><strong>Let&#8217;s look at numbers.  Say you have ~$500K in hand and a requirement of ~$100K to live.  20% seems plausible.  But you will actually need to do rather better than 20%.  Insurance costs are a mother (maybe not in the uk), but they&#8217;re a good deal less than usable office space, bandwidth and lots of other oddments you&#8217;ll find yourself paying (eg, accountants aren&#8217;t free, lawyers aren&#8217;t cheap, and programmers mostly suck).  So, your real expenses aren&#8217;t 100K/year, but more like say 150K or worse.  Oh yeah, there&#8217;s taxes, too.  So, in reality starting from a 6figure base, you need to make ~30% or rather better to *break*even*.  If you have a year in which you make less than your break-even point, then the numbers get really grim.  On the other hand, you need to have a serious blowout year to make a significant difference in these basic numbers.  There&#8217;s no margin for error or, worse, misfortune.  Don&#8217;t get sick, don&#8217;t break an arm, don&#8217;t have a loved-one need anything from you and don&#8217;t lose any money!  In spite of all of your experience, intelligence and hard work, a bit of bad luck can put you into an untenable position.  There&#8217;s a good reason the Greeks believed that the only thing more powerful and less controllable than their rich pantheon of powerful Gods were <a rel="nofollow" href="http://en.wikipedia.org/wiki/Moirae" target="_blank">The Fates</a>.</strong></p>
<p>All of this said, who the heck am I?  Sounds like you have a great background and some passionate ideas about what you want to do.  I don&#8217;t want to be negative or dissuade you from pursuing a dream.  But I assume you&#8217;ve got all the up-side worked out and have thus focused on the (potential) down-side!  ;^&gt;</p>
<p>Best,</p></blockquote>
<p>I haven&#8217;t heard back from <em>Sean</em> and at this point don&#8217;t expect to though I gave him as direct and honest advice as I was capable of providing.</p>
<p><strong>a cautionary tale</strong></p>
<p>This exchange resonated with me because, almost exactly five years ago I had a &#8216;serious&#8217; conversation with my then-fiancée (and now wife and mother of our beautiful son).  I had been working hard for years and had lived very frugally (would you believe a $900/month 1-bedroom apartment in manhattan two blocks east of union sq?), saving my money to one day pursue a long-held dream.  I said to her, &#8220;I can buy you a house with cash today or I can start a business and, most likely, lose everything and have to start all over again.&#8221;</p>
<p>(This was my own version of David Einhorn&#8217;s memorable &#8216;Greenlight moment&#8217; as recounted in his &#8220;Fooling Some of the People All of the Time.&#8221;)</p>
<p>She assented and not too many weeks later I walked away from my steadily ascending career and Puppetmaster Trading was formed.  I was then in a similar circumstance to what my erstwhile pen-pal <em>Sean</em> is in today.</p>
<p>Around the time that I had this email exchange, I was being forced to face the fact that Puppetmaster Trading was in just such an untenable position as I&#8217;d described.</p>
<p>Someday I might write a post-mortem along the lines of the <a title="Roger Ehrenberg: Monitor110: a post-mortem" href="http://www.informationarbitrage.com/2008/07/monitor110-a-po.html" target="_blank">courageous and revealing post</a> Roger Ehrenberg wrote describing the errors he&#8217;d made in one of his startups.  But today isn&#8217;t that day; I need some distance and perspective to adequately compose my thoughts and identify the key errors I&#8217;ve made along the way.</p>
<p>So, to <em>Sean</em> and others like him, view this as a cautionary tale.  Don&#8217;t view it as &#8216;proof&#8217; that starting your company is a bad idea.  Even given constraints like <em>Sean</em>&#8216;s, I&#8217;m 100% certain that success was possible but for a few costly errors of judgment I personally made.  After the first year and a half, our trading returns were always positive.  In 2008 we had a real blowout year which could have been a game-changer had I not elected to pursue an ill-fated partnership (which hinted beguilingly at an outright sale) rather than sticking to what was working.  There were other mistakes, too &#8211; some of them possibly worse.  Interestingly, all of them were about running a business and not about algorithmic trading<em> per se</em>.</p>
<p>Selecting a business model and <span style="text-decoration: underline;">focus</span>, funding issues, partnership dynamics, effective team-building and the like are where the game is won or lost.</p>
<p><strong>the funny business (models) of algorithmic trading</strong></p>
<p>As far as business models go, algorithmic trading can be taken in quite a few directions, the simplest of which is proprietary trading which is where we ultimately settled.  If you&#8217;re building a platform you can try to be a product company, but then I don&#8217;t think you&#8217;d really qualify as an algo-trading concern.  One can also form one of many varieties of funds or advisories to bring in external funding and all of these have their strengths and drawbacks.  And all require the track record, marketing savvy and connections to bring in the commitments.  We&#8217;ve looked at almost all of these options and pursued a few.</p>
<p>If you&#8217;re building your own platform with the intent of trading it, it&#8217;s a bit of a funny situation, because no-one wants to bear the cost of building a system you won&#8217;t sell.  Buying systems and then integrating them such that they&#8217;re practically usable is such an expensive proposition that one is essentially forced to bring in external money unless they happen to have a few spare millions of dollars lying about that they don&#8217;t mind spending. Actually, in retrospect, this is nearly as true if you&#8217;re building instead of buying.</p>
<p>Perhaps the most interesting models that we explored were those in which algorithms backed structured products or ETF-like vehicles.  I think there will be many such products in the future with good reason.  But to do this, you need to partner with a bigger financial firm.  Here, again, you need connections (and probably will be better served by a firm name a bit more sober than our own!) and at least some heft of your own as established investment houses aren&#8217;t in the business of working with the proverbial two guys in a garage.</p>
<p>All of these are viable models, and all present unique challenges and opportunities.  The bottom-line is that to startup successfully you need to select one and then either obtain funding early on or you need to be lucky *and* commit no errors.</p>
<p><strong>to build or buy&#8230;<br />
</strong></p>
<p>As for the platform we built, Stratbox, I can only view it as a success &#8211; many tens of thousands of trades have passed through it and only once, very early on in (I think) december&#8217;05 (before it had even a rudimentary GUI), did we lose any money from it on account of a coding error.  Although I haven&#8217;t looked carefully at algo platforms in years, I&#8217;m told it has features that even well-established companies haven&#8217;t put into their commercial products and there&#8217;s no doubt that having full source code enables degrees of freedom that are impossible with off-the-shelf products.</p>
<p>The fact that Stratbox isn&#8217;t a commercial product has real drawbacks, especially in terms of the &#8216;fit and finish&#8217; one expects from established software.   But it also brings considerable  benefits in that you can really drive development based on immediate needs.  In very short time frames, you can build the 90% of functionality that you need *now*.   It&#8217;s just not possible for an established vendor to implement, test, and roll-out new features with the requisite solidity and 100% finish anywhere near as fast as can an &#8216;agile&#8217; team with skin (and maybe an organ or two) in the game.  Thus, if I were to start all over again, while I would look at the various vendor offerings (and might well change my mind based on that review), I&#8217;m still inclined to think that I&#8217;d continue to &#8220;roll my own&#8221;.</p>
<p><strong>the evolution will be blogged</strong></p>
<p>I started this blog as a means of composing my thoughts and sharing my &#8216;algorithmic trading experiences&#8217;  and in that light it&#8217;s been a quiet success.  Although it has been a minor time- and cash-sink, I enjoy it and have benefited from the people I&#8217;ve met through its pages.   I also always view writing as its own reward.  I send a sincere &#8220;thank you&#8221; to all who have read and all who have shared their own insights and experiences.  At some point &#8211; not too soon &#8211; I may try my hand at a constructive post-mortem.  In the meanwhile, I&#8217;ll continue as I have and write when I have something to say.  The longer-term fate of the blog remains to be seen and will likely depend on what I end up doing next.</p>
<p style="text-align: center;"><a href="http://www.puppetmastertrading.com"><img class="aligncenter" src="/images/logo-txt.gif" alt="" width="407" height="263" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2010/03/02/basic-economics-of-an-algorithmic-trading-startup/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>lock free</title>
		<link>http://www.puppetmastertrading.com/blog/2010/02/16/lock-free/</link>
		<comments>http://www.puppetmastertrading.com/blog/2010/02/16/lock-free/#comments</comments>
		<pubDate>Wed, 17 Feb 2010 00:55:38 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[EMS Internals]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=1010</guid>
		<description><![CDATA[One of the recurring technology themes in these pages has been the ongoing and dramatic move from single to multi-core systems and the need to seriously increase the parallelism in our software designs. For me, one of the seminal, large-grained design patterns was the SEDA Architecture. For years, this informed my systems&#8217; designs and formed [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" style="margin-left: 5px; margin-right: 5px;" src="/images/lockfree.jpg" alt="" width="310" height="324" /></p>
<p>One of the recurring technology themes in these pages has been the ongoing and dramatic move from single to multi-core systems and the need to seriously increase the parallelism in our software designs. For me, one of the seminal, large-grained design patterns was the <a title="SEDA Architecture" href="http://www.eecs.harvard.edu/~mdw/proj/seda/" target="_blank">SEDA Architecture</a>. For years, this informed my systems&#8217; designs and formed a conceptual backbone for development. That said, I&#8217;ve been broadly aware for some time that SEDA&#8217;s golden age has (incredibly!) already passed us by, but haven&#8217;t identified what might replace it as a reference point for my design efforts.</p>
<p>Before considering tools, languages or patterns that might help, we need to reflect on the problem(s) we&#8217;re trying to solve. The problems inside an EMS look to me, after years of development, a lot like network routing problems. Indeed, my current view is that this (not just concurrency as I&#8217;d suggested at the time) is why the <a title="FT: Aleynikov indicted" href="http://www.ft.com/cms/s/0/235b1260-1776-11df-87f6-00144feab49a.html" target="_blank">unfortunate</a> Aleynikov &amp; co. at GS were <a title="the other interesting thing about the serge aleynikov story" href="http://www.puppetmastertrading.com/blog/2009/07/08/the-other-interesting-thing-about-the-serge-aleynikov-story/" target="_blank">using erlang</a>.</p>
<p>Why network routing? Think about the load on an EMS. The main issue is that you&#8217;re getting many thousands of teeny little messages per second and only a relatively small number of them matter to only a relatively small subset of &#8216;agents&#8217; within the system. Reducing latency is all about making sure the time you spend on each message is minimized, and that the agents who are interested in a particular message needn&#8217;t wait for each other to do whatever they care to do based on the message. So, really you&#8217;re trying to route each message through your system with as few &#8216;hops&#8217; possible and as much parallelism as you can muster under the (radically!) new assumption that you may have hundreds or thousands of cores available to you during the lifetime of the design.</p>
<p>I spent some time thinking (hoping) that languages might help furnish an answer. Perhaps a move to a functional language like erlang, ocaml or scala might help furnish at least a partial answer. But erlang is slow and peculiar, ocaml doesn&#8217;t support intra-process concurrency and scala looks like a bloated language on a bloated platform (jvm+java class library). And none of them seem to have achieved anything near the critical mass which is so crucial for the development of usable libraries and the availability of skilled developers with long experience in the technology.  Naturally, reasonable people will disagree about such things, but this is my view (today). Java is ok (and certainly sells servers), but it&#8217;s not obvious how it&#8217;s going to help me offload my work onto a GPU anytime soon (and jni is both painful and slow) and I&#8217;ve never been able to get comfortable with just how damn big VMs get.  Image size isn&#8217;t free and if we&#8217;re looking to go deep into the sub-millisecond response time, <em>while running thousands of concurrent strategies</em>, it seems we need to disintermediate the VMs and interpreters of the world. If they&#8217;re really necessary, they can be happily used for the analysis process (as I currently use R), or they can be lit-up and bridged from some lower-level language for batch-like services.</p>
<p>The <a title="greatest technology advertisement ever?" href="http://www.youtube.com/watch?v=jqLPHrCQr2I" target="_blank">good people</a> at Intel have been thinking about this problem for a while as have many other seriously over-educated people. One of the (sensible sounding) conclusions reached as people look for ways to solve problems similar to my own, is that in such systems we should keep messages waiting as little as possible &#8211; ideally, not at all(!). This can be a problem in SEDA-like architectures which are basically made-up of (non-blocking, asynchronous) i/o processes linked to (blocking) queues linking pools of workers. Blocking queues can pile up and cause all sorts of problems like priority inversion and other such enigmatically named nasties. Lock-free queues and other data structures, algos and techniques promise some ways around this and I&#8217;ve been spending time looking into how they might be employed to address my issues.</p>
<p>Before I&#8217;m besieged by throngs of angry erlang/ocaml/scala/java developers, allow me one last observation on the topic.  (Peeved python and ruby users may rant away &#8211; vous m&#8217;amusez  ;^)</p>
<p>Why might a lock free algorithm be better than an equivalent, hardware-based locking implementation?  The answer isn&#8217;t obvious.  If locking is implemented in hardware as is typical (eg, with a compare-and-swap (CAS) instruction), then its explicit cost is measurable in (few) nanoseconds.  Hardware is fast.  The issue isn&#8217;t the speed of execution of the underlying primitives so much as it&#8217;s a consequence of the side effects of these operations at a very low level.  For real performance, cache coherence is King.  See <a title="McKenney: Memory Barriers: a Hardware View for Software Hackers" href="/images/hwViewForSwHackers.pdf" target="_blank">here</a> for an accessible discussion by IBM&#8217;s Paul McKenney and <a title="Ostrovsky: gallery of processor cache effects" href="http://igoro.com/archive/gallery-of-processor-cache-effects/" target="_blank">here</a> for some remarkable examples from Igor Ostrovsky.  This indicates that if you want the highest possible performance, you need to be aware of what is happening &#8216;in the metal.&#8217;  So we need to use a system-level language and erlang, java &amp; friends lose their candidacy in spite of any fantastic benefits they might offer.</p>
<p>Given that even the DoD has mostly given up on ADA means that we&#8217;re left with C/C++.</p>
<p>Ok, so language doesn&#8217;t seem to resolve much for us. (Indeed, it was mostly hopeful thinking on my part – design is mostly language agnostic and hardware is hardware&#8230;)</p>
<p>Apart from Intel&#8217;s own <a title="Intel's Threading Building Blocks" href="http://www.threadingbuildingblocks.org/" target="_blank">Threading Building Blocks (TBB) framework</a>, there are a variety of toolkits available for exploiting lock free parallelism. Perhaps the newest and least known is called <a title="FastFlow parallel programming framework" href="http://calvados.di.unipi.it/dokuwiki/doku.php?id=ffnamespace:about" target="_blank">FastFlow</a>, which is a C++ template library that provides a variety of facilities for writing efficient lock-free network models. It also claims to be faster than TBB, <a title="MIT's Cilk" href="http://supertech.csail.mit.edu/cilk/" target="_blank">Cilk</a> and <a title="OpenMP" href="http://openmp.org/wp/" target="_blank">OpenMP</a> while holding out the promise of one day becoming CUDA- (or more generally, GPU-) aware which would be an incredible win. Finally, it is very small &#8211; the current version (not including tests and examples), weighs in at ~5K lines of (mostly) C++ templates.  Thus, it seems to me particularly well-suited for some experimentation to assess the fit of these techniques in this space and the level of difficulty of doing so.</p>
<p>In the remainder of this post, I&#8217;ll briefly describe the FF design and then illustrate a sample C++ program which uses FastFlow to &#8216;architecturally prototype&#8217; a feed handler interacting with strategies inside an EMS / <a title="containing a strategy" href="http://www.puppetmastertrading.com/blog/2009/08/19/containing-a-strategy/" target="_blank">strategy container</a>.</p>
<p><span id="more-1010"></span></p>
<div class="wp-caption aligncenter" style="width: 509px"><img src="/images/fastflow_architecture.png" alt="FastFlow architecture" width="499" height="382" /><p class="wp-caption-text">FastFlow architecture</p></div>
<p>FastFlow&#8217;s (FF) goals seem quite ambitious, but the design is layered to allow users to work at a level that makes sense for the problems they are trying to solve, so they needn&#8217;t worry themselves (or even understand necessarily) layers below where they need to work.  At bottom is a thin layer of hardware-specific code supporting, one level up, single-producer-single-consumer (SPSC) lock-free queues and a threading model for their efficient interaction.  Above this are defined objects for generalizing from simple to arbitrary network types.  Here you see the definition of a composable Node which serves as the key abstraction for general-purpose streaming networks.  Above this are defined a variety of skeleton templates for building commonly useful graph types.  Because they are Nodes themselves, they can be nested and coupled to any depth.</p>
<p>Consider a simple pipeline:</p>
<div class="wp-caption aligncenter" style="width: 300px"><img title="pipeline" src="/images/ff_pipeline.png" alt="" width="290" height="60" /><p class="wp-caption-text">a simple FastFlow pipeline</p></div>
<p>A farm is slightly more complex and acts something like a load balancing threadpool.  The Emitter pushes &#8216;tasks&#8217; of arbitrary type to an arbitrary number of workers who then coalesce back into an (optional) Collector.  A simple Farm makes no promises about the ordering of tasks, but (I believe) FF provides mechanisms for ensuring their ordering at the collector.</p>
<div class="wp-caption aligncenter" style="width: 300px"><img title="FastFlow Farm" src="/images/ff_farm_with_coll.png" alt="" width="290" height="140" /><p class="wp-caption-text">a FastFlow Farm</p></div>
<p>Finally, because of the composable nature of Nodes, all of these graph types can be combined arbitrarily.  Here you see a Farm of pipelines with an &#8216;accelerator&#8217; (which, if I understand correctly is just an integrated thread for pushing tasks into the network) and a feedback channel.</p>
<div class="wp-caption aligncenter" style="width: 340px"><img title="Composition of subnets" src="/images/ff_composition2.png" alt="" width="330" height="140" /><p class="wp-caption-text">composition of FastFlow subnets</p></div>
<p>For a more complete (and probably accurate!) description of FastFlow, I encourage you to visit their site and <a title="FastFlow Tutorial" href="http://calvados.di.unipi.it/dokuwiki/doku.php?id=ffnamespace:usermanual" target="_blank">tutorial</a>.  The documentation remains limited, but there&#8217;s a good and growing selection of examples to examine and all of the source is available for inspection.</p>
<p><strong>a simple example</strong></p>
<p>Given my use-case, my first interest is in seeing how FastFlow might work in the context of asynchronous, non-blocking network handling.  To this end, I&#8217;ve built a simple Farm as depicted above in which the Emitter uses <strong>select()</strong> to read messages off the network which it parses and pushes into the farm for &#8216;processing&#8217; which is currently <a title="Wiki: NOP" href="http://en.wikipedia.org/wiki/NOP" target="_blank">NOP</a>-ed.  The messages/tasks are then coalesced into a collector which does nothing more than free memory allocated in the Emitter.  Within the Farm, each of the nodes inhabits its own thread and outside of the farm I&#8217;ve implemented a very simple &#8216;client&#8217; which connects to the Emitter&#8217;s socket and sends delimited Integral &#8216;messages.&#8217;  Ordinarily this would appear in its own process, but for the sake of only requiring 1 file, I&#8217;ve mashed them all together and the client lives in its own thread.  That&#8217;s it.</p>
<p>It turns out that the FastFlow part of this is, by far, the simplest.  Since the FF skeletons are implemented as templates, extending them couldn&#8217;t be much easier.  Here&#8217;s the definition of the worker and collector components.</p>
<pre class="brush: cpp; title: ; notranslate">
// typical worker: does little ;^p
class Worker: public ff_node {
public:
  void * svc(void * task) {
    return task;
  }
};

// collector that just frees the malloc'ed memory
class freeing_collector: public ff_node {
public:
  void * svc(void * task) {
    int * t = (int *)task;
    if (*t == -1) return NULL;
    else free(task);
    return GO_ON;
  }
};
</pre>
<p>They are both nodes and their only requirement is to implement the <strong>svc</strong> method which is called by the FF framework when they are meant to service a task.  They can optionally implement <strong>svc_init</strong> and <strong>svc_end </strong>methods which provide an opportunity for initialization and cleanup.  The socket-reading emitter makes use of the <strong>svc_init</strong> method to initially setup the socket.  Later, as it repeatedly reads from the socket into a buffer, it cracks the incoming stream and then calls the <strong>ff_send_out()</strong> method to push those messages out to the downstream workers.  The whole example is about 350 lines of code and nearly 200 lines are consumed by the Emitter.  Almost all of this bulk is network-related, so I won&#8217;t illustrate here.  But highlighted here you can see the main FF-specific part of the Emitter:</p>
<pre class="brush: cpp; highlight: [16,17,18,19]; title: ; notranslate">
 // handle new data coming in
 void new_data(int nbytes, const char* buf) {
   static char remainder[kMaxMsgSz];
   int *t;
   int j = 0;
   int i = 0;
   char msgbuf[kMaxMsgSz];
   for (; i &lt; nbytes; i++) {
     if ( kDelimiter == buf[i] ) {
       int rlen = (j==0) ? strlen(remainder) : 0; // remainder?
       int len = i-j;
       if (rlen&gt;0) strncpy(msgbuf,remainder,rlen);
       int start = (rlen==0) ? 0 : rlen;
       strncpy(&amp;(msgbuf[start]),&amp;(buf[j]),len);
       msgbuf[len+rlen] = '&#92;&#48;';
       t = (int *)malloc(sizeof(int));
       *t = atoi(msgbuf);
       j = i;
       ff_send_out(t);  // push message into farm
     }
   } // for

   int k = j+1;
   if (k &lt; i) { // save 'remainder'
     strncpy(remainder,&amp;(buf[k]),(i-k));
   } else remainder[0] = '&#92;&#48;';
 }
</pre>
<p>Finally, all of the pieces are assembled and launched in the<strong> main()</strong>.</p>
<pre class="brush: cpp; title: ; notranslate">
//  We construct a 'server' which is a fastflow emitter and which reads
//    integral 'msgs' from a client over a non-blocking socket.  Msgs
//    are parsed and fed into a fastflow farm for further handling.
//    The client is placed within its own thread - this is only so the
//    whole example can be placed in one file.
//
int main(int argc, char * argv[]) {
 // use: argv[0] &lt;#msgs=1024&gt; &lt;#port=9999&gt;

 int msgs = (argc &gt; 1) ? atoi(argv[1]) : 1024;
 int port = (argc &gt; 2) ? atoi(argv[2]) : 9999;

 int nworkers = 5;               // how many workers will recv msgs

 printf(&quot;main: sending #%d msgs to port &lt;%d&gt;\n&quot;,msgs,port);

 select_reader sr(port);         // we create 'server'
 freeing_collector fc;           // and a freeing collector
 ff_farm&lt;&gt; farm;                 // and a farm for it to live in
 farm.add_emitter(&amp;sr);          // add both to the farm
 farm.add_collector(&amp;fc);

 std::vector&lt;ff_node *&gt; workers; // build a collection of workers
 for(int i =0; i &lt; nworkers; i++) { workers.push_back(new Worker); }

 farm.add_workers(workers);      // add all workers to the farm

 farm.run();                     // launch the farm
 printf(&quot;main: started farm.\n&quot;);

 sr.wait_til_ready();            // don't create client til srvr ready

 // create client which will send msgs via socket
 //
 printf(&quot;main: creating client...\n&quot;);
 client_thread* client = new client_thread(msgs,port);
 if (client != NULL) client-&gt;join();

 farm.wait();                    // wait for farm to be done its workload

 // emit some stats
#if defined(TRACE_FASTFLOW)
 std::cout &lt;&lt; &quot;DONE, time= &quot; &lt;&lt; farm.ffTime() &lt;&lt; &quot; (ms)\n&quot;;
 farm.ffStats(std::cout);
#endif

 return 0;
}
</pre>
<p>The whole example can be found <a title="FF networking example: C++ source" href="/images/ttest.cpp" target="_blank">here</a>.</p>
<p>Writing this example was a bit of a &#8216;tale of two frameworks&#8217; for me as I found the FastFlow part to be really easy and powerful.  On the other hand, I wanted to try out the <a title="boost::asio" href="http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html" target="_blank">boost::asio</a> framework for non-blocking networking i/o (primarily in the hope it might cut down the code size a bit) and while implementing the trivial (blocking) client was, well, trivial, implementing a non-blocking server with boost::asio was a serious pain and I ultimately decided that <a title="Linus' screed on C++ and boost" href="http://thread.gmane.org/gmane.comp.version-control.git/57643/focus=57918" target="_blank">Linus just might be on to something wrt to boost</a> and scrapped that part of the effort (but kept the boost client).</p>
<p>Nothing about this example illuminates the potential performance advantages of a lock free approach, but this exercise has certainly convinced me that the FF authors have managed to combine very low-level performance considerations within a package which can be easily used from a high-level perspective.  Most problems will most likely be better served by higher-level programming languages, but some problems remain intractably bound to the metal and I suspect that writing ultra-low-latency trading systems will remain in the latter class for some time to come.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2010/02/16/lock-free/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>transitions</title>
		<link>http://www.puppetmastertrading.com/blog/2010/02/08/transitions/</link>
		<comments>http://www.puppetmastertrading.com/blog/2010/02/08/transitions/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 21:21:12 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[EMS Internals]]></category>
		<category><![CDATA[portfolio management]]></category>
		<category><![CDATA[regime-switching]]></category>
		<category><![CDATA[strategy development]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=1004</guid>
		<description><![CDATA[Today we return to our series on regime switching and the topic of managing portfolios of strategies.  In particular, we build on the examples illustrated in sensitivity testing and steppin&#8217; out, in which we showed historical and then real-time &#8216;forward-walking&#8217; of strategies.  The next step we&#8217;d described was to evolve the techniques illustrated to support [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" style="margin-left: 5px; margin-right: 5px;" src="/images/genetic.png" alt="" width="353" height="285" />Today we return to our series on regime switching and the topic of managing portfolios of strategies.  In particular, we build on the examples illustrated in <a title="sensitivity testing: historical forward walk" href="http://www.puppetmastertrading.com/blog/2009/11/14/sensitivity-testing/" target="_blank">sensitivity testing</a> and <a title="steppin' out" href="http://www.puppetmastertrading.com/blog/2009/11/25/steppin-out/" target="_blank">steppin&#8217; out</a>, in which we showed historical and then real-time &#8216;forward-walking&#8217; of strategies.  The next step we&#8217;d described was to evolve the techniques illustrated to support the real-time management of a portfolio of strategies.</p>
<p>In the example below, we look at another &#8216;meta&#8217; strategy named <em>StrategyPortfolio</em> which maintains a dynamic portfolio &#8211; P &#8211; of strategies which it will select from a set of strategies &#8211; S &#8211; running concurrently in simulation.  The constituents of P as well as their cash allocations and parameterizations will be rebalanced/adjusted regularly after an initial &#8216;out-of-sample&#8217; period during which only the S strategies are run.</p>
<p>Apart education, the intention of this strategy, as I&#8217;d originally suggested <a title="multi-strategy trading with regimes" href="http://www.puppetmastertrading.com/blog/2009/09/13/multi-strategy-trading-with-regimes/" target="_blank">here</a>, is to &#8216;back-into&#8217; a regime-switching strategy without attempting to directly quantify the regimes explicitly.</p>
<p>This has proved to be even more interesting than I&#8217;d expected, not so much because it performs particularly well (though it&#8217;s promising), but because of all of the things it has taught us.  In particular, the transitions are a killer and there are properties of strategies which (dis-)qualify them from being effective in such a scheme&#8230;</p>
<p><span id="more-1004"></span></p>
<p><strong><em>bad news </em><em>good news </em></strong><img class="alignleft" style="margin-left: 5px; margin-right: 5px;" src="/images/goodbad.jpg" alt="" width="270" height="212" /></p>
<p>As before, I&#8217;m not going to take the time to write-up my results in any formal manner but will again rely upon a quick screencast of the software running.  The good news is that I&#8217;m figuring out how to edit these things, so it&#8217;s mercifully shorter than earlier screencasts&#8230;</p>
<p><a title="Screencast: StrategyPortfolio in Stratbox" href="/images/flash/StrategyPortfolio/StrategyPortfolio.html" target="_blank">Please click here to see the screencast.</a></p>
<p>I hope you find it interesting and will look forward to any comments or suggestions you might make.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2010/02/08/transitions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Kooderive</title>
		<link>http://www.puppetmastertrading.com/blog/2010/02/03/kooderive/</link>
		<comments>http://www.puppetmastertrading.com/blog/2010/02/03/kooderive/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 15:31:20 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[dereferenced]]></category>
		<category><![CDATA[EMS Internals]]></category>
		<category><![CDATA[monte-carlo methods]]></category>
		<category><![CDATA[open-source software]]></category>
		<category><![CDATA[options pricing]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=1000</guid>
		<description><![CDATA[Some time back, I&#8217;d written about NVidia&#8217;s CUDA noting that it looked ideal for many asset-pricing and monte-carlo type problems in finance.  At the time, I was hopeful that it would be quickly integrated into existing open source efforts like QuantLib, but adoption has proved slower than I&#8217;d hoped, most likely because implementing non-trivial problems [...]]]></description>
			<content:encoded><![CDATA[<div class="wp-caption alignleft" style="width: 240px"><img class="   " src="/images/cuda_simonRogerson.jpg" alt="photo by Simon Rogerson" width="230" height="173" /><p class="wp-caption-text">photo by Simon Rogerson</p></div>
<p>Some time back, I&#8217;d <a title="TESLA &amp; CUDA" href="http://www.puppetmastertrading.com/blog/2008/11/29/nvidias-tesla-and-the-compute-unified-device-architecture/" target="_blank">written</a> about NVidia&#8217;s CUDA noting that it looked ideal for many asset-pricing and monte-carlo type problems in finance.  At the time, I was hopeful that it would be quickly integrated into existing open source efforts like <a title="QuantLib: a free/open-source library for quantitative finance" href="http://quantlib.org/" target="_blank">QuantLib</a>, but adoption has proved slower than I&#8217;d hoped, most likely because implementing non-trivial problems on CUDA is, well, even less trivial than doing them without..</p>
<p><strong>LMM on CUDA</strong></p>
<p><strong> </strong>Happily, I&#8217;ve just seen a promising first step in this direction as Über-quant and C++ artisan <a title="Mark Joshi" href="http://www.markjoshi.com/" target="_blank">Mark Joshi</a> recently announced an open-source project, <a title="Sourceforge: Kooderive" href="http://sourceforge.net/projects/kooderive/" target="_blank">Kooderive</a> which looks to implement the <a title="Wiki: LMM" href="http://en.wikipedia.org/wiki/LIBOR_market_model" target="_blank">LIBOR Market Model</a> (LMM)  on top of CUDA.  His announcement on the QuantLib mailing lists reads:</p>
<blockquote><p>Dear All,</p>
<p>various people have shown interest in the use of <span id="lw_1265210335_0">CUDA</span> with QuantLib. I<br />
have now made some progress on a CUDA implementation of the <span id="lw_1265210335_1" style="border-bottom: 1px dashed #0066cc; background: transparent none repeat scroll 0% 0%; cursor: pointer;">LIBOR<br />
market model</span>.</p>
<p>In particular, I now have a path generator for the LMM working which<br />
does 16384 paths for 40 rates, 40 steps, 5 factor model, displaced<br />
diffusion predictor-corrector that takes 0.1 seconds on my Quadro 4600.</p>
<p>The state of the project is code fragments that can be called from<br />
other code. Those who are interested can get the code via<br />
the subversion repository on <a href="http://kooderive.sourceforge.net/" target="_blank"><span id="lw_1265210335_2">kooderive.sourceforge.net</span></a> .  The only<br />
project file is currently for VC9 x64. It also uses thrust and the<br />
CUDA SDK.</p>
<p>The next stage will be writing routines, that use QuantLib for the CPU<br />
stuff and kooderive for the GPU stuff,  to actually price things.</p>
<p>A gentle reminder that I will be giving a course on the LMM and<br />
QuantLib in June in <span id="lw_1265210335_3" style="background: transparent none repeat scroll 0% 0%; cursor: pointer;">London</span>, and I will include a session on kooderive<br />
if there<br />
is sufficient interest.</p>
<p>I am happy to take code contributions for kooderive. However, I am not<br />
looking for a redesign of the library or contributions which introduce<br />
dependence on other libraries. I am interested in contributions of<br />
separate routines and of optimizations of existing routines that do<br />
not change interfaces.</p>
<p>regards</p>
<p>Mark<br />
&#8211;<br />
Pricing exotic <span id="lw_1265210335_4" style="border-bottom: 1px dashed #0066cc; background: transparent none repeat scroll 0% 0%; cursor: pointer;">interest rate derivatives</span> &#8211; The <span id="lw_1265210335_5" style="background: transparent none repeat scroll 0% 0%; cursor: pointer;">LIBOR Market Model</span> in<br />
QuantLib <span id="lw_1265210335_6" style="border-bottom: 1px dashed #0066cc; cursor: pointer;">June 2010</span>, London,<br />
<a href="http://www.moneyscience.com/training/index.html" target="_blank"><span id="lw_1265210335_7">http://www.moneyscience.com/training/index.html</span></a></p>
<p>Assoc Prof Mark Joshi<br />
Centre for Actuarial Studies<br />
<span id="lw_1265210335_8">University of Melbourne</span><br />
My website is <a href="http://www.markjoshi.com/" target="_blank"><span id="lw_1265210335_9">www.markjoshi.com</span></a></p></blockquote>
<p><span><br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2010/02/03/kooderive/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>dingbat kabuki</title>
		<link>http://www.puppetmastertrading.com/blog/2010/01/28/dingbat-kabuki/</link>
		<comments>http://www.puppetmastertrading.com/blog/2010/01/28/dingbat-kabuki/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 13:08:01 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[execution quality]]></category>
		<category><![CDATA[market structure]]></category>
		<category><![CDATA[our managed markets]]></category>
		<category><![CDATA[post-trade analysis]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=973</guid>
		<description><![CDATA[Like many Americans, last night I dutifully switched on my TV at 9pm to see the State of our Union.  Always a spectacle, America&#8217;s leadership have upped the surreality ante with the bizarre backdrop of Biden lip-synching amiably in the background whilst Madame Speaker sat with all the calm collection of a fish on a [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" src="/images/kabuki.gif" alt="" width="200" height="304" /> Like many Americans, last night I dutifully switched on my TV at 9pm to see the State of our Union.  Always a spectacle, America&#8217;s leadership have upped the surreality ante with the bizarre backdrop of Biden lip-synching amiably in the background whilst Madame Speaker sat with all the calm collection of a fish on a hook and never seemed fully in control of herself or her eyebrows.  The spectacle of would&#8217;ve-been king McCain sitting there and glowering openly at the lecturn as his confederates sat in stony silence while their &#8216;opposition&#8217; applauded like drunken high schoolers at a home coming at every mundane utterance proved a bit much and I had turned off the glowing beacon of groupthink by 9:25 and gone to investigate something on my computer.  I was surprised and delighted to see that it was still available: dingbatkabuki.com</p>
<p><strong>Dingbat Kabuki and other <em>structural</em> market hacks</strong></p>
<p>When I first started puppetmaster trading, one of my dearest friends, a Yale-educated economist and professor of same, asked me an important question.  He asked:</p>
<blockquote><p>In the markets, there are always &#8216;insiders&#8217; who have the ability to trade on knowledge that you <em>can&#8217;t</em> know or with an advantage that you <em>can&#8217;t</em> have.  How are you going to compete with these players?</p></blockquote>
<p>I provided a variety of answers, but at the time my conception of the universe of people with both inside knowledge and the ability to trade on it was limited to cases like that of Mr Rajaratnam.  I believed that cases like these were constrained by clear laws that were duly surveilled and prosecuted by the appropriate authorities.  The problem seemed like a very real one, but constrained in size and not essential to my enterprise.  I still hope that my belief of the time was true, but since then I&#8217;ve certainly understood that there&#8217;s more than one way to hack the market.</p>
<p>For some, a market hack might consist of some kind of simple (or complex) algorithm(s) applied to some set of markets.  But this really isn&#8217;t a hack so much as it&#8217;s a trading strategy &#8211; like many that have long existed &#8211; only that it&#8217;s now implemented in software where originally it would have been implemented in wetware.  While implementing trading strategies in software does open up new vistas in terms of the kinds of strategies that you can look to implement &#8211; computers are faster than people by a noteworthy amount in many tasks &#8211; but, for the most part, you&#8217;re really still just trading and when you take on positions, you are still bearing risk.  You might be &#8216;hacking&#8217; but it&#8217;s really not a market hack as I&#8217;ve come to appreciate.</p>
<p><span id="more-973"></span></p>
<p><strong>hack the market structure </strong></p>
<p>Another area where my perspective has changed substantively since those halcyon days of &#8217;05 is my appreciation for market (micro) structure.  In futures, market structure is pretty plain as most contracts are effectively monopolies run by their listing exchanges.  There are a few cases of instruments which are tradable across markets, but a rich market microstructure is just not a core identifying characteristic for futures like it is in the fragmented and incredibly dynamic and quickly developing world of equities.  So, while there are some dozens of futures exchanges scattered about the globe, as a futures trader, routing algorithms just don&#8217;t enter the picture except in limited and relatively simple cases.</p>
<p>If I have a view on or a hedging need for interest rates that I see effectively expressed through futures, then I go to e.g. the cme and I don&#8217;t need to worry my pretty head about getting a great execution because the exchange is in one place and it&#8217;s all lit up and filled to the brim with liquidity.  Easy peasy.  But if I have a view on, say, General Electric that I want to express with an equity position and I&#8217;m trading in sufficient size or sufficiently close to the market that I really want to ensure best execution, then I might find the need to look around some dozens of lit exchanges and maybe even ping about in a dark pool or twelve.  This is decidedly not easy peasy and is one of the reasons wall st has an insatiable hunger for propeller heads with advanced degrees in seemingly unrelated fields.</p>
<p>Last summer&#8217;s brouhaha about &#8216;flash&#8217; orders first illuminated for many a rich ground for genuine market hacks: the incredibly dynamic terrain of equity market micro structure which changes almost daily with the emergence of new exchanges, ATSes, order types, rebates and pricing structures and all of the many other critical minutia that differentiate the many venues.  Some of these undoubtedly provide meaningful and important services; contrary to populist inclination, dark pools are largely a defense <em>against</em> frothy HF trading strategies.</p>
<p>But the concern (if perhaps not all of the attention) is <a title="Rosenblatt's view on HF Trading" href="http://hft.thomsonreuters.com/files/2009/11/Rosenblatt-HFTexcerpt4Reuters2.pdf" target="_blank">merited</a>.   Equity microstructural &#8216;rules&#8217; change so quickly that even independent and upright regulators could hardly be expected to keep up.  This is clearly fertile ground for genuine &#8211; if perhaps fleeting &#8211; market hacks.</p>
<p><strong><a title="Wiki: Steganography" href="http://en.wikipedia.org/wiki/Steganography" target="_blank">steganography</a> and hacking the market<br />
</strong></p>
<p>What characteristics make equity market structure a fertile ground for these kinds of genuine market hacks which I&#8217;m describing?  I think the main answer is to be found in the ancient art of steganography &#8211; hiding in plain site.  Everything about equity market microstructure is public.  All of the rules for each of the venues are available to the people who might make use of them.  Unraveling what they <em>imply</em> about where you should be executing for any given order is the tricky bit which is hardly revealed through a simple reading of all of the various rules.</p>
<p>Where else do we see this phenomenon?  The US Tax code comes to mind (sort of like the iPhone: &#8220;there&#8217;s a loophole for that&#8221;).  The 2,000 page health care bill comes to mind.  Everybody seems to care about health care, but who&#8217;s actually read that bill?  Who could?</p>
<p>Totally public yet it may as well be encrypted.  Steganography.</p>
<p>Elizabeth Warren has also made this observation in the context of contracts made between banks and their retail clientele.  Noted scholar Scott Adams dubbed it a &#8216;<a title="Wiki: Confusopoly" href="http://en.wikipedia.org/wiki/The_Dilbert_Future" target="_blank">confusopoly</a>.&#8217;</p>
<blockquote><p><em>a group of companies with similar products who intentionally confuse customers instead of competing on price</em></p></blockquote>
<p>So, could people hack the tax code?  <a title="Hanky panky" href="http://www.puppetmastertrading.com/blog/2009/01/08/and-this-little-piggy-hollowed-out-our-nation/" target="_blank">Hank</a> and I think so.  So do my friends in the <a title="Play by the rules" href="http://www.puppetmastertrading.com/blog/2009/04/13/playing-by-the-rules/" target="_blank">lobbying business</a>.  How about all those recently converted bank holding companies &#8211; hack much?  In my last post we read one insider&#8217;s view that Madoff had effectively hacked the SEC&#8230; perhaps regulatory organizations themselves are also hackable instruments!  How about that health care bill?  &#8230;</p>
<p><strong>misdirecting the hack</strong></p>
<p>A lot of attention has focused recently on exchange traded markets and people are up in arms about HF traders and proprietary trading.  I&#8217;ve argued <a title="it's not about microstructure" href="http://www.puppetmastertrading.com/blog/2009/08/07/its-not-about-microstructure/" target="_blank">before</a> that this appears to be a great ploy to take attention away from the real issues at hand; in the worst case, HFT improprieties might account for no more than 1% of the money <em>disappeared</em> in the last few years as part of the so-called &#8216;credit crisis&#8217;.  It&#8217;s easy for non-finance-professionals not to understand that the big bad wolves of the credit crisis essentially all happened off market in essentially unregulated multi-trillion dollar otc markets of <a title="perfect crime" href="http://www.puppetmastertrading.com/blog/2009/11/02/perfect-crime/" target="_blank">ingeniously engineered</a> structured products. These are the <em>real</em> market hackers.  Exchange traded instruments had effectively nothing to do with our current circumstances but remain a convenient scapegoat.</p>
<p>Some argue persuasively that there are fundamental, <a title="Murray Rothbard: The Case Against the Fed" href="http://mises.org/books/fed.pdf" target="_blank">structural market hacks</a> at the very foundations of our financial system.  I wouldn&#8217;t know.  But it is the kind of thing one might think about while watching the highly stylized performance of our leaders last night.</p>
<p><strong>dingbat kabuki and the transparent market hack</strong></p>
<p>To my knowledge, Cal&#8217;s (go bears!) Professor Brad DeLong coined the term &#8216;dingbat kabuki&#8217; back in 2005 in <a title="the original" href="http://delong.typepad.com/sdj/2005/10/dingbat_kabuki_.html" target="_blank">shrill response</a> to a Washington Post article.  He reprised the term this week in response to the latest bit of <a title="Andrew Mellon's rotting corpse" href="http://delong.typepad.com/sdj/2010/01/barack-herbert-hoover-obama.html" target="_blank">macroeconomic genius</a> out of washington.  What an inspired phrase.  Yesterday at 2:30 and last night at 9pm the markets voiced their applause and cheered on the performance.</p>
<p>Indeed, it is masterful.</p>
<p>&#8211;</p>
<p>A technical note about this post.  While writing it, I seem to have accidentally published it at some point and then realized the error and &#8216;unpublished&#8217; it.  I apologize if this had any untoward effects on you or your RSS reader.</p>
<p><strong><br />
</strong></p>
<p style="text-align: center;"><img class="aligncenter" src="/images/musashi.jpg" alt="" width="677" height="325" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2010/01/28/dingbat-kabuki/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;the SEC made Madoff&#8221;</title>
		<link>http://www.puppetmastertrading.com/blog/2010/01/17/the-sec-made-madoff/</link>
		<comments>http://www.puppetmastertrading.com/blog/2010/01/17/the-sec-made-madoff/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 14:32:59 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[dereferenced]]></category>
		<category><![CDATA[our managed markets]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=944</guid>
		<description><![CDATA[Bill Harts, a friend of mine who has, as they say, forgotten more about electronic trading and market structure than most will ever be burdened by, has recently taken an interest in the public letters written to the SEC in response to their requests for public comments on dark pools.  Mostly, these letters are funny [...]]]></description>
			<content:encoded><![CDATA[<p><a title="Bill Harts &amp; Co." href="http://hartsandco.blogspot.com/" target="_blank">Bill Harts</a>, a friend of mine who has, as they say, forgotten more about electronic trading and market structure than most will ever be burdened by, has recently taken an interest in the <a title="public letters to the SEC on dark pools" href="http://hartsandco.blogspot.com/2010/01/dark-pool-letters-to-sec.html" target="_blank">public letters written to the SEC</a> in response to their requests for public comments on dark pools.  Mostly, these letters are funny and reveal people&#8217;s propensity to point shoot and aim in that untidy order.</p>
<p>But some are revealing and one in particular is <a title="Steve Wunsch letter to SEC" href="http://www.sec.gov/comments/s7-27-09/s72709-32.pdf" target="_blank">100% required reading</a> for anyone interested in electronic markets.</p>
<p>The writer introduces himself thusly:</p>
<blockquote><p>I am Steve Wunsch, the principal inventor of two SEC‐regulated stock exchanges, the Arizona Stock Exchange “AZX” (originally called Wunsch Auction Systems, Inc. “WASI”) and the ISE Stock Exchange, both of which include dark pools. In fact, both of them, like all modern stock exchanges, have both lit and dark components and, thus, have provided me with potentially useful perspective on the dark pool question and on transparency in general. I will focus heavily on the latter, for it is impossible to understand the dark pool issues raised without understanding the value of transparency or, if improperly applied, the lack thereof. The AZX experience was, I believe, particularly instructive in this regard. Its highly transparent call market structure, combined with its unique regulatory status as a “low volume exempt”exchange, enabled me to see transparency and the role of regulation in promoting it from a perspective that I don’t believe anyone else has.</p></blockquote>
<p>He deftly mixes snark and a historical perspective on regulation with an opinionated and informed view on the forces driving current equity markets&#8217; microstructure arguing that the worst issues are due to regulatory failures.  He concludes, logically enough, that the SEC should be disbanded.  Perhaps his most inflammatory bit is his claim that the &#8220;SEC made Madoff.&#8221;  For effect, the section is entitled &#8220;An American Oligarchy&#8221;:</p>
<blockquote><p>AN AMERICAN OLIGARCHY</p>
<p>It is not in the Commission’s interest to admit failures of policy, such as the ones I have described in this letter, and I have never seen it done. It was not in the Commission’s interest to admit that Bernie Madoff was the SEC’s most trusted and intimate confidante in formulating and selling transparency, electronic trading and<br />
the whole NMS concept to Wall Street, the public and Congress. His legitimate business was the epitome of the kind of transparent electronic competition that NMS’s leveling policies were trying to create, and he occupied the most favored place of all industry advisors on policy and rules as NMS was being created. In a very real and literal sense, Madoff’s legitimate business and NMS were made for each other. NMS cleared a path for the application of continuous transparency by new electronic competitors, very visibly led by Madoff, enabling him to become at one time the third largest market in the United States, even though he wasn’t officially registered as anything but a broker‐dealer.</p>
<p>Had the SEC not emasculated the rules by which the NYSE controlled its members, Madoff would never have happened. In the time before NMS, when the exchange had Rule 390 or the stronger Rule 394 before it, diverting orders away from the floor or selling them to Madoff would have been banned. But on antitrust principles, the SEC wanted to foster NYSE‐busting competition in NMS, and Madoff became its PosterBoy for such competition. In order to make way for him, the SEC opened up a variety of loopholes that allowed orders to be diverted from NYSE to Madoff and printed on regionals like Cincinnati. Rules 19c‐1, 19c‐2 and 19c‐3 were in this vein. There were perennial attempts by the NYSE to plug the loopholes and rein in the membership, but the SEC batted them all away, enabling Madoff to continually grow his business. Eventually, the NMS environment forced the NYSE to abandon Rule 394, then Rule 390 and ultimately its membership organization altogether when it demutualized. This was all very good for Madoff. And Madoff was very good for NMS, giving it industry cred far in excess of what this poorly articulated socialist leveling theory could have had without his support.</p>
<p>In spite of a 457‐page SEC investigation into Madoff and how his Ponzi scheme was missed, the most obvious reasons were not considered, namely, that Madoff played a central role in helping the Commission design and sell NMS, and that NMS made him rich long before the Ponzi scheme. Most importantly, the credibility that theCommission’s collaboration with Madoff on NMS conferred on him was the principal factor enabling him to bring in money for the Ponzi scheme. Although the investigation’s report notes his credibility in the industry, it is mentioned as if itwere just a fact of life and was already there. Not mentioned is that his superior access to the SEC and apparent influence over the Commission, both of which were implicitly proved by his ability to get rich on NMS, are the most important reasons that he had such extraordinary credibility in the industry. The truth is that the SEC made Madoff. He could not have existed as a threat to investors without the Commission’s active and dedicated support over several decades.</p></blockquote>
<p>Although, in typical blogger fashion, I&#8217;ve highlighted his spiciest claim, the rest of the letter is more technical and informative while just as entertaining.  I encourage you to read it and then engage in a thought experiment in which You are the designer of an electronic exchange and must balance the needs of a very heterogeneous set of users and stakeholders while ensuring transparency, liquidity, profitability, &#8220;fairness&#8221;, performance (he references an exchange targeting 100M executions per second) and utterly fail-safe transactional integrity&#8230;</p>
<p>I have embedded the full letter below the break&#8230;</p>
<p><span id="more-944"></span></p>
<p><object style="width: 600px; height: 475px;" classid="clsid:166b1bca-3f9c-11cf-8075-444553540000" width="600" height="475" codebase="http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0"><param name="sound" value="true" /><param name="progress" value="true" /><param name="autostart" value="true" /><param name="swliveconnect" value="false" /><param name="swstretchstyle" value="meet" /><param name="swstretchhalign" value="none" /><param name="swstretchvalign" value="none" /><param name="src" value="/images/steveWunsch.pdf" /><param name="align" value="left" /><embed style="width: 600px; height: 475px;" type="application/x-director" width="600" height="475" src="/images/steveWunsch.pdf" align="left" swstretchvalign="none" swstretchhalign="none" swstretchstyle="meet" swliveconnect="false" autostart="true" progress="true" sound="true"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2010/01/17/the-sec-made-madoff/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>core arb</title>
		<link>http://www.puppetmastertrading.com/blog/2009/12/15/core-arb/</link>
		<comments>http://www.puppetmastertrading.com/blog/2009/12/15/core-arb/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 15:05:17 +0000</pubDate>
		<dc:creator>tito</dc:creator>
				<category><![CDATA[dereferenced]]></category>
		<category><![CDATA[FIX Protocol]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.puppetmastertrading.com/blog/?p=918</guid>
		<description><![CDATA[Cloud computing looks to have turned yet another interesting corner.   This time the turn leads towards the development of a liquid, fully electronic new marketplace in &#8220;spot instances&#8221;. &#8216;Spot&#8216; means what you would expect it to in the context of trading: the current pricing for immediate delivery of a commodity.  &#8216;Instance&#8216; is the atomic [...]]]></description>
			<content:encoded><![CDATA[<div class="wp-caption alignleft" style="width: 95px"><img src="/images/core.jpeg" alt="core arbitrage?" width="85" height="127" /><p class="wp-caption-text">FIX interface?</p></div>
<p>Cloud computing looks to have turned yet <a title="Amazon EC2 Spot Instances Blog post" href="http://aws.typepad.com/aws/2009/12/ec2-spot-instances-and-now-how-much-would-you-pay.html" target="_blank">another interesting corner</a>.   This time the turn leads towards the development of a liquid, fully electronic new marketplace in &#8220;spot instances&#8221;.</p>
<p>&#8216;<a title="wikipedia: spot priing" href="http://en.wikipedia.org/wiki/Spot_price" target="_blank"><em>Spot</em></a>&#8216; means what you would expect it to in the context of trading: the current pricing for immediate delivery of a commodity.  &#8216;<em>Instance</em>&#8216; is the atomic element within Amazon&#8217;s cloud environment; an instance is the smallest chunk of computing capability which can be provisioned within the cloud.</p>
<p><strong>Amazon is making markets in <em>cores</em> and they&#8217;re exposing functionality just as a regular exchange would: both through user interface &#8216;screens&#8217; as well as programmable APIs.</strong></p>
<p>From their <a title="spot instances announcement" href="http://aws.amazon.com/ec2/spot-instances/" target="_blank">announcement</a>:<strong><br />
</strong></p>
<blockquote><p>Spot Instances enable you to bid for unused Amazon <span>EC2</span> capacity.  Instances are charged the Spot Price set by Amazon <span>EC2</span>, which fluctuates periodically depending on the supply of and demand for Spot Instance capacity. To use Spot Instances, you place a Spot Instance request, specifying the instance type, the region desired, the number of Spot Instances you want to run, and the maximum price you are willing to pay per instance hour. To determine how that maximum price compares to past Spot Prices, the Spot Price history is available via the Amazon <span>EC2 API</span> and the <span>AWS</span> Management Console. If your maximum price bid exceeds the current Spot Price, your request is fulfilled and your instances will run until either you choose to terminate them or the Spot Price increases above your maximum price (whichever is sooner).</p></blockquote>
<h5>embedded optionality</h5>
<p>While the inclusion of, effectively, a market data service is neat, probably the most interesting aspect of the initial protocol they&#8217;ve designed is that it contains embedded optionality and behaves a bit like <a title="wikipedia: barrier options" href="http://en.wikipedia.org/wiki/Barrier_option" target="_blank">barrier options</a>.  That is, when I setup an &#8216;order&#8217;, I need specify a maximum price I&#8217;m willing to pay.  When the spot price drops below my max, I get &#8220;knocked-into&#8221; a contract and instances are allocated to me.  If the spot price rises above my max while I&#8217;m running, I get &#8220;knocked-out&#8221; of the contract and my jobs get terminated.</p>
<p>The intent is to allow for low-priority jobs to be dynamically run whenever pricing drops below a user&#8217;s threshold, but the (intended?) consequence is that it adds the <em>delicious and malleable tang of path dependency</em> to these instruments&#8230;</p>
<h5>secondary markets, FIX, arbitrage..?</h5>
<p>Amazon currently controls the market entirely, but it&#8217;s not hard to imagine a secondary market evolving.  Given that others are beginning to copy Amazon&#8217;s APIs, one can also imagine markets which operate across providers &#8230;  perhaps accessed via FIX?&#8230;</p>
<p>Who knows?  In the not-too-distant future, we may well be able to implement &#8216;<strong><em>core arb</em></strong>&#8216; strategies&#8230;or make markets in cores&#8230; or find that we can effectively hedge with disciplined exposure to the &#8216;core market&#8217; or &#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.puppetmastertrading.com/blog/2009/12/15/core-arb/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
