<?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>Introductory &#8211; The Financial Hacker</title>
	<atom:link href="https://financial-hacker.com/category/introduction/feed/" rel="self" type="application/rss+xml" />
	<link>https://financial-hacker.com</link>
	<description>A new view on algorithmic trading</description>
	<lastBuildDate>Sun, 11 Jan 2026 12:48:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://financial-hacker.com/wp-content/uploads/2017/07/cropped-mask-32x32.jpg</url>
	<title>Introductory &#8211; The Financial Hacker</title>
	<link>https://financial-hacker.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>&#8220;Please Send Me a Trading System!&#8221;</title>
		<link>https://financial-hacker.com/please-send-me-a-trading-system/</link>
					<comments>https://financial-hacker.com/please-send-me-a-trading-system/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Thu, 08 Oct 2020 09:26:00 +0000</pubDate>
				<category><![CDATA[3 Most Useful]]></category>
		<category><![CDATA[Introductory]]></category>
		<category><![CDATA[No Math]]></category>
		<category><![CDATA[Research]]></category>
		<category><![CDATA[System Evaluation]]></category>
		<guid isPermaLink="false">https://financial-hacker.com/?p=3565</guid>

					<description><![CDATA[&#8220;It should produce 150 pips per week. With the best EAs and indicators that you know. How much does it cost? Please also send live histories of your top systems.&#8221;  Although we often get such requests, we still don&#8217;t know the best indicators, don&#8217;t believe in best EAs, and don&#8217;t sell top systems. We do &#8230; <a href="https://financial-hacker.com/please-send-me-a-trading-system/" class="more-link">Continue reading<span class="screen-reader-text"> "&#8220;Please Send Me a Trading System!&#8221;"</span></a>]]></description>
										<content:encoded><![CDATA[
<p><em>&#8220;It should produce 150 pips per week. With the best EAs and indicators that you know. How much does it cost? Please also send live histories of your top systems.&#8221;</em> <br />
Although we often get such requests, we still don&#8217;t know the best indicators, don&#8217;t believe in best EAs, and don&#8217;t sell top systems. We do not sell algo trading systems at all, but only program them for clients after their specifications. We do not trade them, except for testing. But after programming almost 1000 systems, we can see <strong>a pattern emerging</strong>. Which trading <span style="font-size: inherit;">strategies do usually work? Which will fall apart already in the backtest? Here&#8217;s a ranking of all systems we did so far, with a surprising winner.</span><span id="more-3565"></span></p>
<p>One should think that most clients come up with very similar trading systems, so we could meanwhile just click them together from ready code. But it is not so. There&#8217;s apparently no limit of trading ideas. Almost any other system uses some new trading method, unusual data source, or exotic indicator. Still, the systems can be classified in several simple categories. Any of them has its specific success and failure rate.</p>
<h3>Trading systems categorized</h3>
<p>We classify the systems by their market and by their trading rules, both specified by the client. The 4 main markets are Forex/ CFDs, cryptocurrencies, stocks/ETFs/futures, and options. And the 4 <a href="https://zorro-project.com/algotrading.php" target="_blank" rel="noopener">main algorithmic trading methods</a> are risk premia, market models, data mining, and indicator soups.  To recap:</p>
<p><strong>Risk premium systems</strong> gain higher profits by accepting higher risks. In that category fall many stock portfolio rotation and options trading systems.</p>
<p><strong>Market model systems</strong> exploit a particular market inefficiency by detecting anomalies in price curves. Mean reversion, market cycles, market events, or statistical arbitrage are typical model based trade methods. </p>
<p><strong>Data mining systems</strong> predict a price trend by evaluating signals with a machine learning algorithm (aka &#8216;artificial intelligence&#8217;). Those signals are usually derived from the order book or the price curve, but sometimes also from fundamental data or exotic data sources.</p>
<p><strong>Indicator soups</strong> are the most often demanded systems. They do not target a particular market inefficiency, except maybe for going with the trend. They generate trade signals from a combination of traditional or new invented &#8216;technical indicators&#8217;. </p>
<p>Some algo trading systems can fall in more than one category. For instance, a <a href="https://financial-hacker.com/build-better-strategies/">grid trader</a> can be considered a risk premium system (high probability of small wins against low probability of high losses), but also a model based system (exploitation of volatility anomalies). If a system cannot be clearly assigned, it is split among several categories in the table below. We can see that clients favor some of the 16 possible combinations, while others are rare:</p>
<table style="background-color: #cadbe6; width: 100%; height: 230px;">
<tbody>
<tr style="height: 55px;">
<td style="height: 55px; width: 23.0159%;"> </td>
<td style="height: 55px; width: 18.254%;">Risk<br />
premium</td>
<td style="height: 55px; width: 14.7619%;">Market<br />
model</td>
<td style="height: 55px; width: 14.9206%;">Data<br />
mining</td>
<td style="height: 55px; width: 18.254%;">Indicator<br />
soup</td>
<td style="height: 55px; width: 10.6349%;">Sum</td>
</tr>
<tr style="height: 35px;">
<td style="height: 35px; width: 23.0159%;">Forex/CFDs</td>
<td style="height: 35px; width: 18.254%; text-align: center;">21</td>
<td style="height: 35px; width: 14.7619%; text-align: center;">74</td>
<td style="height: 35px; width: 14.9206%; text-align: center;">121</td>
<td style="height: 35px; width: 18.254%; text-align: center;">235</td>
<td style="height: 35px; width: 10.6349%; text-align: center;">451</td>
</tr>
<tr style="height: 35px;">
<td style="height: 35px; width: 23.0159%;">Crypto</td>
<td style="height: 35px; width: 18.254%; text-align: center;">0</td>
<td style="height: 35px; width: 14.7619%; text-align: center;">4</td>
<td style="height: 35px; width: 14.9206%; text-align: center;">55</td>
<td style="height: 35px; width: 18.254%; text-align: center;">40</td>
<td style="height: 35px; width: 10.6349%; text-align: center;">99</td>
</tr>
<tr style="height: 35px;">
<td style="height: 35px; width: 23.0159%;">Stocks/ETFs</td>
<td style="height: 35px; width: 18.254%; text-align: center;">68</td>
<td style="height: 35px; width: 14.7619%; text-align: center;">95</td>
<td style="height: 35px; width: 14.9206%; text-align: center;">34</td>
<td style="height: 35px; width: 18.254%; text-align: center;">14</td>
<td style="height: 35px; width: 10.6349%; text-align: center;">211</td>
</tr>
<tr style="height: 35px;">
<td style="height: 35px; width: 23.0159%;">Options</td>
<td style="height: 35px; width: 18.254%; text-align: center;">48</td>
<td style="height: 35px; width: 14.7619%; text-align: center;">159</td>
<td style="height: 35px; width: 14.9206%; text-align: center;">16</td>
<td style="height: 35px; width: 18.254%; text-align: center;">12</td>
<td style="height: 35px; width: 10.6349%; text-align: center;">235</td>
</tr>
<tr style="height: 35px;">
<td style="height: 35px; width: 23.0159%;">Sum</td>
<td style="height: 35px; width: 18.254%; text-align: center;">137</td>
<td style="height: 35px; width: 14.7619%; text-align: center;">332</td>
<td style="height: 35px; width: 14.9206%; text-align: center;">226</td>
<td style="height: 35px; width: 18.254%; text-align: center;">301</td>
<td style="height: 35px; width: 10.6349%; text-align: center;">996</td>
</tr>
</tbody>
</table>
<p>For determining the success or failure rate, we used 8-years backtests for unoptimized systems, and a walk forward analysis for optimized systems. A successful system had to return at least 12% CAGR for stocks, futures, or options, or 30% annual profit for Forex, CFDs, or cryptocurrencies. The R2 parameter had to be above 0.7. If clients ordered a <a href="https://zorro-project.com/backtest.php" target="_blank" rel="noopener">Montecarlo analysis</a>, the system had to pass it at 95% confidence. If one of those conditions was not fulfilled, the system was classified as failure. </p>
<p>The percentages of successful systems:</p>
<table class=" alignleft" style="height: 230px; background-color: #cadbe6; width: 100%;" border="0" width="100%" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 15.0pt;">
<td class="xl65" style="height: 50px; width: 23.0159%;" width="80" height="40"> </td>
<td class="xl65" style="width: 14.7619%; height: 35px;" width="80">Risk<br />
premium</td>
<td class="xl65" style="width: 15.0794%; height: 35px;" width="80">Market<br />
model</td>
<td class="xl65" style="width: 15.0794%; height: 35px;" width="80">Data<br />
mining</td>
<td class="xl65" style="width: 16.6667%; height: 35px;" width="80">Indicator<br />
soup</td>
<td class="xl66" style="width: 15.2381%; height: 50px;" width="80">Success<br />
rate</td>
</tr>
<tr style="height: 15.0pt;">
<td class="xl65" style="height: 15px; width: 23.0159%;" width="80" height="20">Forex/CFDs</td>
<td class="xl65" style="width: 14.7619%; height: 15px; text-align: center;" align="right" width="80">88 %</td>
<td class="xl65" style="width: 15.0794%; height: 15px; text-align: center;" align="right" width="80">81 %</td>
<td class="xl65" style="width: 15.0794%; height: 15px; text-align: center;" align="right" width="80">69 %</td>
<td class="xl65" style="width: 16.6667%; height: 15px; background-color: #ff0000; text-align: center;" align="right" width="80">31 %</td>
<td class="xl66" style="width: 15.2381%; height: 15px; text-align: center;" align="right" width="80">52 %</td>
</tr>
<tr style="height: 15.0pt;">
<td class="xl65" style="height: 15px; width: 23.0159%;" width="80" height="20">Crypto</td>
<td class="xl65" style="width: 14.7619%; height: 15px; text-align: center;" align="right" width="80">0 %</td>
<td class="xl65" style="width: 15.0794%; height: 15px; text-align: center;" align="right" width="80">75 %</td>
<td class="xl65" style="width: 15.0794%; height: 15px; text-align: center;" align="right" width="80">62 %</td>
<td class="xl65" style="width: 16.6667%; height: 15px; background-color: #ff0000; text-align: center;" align="right" width="80">25 %</td>
<td class="xl66" style="width: 15.2381%; height: 15px; text-align: center;" align="right" width="80">49 %</td>
</tr>
<tr style="height: 15.0pt;">
<td class="xl65" style="height: 15px; width: 23.0159%;" width="80" height="20">Stocks/ETFs</td>
<td class="xl65" style="width: 14.7619%; height: 15px; background-color: #00ff00; text-align: center;" align="right" width="80">92 %</td>
<td class="xl65" style="width: 15.0794%; height: 15px; text-align: center;" align="right" width="80">85 %</td>
<td class="xl65" style="width: 15.0794%; height: 15px; text-align: center;" align="right" width="80">61 %</td>
<td class="xl65" style="width: 16.6667%; height: 15px; text-align: center;" align="right" width="80">35 %</td>
<td class="xl66" style="width: 15.2381%; height: 15px; text-align: center;" align="right" width="80">80 %</td>
</tr>
<tr style="height: 15.0pt;">
<td class="xl65" style="height: 15px; width: 23.0159%;" width="80" height="20">Options</td>
<td class="xl65" style="width: 14.7619%; height: 15px; background-color: #00ff00; text-align: center;" align="right" width="80">96 %</td>
<td class="xl65" style="width: 15.0794%; height: 15px; background-color: #00ff00; text-align: center;" align="right" width="80">91 %</td>
<td class="xl65" style="width: 15.0794%; height: 15px; text-align: center;" align="right" width="80">75 %</td>
<td class="xl65" style="width: 16.6667%; height: 15px; text-align: center;" align="right" width="80">58 %</td>
<td class="xl66" style="width: 15.2381%; height: 15px; text-align: center;" align="right" width="80">89 %</td>
</tr>
<tr style="height: 15.0pt;">
<td class="xl66" style="height: 15px; width: 23.0159%;" width="80" height="20">Success rate</td>
<td class="xl66" style="width: 14.7619%; height: 15px; text-align: center;" align="right" width="80">93 %</td>
<td class="xl66" style="width: 15.0794%; height: 15px; text-align: center;" align="right" width="80">87 %</td>
<td class="xl66" style="width: 15.0794%; height: 15px; text-align: center;" align="right" width="80">67 %</td>
<td class="xl66" style="width: 16.6667%; height: 15px; text-align: center;" align="right" width="80">32 %</td>
<td class="xl66" style="width: 15.2381%; height: 15px; text-align: center;" align="right" width="80">66 %</td>
</tr>
</tbody>
</table>
<p> The average success rates at the end of the columns and rows are weighted by the number of systems. We can see that the overall success rate was only 66%. In 34% of cases we had to break the bad news to the client that it&#8217;s not advised to trade this system live. It produced no, or too little profit in the tests. Sometimes we could see what the problem was, and suggest ways to improve the system. But even total failures were no wasted money. When you know that your favorite manually traded system won&#8217;t work in the long run, you&#8217;ll save a lot more money than spent for programming and testing. </p>
<h3>And the winner is&#8230;</h3>
<p>The statistics are spoiled by the forex and crypto systems, half of which were losers. This is at least better than most such systems from trading books or trader forums, of which 90% fail already in a simple out-of-sample test, or at least in a cluster or Montecarlo analysis. We got a surprising result in the &#8216;Indicator soup&#8217; systems. You would normally expect that they all fail big time, since they are not based on a market model. But in fact almost every third indicator hodgepodge was successful, even in live trading on a test server. Maybe the clients knew more than we did. </p>
<p>It is also a bit surprising that the most complex systems of all, the data mining systems that usually employ deep learning algorithms, did not fare much better. They have an acceptable success rate, but are easily surpassed by a certain sort of much simpler systems. </p>
<p>Of all systems we tested so far, the big winners were the long-term trading systems for <strong>stocks</strong>, <strong>ETFs</strong>, or <strong>options</strong>. Of the option traders, the simpler systems had often better performance. It&#8217;s relatively hard to specify a losing option system, but some still managed it by using short expiration dates, complex entries, fancy rollovers, or intraday buying and selling. One of the very simple, but successful option traders was included in the Zorro scripts.</p>
<p>We found another trend that is not visible in the table: With a few exceptions like HFT or arbitrage, there was an almost linear correlation between <strong>time frames</strong> and performances. Systems on one, five, or ten minute bars were rarely profitable. The good systems traded mostly on 1-hour, 4-hour, or 24-hour time frames. Faster is not always better.</p>
<p>This does not mean that we all should now abandon forex and cryptos and trade only long-term options or ETF portfolios. Diversification is a key to success. All markets still have long periods of ineffectivity and plenty opportunities of trading profits. Maybe the statistics above help to look for them. </p>
<p><strong>Update (2025):</strong> This article was posted 5 years ago, and we have meanwhile more than 2000 systems programmed for clients. Due to technical progress especially with machine learning systems the overall success rate is now slightly better at 71%. But the success relations between the various trading methods are still the same.</p>
<h3>Related articles</h3>
<p><strong>⇒ </strong><a href="https://financial-hacker.com/i-hired-a-contract-coder/">I Hired a Contract Coder</a></p>
<p><strong>⇒ </strong><a href="https://financial-hacker.com/build-better-strategies/">Build Better Strategies!</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/please-send-me-a-trading-system/feed/</wfw:commentRss>
			<slash:comments>32</slash:comments>
		
		
			</item>
		<item>
		<title>Algorithmic Options Trading 3</title>
		<link>https://financial-hacker.com/algorithmic-options-trading-part-3/</link>
					<comments>https://financial-hacker.com/algorithmic-options-trading-part-3/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Sun, 26 Nov 2017 07:59:48 +0000</pubDate>
				<category><![CDATA[Introductory]]></category>
		<category><![CDATA[No Math]]></category>
		<category><![CDATA[System Development]]></category>
		<category><![CDATA[Call]]></category>
		<category><![CDATA[Earnings]]></category>
		<category><![CDATA[ETF]]></category>
		<category><![CDATA[Options]]></category>
		<category><![CDATA[Put]]></category>
		<category><![CDATA[SPY]]></category>
		<category><![CDATA[Strangle]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=2718</guid>

					<description><![CDATA[In this article we&#8217;ll look into a real options trading strategy, like the strategies that we code for clients. This one however is based on a system from a trading book. As mentioned before, options trading books often contain systems that really work &#8211; which can not be said about day trading or forex trading &#8230; <a href="https://financial-hacker.com/algorithmic-options-trading-part-3/" class="more-link">Continue reading<span class="screen-reader-text"> "Algorithmic Options Trading 3"</span></a>]]></description>
										<content:encoded><![CDATA[<p>In this article we&#8217;ll look into a real options trading strategy, like the strategies that we code for clients. This one however is based on a system from a trading book. As mentioned before, options trading books often contain systems that <strong>really work</strong> &#8211; which can not be said about day trading or forex trading books. The system examined here is indeed able to produce profits. Which is not surprising, since it apparently <strong>never loses</strong>. But it is also obvious that its author has never backtested it. <span id="more-2718"></span></p>
<p>To clarify: I&#8217;ve selected the system not because of high profit expectancy or clever algorithm, but because it is quite simple and does not need any of the additional data normally used for option systems, such as earnings reports, open interest, implied volatility, or greeks. Which means that you don&#8217;t need to call R functions for options math, and you don&#8217;t need to pay for iVolatility options data, Zacks earnings, or any other historical data for backtesting the system. The free <a href="http://www.financial-hacker.com/hackers-tools-zorro-and-r/" target="_blank" rel="noopener">Zorro</a> version is sufficient.</p>
<p>The book cover praises the system inside:  <strong><em>To reduce your investment risk to nearly zero &#8211; Achieve consistent high annual returns in excess of 30% &#8211; It does not require you to learn fundamental and technical analyzes, deltas, thetas, gamas, vegas or other Greek goblethegooks of stocks or options  &#8211; It does not require the ability to predict market direction &#8211; It does not require stock picking skills &#8211; It does not require close monitoring</em></strong>.</p>
<p>All statements with which I, of course, highly sympathize. After all, why would we need Greek goblethegooks when we get annual 30% without them! And here are the (simplified) rules of our strategy:</p>
<ol>
<li>Sell a 6 weeks call and a 6 weeks put of an index ETF. Choose strike prices so that the premiums are in the $1..$2 range.</li>
<li>If the underlying price touches one of our strike prices, thus threatening an <a href="http://www.financial-hacker.com/algorithmic-options-trading/" target="_blank" rel="noopener">in-the-money</a> expiration, buy back that option and immediately sell a new option of the same type, but to a further expiration date, and a premium that covers the loss.</li>
<li>Wait until all options are expired, then go back to 1.</li>
</ol>
<p>If you have a bit experience with options, you&#8217;ll notice that rule 1 describes a <strong>strangle</strong> combo. And you&#8217;ll next notice something strange with rule 2. Right, such a system can never lose, since any loss would apparently be compensated by the premium from the new trade. Have we finally found the <a href="http://www.financial-hacker.com/seventeen-popular-trade-strategies-that-i-dont-really-understand/" target="_blank" rel="noopener">Holy Grail</a>, an ever-winning system? </p>
<h3>Strangle profit</h3>
<p>For getting an impression of the profit and risk, let&#8217;s first check the gain/loss diagram of the 6-week $2 premium strangle. This is the definition of a strangle in the curve plotting script from the <a href="http://www.financial-hacker.com/algorithmic-options-trading-2/" target="_blank" rel="noopener">last article</a>:</p>
<pre class="prettyprint">// Strangle
void combo()
{
	optionAdd(1,SELL|CALL,6);
	optionAdd(1,SELL|PUT,-6);
}</pre>
<p>The $6 strike-spot distances have been chosen for $2 premium from a hypothetical index ETF with $250 price, multiplier 100, and 15% annual volatility. This is the profit/loss diagram:</p>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2018/08/OptionsCurve_EURUSD_s.png"><img fetchpriority="high" decoding="async" class="alignnone wp-image-2841 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2018/08/OptionsCurve_EURUSD_s.png" alt="" width="742" height="481" srcset="https://financial-hacker.com/wp-content/uploads/2018/08/OptionsCurve_EURUSD_s.png 742w, https://financial-hacker.com/wp-content/uploads/2018/08/OptionsCurve_EURUSD_s-300x194.png 300w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a></p>
<p>Our potential gain is about $400 per combo trade, as expected (2 * 100 * $2 premium). But the price of our index ETF should better not move more than $10 in any direction until expiration. Otherwise the loss can quickly reach the thousand dollar zone. This does not really look like &#8220;reduce your investment risk to nearly zero&#8221;. But wait, we have rule 2, which will certainly save the day! Let&#8217;s put that to the backtest. </p>
<h3>The system</h3>
<pre class="prettyprint">// Quite simple options trading system 
#include &lt;contract.c&gt;

#define PREMIUM	2.00
#define WEEKS	6    // expiration

int i;
var Price;

CONTRACT* findCall(int Expiry,var Premium)
{
	for(i=0; i&lt;50; i++) {
		if(!contract(CALL,Expiry,Price+0.5*i)) return 0;
		if(between(ContractBid,0.1,Premium)) return ThisContract;
	}
	return 0;
}

CONTRACT* findPut(int Expiry,var Premium)
{
	for(i=0; i&lt;50; i++) {
		if(!contract(PUT,Expiry,Price-0.5*i)) return 0;
		if(between(ContractBid,0.1,Premium)) return ThisContract;
	}
	return 0;
}

void run() 
{
	StartDate = 20110101;
	EndDate = 20161231;
	BarPeriod = 1440;
	BarZone = ET;
	BarOffset = 15*60+20; // trade at 15:20 ET
	LookBack = 1;

	assetList("AssetsIB");
	asset("SPY"); // unadjusted!
	Multiplier = 100;

// load today's contract chain
	contractUpdate("SPY",0,CALL|PUT);
	Price = priceClose(); 

// check for in-the-money and roll 	
	for(open_trades) {
		var Loss = -TradeProfit/Multiplier;
		if(TradeIsCall &amp;&amp; Price &gt;= TradeStrike) {
			exitTrade(ThisTrade);
			printf("#\nRoll %.1f at %.2f Loss %.2f",
				TradeStrike,Price,TradeProfit);
			CONTRACT* C = findCall(NWEEKS*7,Loss*1.1);
			if(C) {
				MarginCost = 0.15*Price - (C-&gt;fStrike-Price);
				enterShort();
			}
		} else if(TradeIsPut &amp;&amp; Price &lt;= TradeStrike) {
			exitTrade(ThisTrade);
			printf("#\nRoll %.1f at %.2f Loss %.2f",
				TradeStrike,Price,TradeProfit);
			CONTRACT* C = findPut(NWEEKS*7,Loss*1.1);
			if(C) { 
				MarginCost = 0.15*Price - (Price-C-&gt;fStrike);
				enterShort();
			}
		}
	}
	
// all expired? enter new options
	if(!NumOpenShort) { 
		CONTRACT *Call = findCall(NWEEKS*7,PREMIUM); 
		CONTRACT *Put = findPut(NWEEKS*7,PREMIUM); 		
		if(Call &amp;&amp; Put) {
			MarginCost = 0.5*(0.15*Price-
				min(Call-&gt;fStrike-Price,Price-Put-&gt;fStrike));
			contract(Call); enterShort();
			contract(Put); enterShort();
		}
	}
}</pre>
<p>A brief discussion of the code (a more detailed intro in system coding can be found in the Black Book). The <strong>findCall</strong> function gets an expiration time and a premium, and looks through the current option chain for a call contract that matches these two parameters. For this it increases the strike price in 50 steps. If then still no contract is found at or below the desired premium, it returns 0. Otherwise it returns a pointer to the found contract. The <strong>findPut</strong> function does the same for a put contract.</p>
<p>The <strong>run</strong> function sets up the backtest time and other parameters for the backtest as well as for live trading. It&#8217;s a daily script, and the function runs every day at 3:20 pm Eastern Time. It uses two historical data files for the backtest. The <strong>asset</strong> function loads a file with the unadjusted SPY prices (why unadjusted? Because determining the strikes-price distances would not work with dividend adjusted prices). The <strong>contractUpdate</strong> function loads the SPY options chain of that day, either from the broker, or from a file.  Those two files must be present, plus the asset list <strong>AssetsIB.csv</strong> that contains commission, margin, and other parameters for simulating the broker or exchange where we trade.</p>
<p>The next part of the code implements the miraculous rule 2. It calculates the current loss, closes any position that is at or in the money, and immediately opens a new position, with a premium slightly above our loss (<strong>Loss*1.1</strong>). This way we&#8217;re punishing the market for going against us. The <strong>printf</strong> function just stores that event in the log, so that we can go through it and better see the fate of those trades.</p>
<p>The last part of the code is the strangle. Note the <strong>MarginCost</strong> calculation. Margin affects the required capital and thus the backtest performance, so it should reflect your broker&#8217;s margin requirement. By default, the margin of a sold option is the premium plus some fixed percentage of the underlying that&#8217;s set up in the asset list. But brokers often apply a more complex margin formula for option combos. Here we assume that the margin of a sold strangle is the premium (which is automatically added) plus 15% of the underlying price minus the minimum of the two strike differences. We multiply that by half because we have 2 positions, but the margin formula is for the whole strangle.</p>
<p>The backtest from 2011-2016 needs only about 2 seconds. This is the result (assuming we always open 1 contract):</p>
<pre class="prettyprint">Monte Carlo Analysis... Median AR 12%
Win 3699$  MI 51.38$  DD 935$  Capital 5108$
Trades 93  Win 59.1%  Avg +39.8p  Bars 24
AR 12%  PF 1.84  SR 1.08  UI 5%  R2 0.89</pre>
<p>We have won about 60% of all trades, and made 12% annual return based on Montecarlo analysis.  Not too exciting. What about the &#8220;consistent high annual returns in excess of 30%&#8221;? And how can we get a $935 drawdown when we always compensate our loss with a new trade?</p>
<h3>Is rolling over irrational?</h3>
<p>Let&#8217;s try the same strategy without the rule 2. This simplifies the script a bit:</p>
<pre class="prettyprint">// Even simpler options trading system 
#include &lt;contract.c&gt;

#define PREMIUM	2.00
#define WEEKS	6 // expiration

int i;
var Price;

CONTRACT* findCall(int Expiry,var Premium)
{
	for(i=0; i&lt;50; i++) {
		if(!contract(CALL,Expiry,Price+0.5*i)) return 0;
		if(between(ContractBid,0.1,Premium)) return ThisContract;
	}
	return 0;
}

CONTRACT* findPut(int Expiry,var Premium)
{
	for(i=0; i&lt;50; i++) {
		if(!contract(PUT,Expiry,Price-0.5*i)) return 0;
		if(between(ContractBid,0.1,Premium)) return ThisContract;
	}
	return 0;
}

void run() 
{
	StartDate = 20110101;
	EndDate = 20161231;
	BarPeriod = 1440;
	BarZone = ET;
	BarOffset = 15*60+20; // trade at 15:20 ET
	LookBack = 1;
	set(PLOTNOW);
	set(PRELOAD|LOGFILE);

	assetList("AssetsIB");
	asset("SPY"); // unadjusted!
	Multiplier = 100;

// load today's contract chain
	Price = priceClose();
	contractUpdate("SPY",0,CALL|PUT);

// all expired? enter new options
	if(!NumOpenShort) { 
		CONTRACT *Call = findCall(WEEKS*7,PREMIUM); 
		CONTRACT *Put = findPut(WEEKS*7,PREMIUM); 		
		if(Call &amp;&amp; Put) {
			MarginCost = 0.5*(0.15*Price-min(Call-&gt;fStrike-Price,Price-Put-&gt;fStrike));
			contract(Call); enterShort();
			contract(Put); enterShort();
		}
	}
}</pre>
<p>Simply removing the rolling over improved the system remarkably:</p>
<pre class="prettyprint">Monte Carlo Analysis... Median AR 25%
Win 5576$  MI 77.46$  DD 785$  Capital 3388$
Trades 78  Win 80.8%  Avg +71.5p  Bars 35
AR 27%  PF 2.00  SR 0.92  UI 5%  R2 0.92</pre>
<p>The equity curve with no rolling:</p>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2018/08/Options32_SPY.png"><img decoding="async" class="alignnone wp-image-2844 size-large" src="http://www.financial-hacker.com/wp-content/uploads/2018/08/Options32_SPY-1024x329.png" alt="" width="840" height="270" srcset="https://financial-hacker.com/wp-content/uploads/2018/08/Options32_SPY-1024x329.png 1024w, https://financial-hacker.com/wp-content/uploads/2018/08/Options32_SPY-300x96.png 300w, https://financial-hacker.com/wp-content/uploads/2018/08/Options32_SPY-768x247.png 768w, https://financial-hacker.com/wp-content/uploads/2018/08/Options32_SPY-1200x386.png 1200w, https://financial-hacker.com/wp-content/uploads/2018/08/Options32_SPY.png 1497w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a></p>
<p>Now the 25% annual return are somewhat closer to the promised profit. Of course at cost of higher risk, since no limiting mechanism is in place. We could now test other option combos instead of the strangle, for instance a <strong>condor</strong> for limiting the risk. We can run an optimization for finding out how the profit is affected by different premiums and expirations. I leave that to the reader. The interesting question is why rolling over options, not only with this, but with many option trading systems that we have coded so far, reduces the performance remarkably. Often to the client&#8217;s great surprise.</p>
<p>Rolling over with loss compensation establishes in fact a <a href="http://www.financial-hacker.com/seventeen-popular-trade-strategies-that-i-dont-really-understand/" target="_blank" rel="noopener">Martingale system</a>. And such a system fares no better in option trading than in the casino. In fact, even worse. In the casino you have at least the same chance with every play. In trading, a losing option combo hints that the market starts trending &#8211; and the trend is likely to continue with the rolled over contract. Quite soon you cannot anymore compensate your losses with higher premiums, since you&#8217;ll find no contracts at that value. Ok, you could then start increasing the contract volume. If you really did that, you can calculate under the link above how long your account will survive. Rolling over a losing contract is typical irrational human behavior &#8211;  but the markets tend to punish irrationality.</p>
<h3>Artificial options data</h3>
<p>Since the system does not rely on goblethegooks, we can check whether the artificial options data that we created in the <a href="http://www.financial-hacker.com/algorithmic-options-trading/" target="_blank" rel="noopener">first part</a> of this mini series can be used for testing this system. The backtest results above were with real options data. Here&#8217;s the result with the synthetic data:</p>
<pre class="prettyprint">Monte Carlo Analysis... Median AR 31%
Win 7162$  MI 99.49$  DD 1188$  Capital 3866$
Trades 88  Win 81.8%  Avg +81.4p  Bars 30
AR 31%  PF 2.36  SR 1.12  UI 4%  R2 0.88
</pre>
<p>It&#8217;s similar, but not quite identical to the real data. Artificial data represents a more efficient market situation, since its option premiums are identical to their theoretical values, and fundamentals such as earnings reports play no role. You can use it for confirming the real data backtest. Or for saving money, by backtesting a non-goblethegooks system (yes, I like this word) first with artifical data, and only if it looks good, purchasing real data for the final test.</p>
<p>I&#8217;ve added the full script to the 2017 repository. You&#8217;ll need Zorro version 1.73 or above. You can find the unadjusted SPY data in the History folder of the archive (alternatively, download it with the Zorro command <strong>assetHistory( &#8220;SPY.US&#8221;, FROM_STOOQ | UNADJUSTED)</strong>). If you don&#8217;t want to create the artificial 2011-2016 options history yourself, you can download it from the historical data archives <a href="http://zorro-project.com/download.php" target="_blank" rel="noopener">here</a>. </p>
<h3>Conclusions</h3>
<ul style="list-style-type: square;">
<li>Mind the margin cost in backtests.</li>
<li>Do not roll over losing contracts.</li>
<li>If your system has no goblethegooks, try artificial data.</li>
</ul>
<h3>Literature</h3>
<p>(1) is the book from which I pulled the system. The book is ok &#8211; not better or worse than most other options books, but at only $10, getting it is no mistake. <br />
(2) is a really good introduction into the options trading matter. Even though its author shamelessly plagiarized the title of my blog, and this even years before I started writing it!</p>
<p><strong>(1) Daniel Mollat, $tock option$, BN Publishing 2011<br />
</strong><strong>(2) Philip Z Maymin, Financial Hacking, Wspc 2012</strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/algorithmic-options-trading-part-3/feed/</wfw:commentRss>
			<slash:comments>46</slash:comments>
		
		
			</item>
		<item>
		<title>Algorithmic Options Trading 2</title>
		<link>https://financial-hacker.com/algorithmic-options-trading-2/</link>
					<comments>https://financial-hacker.com/algorithmic-options-trading-2/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Sat, 17 Jun 2017 23:00:22 +0000</pubDate>
				<category><![CDATA[Introductory]]></category>
		<category><![CDATA[System Development]]></category>
		<category><![CDATA[Binary options]]></category>
		<category><![CDATA[Black-Scholes Formula]]></category>
		<category><![CDATA[Butterfly]]></category>
		<category><![CDATA[Call]]></category>
		<category><![CDATA[Condor]]></category>
		<category><![CDATA[Options]]></category>
		<category><![CDATA[Profit diagram]]></category>
		<category><![CDATA[Put]]></category>
		<category><![CDATA[Strangle]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=2298</guid>

					<description><![CDATA[In this second part of the Algorithmic Options trading series we&#8217;ll look more closely into option returns. Especially into combining different option types for getting user-tailored profit and risk curves. Option traders know combinations with funny names like &#8220;Iron Condor&#8221; or &#8220;Butterfly&#8221;, but you&#8217;re not limited to them. With some tricks you can create artificial &#8230; <a href="https://financial-hacker.com/algorithmic-options-trading-2/" class="more-link">Continue reading<span class="screen-reader-text"> "Algorithmic Options Trading 2"</span></a>]]></description>
										<content:encoded><![CDATA[<p>In this second part of the <a href="http://www.financial-hacker.com/algorithmic-options-trading/">Algorithmic Options trading</a> series we&#8217;ll look more closely into option returns. Especially into combining different option types for getting user-tailored profit and risk curves. Option traders know combinations with funny names like &#8220;Iron Condor&#8221; or &#8220;Butterfly&#8221;, but you&#8217;re not limited to them. With some tricks you can create artificial financial instruments of any desired property &#8211; for instance &#8220;<a href="http://www.financial-hacker.com/binary-options-scam-or-opportunity/" target="_blank" rel="noopener">Binary Options</a>&#8221; with more than 100% payout factor.<span id="more-2298"></span></p>
<p>The <strong>profit diagram</strong> of an option is its profit or loss at or before expiration in dependence of the price of the underlying. Let&#8217;s assume that we know that the price of a certain asset will rise in the next months. So we buy a call option on that asset. Our profit diagram then looks like this:</p>
<p><figure id="attachment_2488" aria-describedby="caption-attachment-2488" style="width: 423px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s.png"><img decoding="async" class="wp-image-2488" src="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s.png" alt="" width="423" height="257" srcset="https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s.png 846w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s-300x182.png 300w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s-768x466.png 768w" sizes="(max-width: 423px) 85vw, 423px" /></a><figcaption id="caption-attachment-2488" class="wp-caption-text">AAPL call at strike 144</figcaption></figure></p>
<p>This is the potential return when buying a current (June 2017) AAPL call option with 4 months expiration time. We have to pay $668 premium for that option. The current AAPL price is $144, and that&#8217;s also our strike price. The blue line is our profit or loss, dependent on the AAPL price at expiration. The option will expire out of the money when AAPL stays below $144, so we&#8217;ll then lose the premium. We&#8217;ll still lose a part of the premium if the option expires only slightly in the money. The break even point is at about $151. And if AAPL floats even higher at expiration time, we can collect huge profits of a multiple of the premium. So buying a call option means an unlimited profit chance at a limited risk. You can not lose more than the premium.</p>
<p>The green line in the diagram is the theoretical option value after 2 months, at half the expiration time. It is approximated with a finite difference method or calculated with the Black-Scholes formula, dependent on option type. The real option price is normally close to that theoretical value. So we can see that we could already sell the option with a profit after two months when the AAPL price is then above $148.</p>
<p>By the way, this option profit diagram resembles the response function of a Rectified Linear Unit in a <a href="http://www.financial-hacker.com/build-better-strategies-part-5-developing-a-machine-learning-system/" target="_blank" rel="noopener">neural network</a>. So we can speculate that when a billion option traders permanently sell and buy large numbers of options, when the underlying price depends on option demand, and when profits are always reinvested in new options, the option market becomes a huge neural net. Some day artificial intelligence might emerge and the options start buying and selling themselves&#8230;</p>
<h3>Option combos</h3>
<p>Now let&#8217;s assume we know for sure that the AAPL price will move in the next time, but we do not know if it will rise or fall. For making profit in both cases, we just buy a call and a put option, both with the strike at the current price of $144:</p>
<p><figure id="attachment_2490" aria-describedby="caption-attachment-2490" style="width: 423px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s3.png"><img loading="lazy" decoding="async" class="wp-image-2490" src="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s3.png" alt="" width="423" height="257" srcset="https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s3.png 846w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s3-300x182.png 300w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s3-768x466.png 768w" sizes="auto, (max-width: 423px) 85vw, 423px" /></a><figcaption id="caption-attachment-2490" class="wp-caption-text">1 call at 144 + 1 put at 144</figcaption></figure></p>
<p>We can see that a call and a put option with the same parameters don&#8217;t cancel out each other! The resulting profit diagram is just the sum of the profit diagrams of the single options. For both options we have to pay a $1310 total premium. If the AAPL price stays inside the $131 &#8211; $157 range, we lose. If it ends up outside this range, we win. If it ends up outside by a wide margin, we win big.</p>
<p>Now suppose we think an asset won&#8217;t be very volatile in the next time and its price will stay inside a range. We&#8217;ll then sell the two options instead of buying them. Selling instead of buying just turns the above profit diagram upside down. And we can already see the problem with that: The profit is now limited and the risk unlimited.</p>
<p>For fixing this, we need to add some more options to the combination:</p>
<p><figure id="attachment_2493" aria-describedby="caption-attachment-2493" style="width: 423px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s4.png"><img loading="lazy" decoding="async" class="wp-image-2493" src="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s4.png" alt="" width="423" height="257" srcset="https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s4.png 846w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s4-300x182.png 300w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s4-768x466.png 768w" sizes="auto, (max-width: 423px) 85vw, 423px" /></a><figcaption id="caption-attachment-2493" class="wp-caption-text">1 call at 139 + 1 call at 149 &#8211; 2 calls at 144</figcaption></figure></p>
<p>For this profit diagram we&#8217;ve used 4 options. We bought one call at a strike $5 below the current price, another call at a strike $5 above the current price, and we sold short two calls with the strike at the current price. For the two long options we paid $1400 premium, and for the two short options we got $1340. This leaves us with $60 total premium cost, and a chance of up to $440 profit when the price stays inside the $140 &#8211; $148 range. This option combo, for whatever reason, got the name &#8220;Long Butterfly&#8221; by option traders.</p>
<p>By the way, you can see from this butterfly that you can really produce any profit diagram with a suited combination of options. The position of the butterfly peak is determined by the strike prices, its width by their distance, its height by the number of options. This way, many different butterfly peaks can be theoretically put together to a profit diagram of any shape. Unfortunately, you cannot just as freely determine its vertical position &#8211; a part of the diagram will be always below the zero line&#8230;</p>
<h3>The code</h3>
<p>Here&#8217;s a small C script (for <a href="http://www.financial-hacker.com/hackers-tools-zorro-and-r/" target="_blank" rel="noopener">Zorro</a>) for experiments with all sorts of option combinations:</p>
<pre class="prettyprint">#include &lt;contract.c&gt;
void optionAdd(int Num,int Type,var StrikeOffs);

#define ASSET     "AAPL"
#define EXPIRY	  120	// 4 months
#define BUY	(1&lt;&lt;10)
#define SELL	(1&lt;&lt;11)

void combo() // "Butterfly"
{
	optionAdd(1,BUY|CALL,-5);  
	optionAdd(2,SELL|CALL,0);
	optionAdd(1,BUY|CALL,5);
}

//////////////////////////////////////////////////
#define POINTS 100 
var OptionGains[POINTS],OptionVals50[POINTS];
var UnderL,HistVol;

void optionPlot(int Num,CONTRACT* C,var Premium,var RangeMin,var RangeMax) 
{
	PlotScale = 10;
	var Step = (RangeMax-RangeMin)/POINTS;
	Step = round(Step+0.5,1); // round up
	RangeMin = round(RangeMin,1);

	int i;
	for(i=0; i&lt;POINTS; i++)
	{
		if(Num == 0) {
			OptionGains[i] = OptionVals50[i] = 0;
		} else {
			var Price = RangeMin + i*Step;
			if(Price &gt; RangeMax) break;
			var Gain = 0;
			var Strike = C-&gt;fStrike; 
			var Val50 = contractVal(C,Price,HistVol,0,0);
			switch(C-&gt;Type&amp;(BUY|SELL|CALL|PUT)) {
				case BUY|CALL: 
					if(Price &gt; Strike) Gain = Price - Strike;
					Gain -= Premium;
					Val50 -= Premium;
					break;
				case BUY|PUT: 
					if(Price &lt; Strike) Gain = Strike - Price;
					Gain -= Premium;
					Val50 -= Premium;
					break;
				case SELL|CALL: 
					if(Price &gt; Strike) Gain = Strike - Price;
					Gain += Premium;
					Val50 = Premium - Val50;
					break;
				case SELL|PUT: 
					if(Price &lt; Strike) Gain = Price - Strike;
					Gain += Premium;
					Val50 = Premium - Val50;
					break;
			}
			OptionGains[i] += Multiplier*Num*Gain;
			OptionVals50[i] += Multiplier*Num*Val50;
			plotBar("Zero",i,0,0,LINE,BLACK);
			plotBar("ValueAt50%",i,Price,OptionVals50[i],LINE|LBL2,GREEN);
			plotBar("ValueAtExpiry",i,Price,OptionGains[i],LINE|LBL2,BLUE);
		}
	}
}

void optionAdd(int Num,int Type,var StrikeOffs)
{
	CONTRACT C;
	C.Type = Type;
	C.Expiry = EXPIRY;
	C.fStrike = round(UnderL+StrikeOffs,1);
	var Premium = contractVal(&amp;C,UnderL,HistVol,0,0);
	C.Expiry = EXPIRY*0.5; // for the value at 50% expiration 
	optionPlot(Num,&amp;C,Premium,0.8*UnderL,1.2*UnderL);
}

void run() 
{
	BarPeriod = 1440;
	StartDate = NOW;
	set(PRELOAD);
	if(is(INITRUN)) {
		initRQL();
		assetAdd(ASSET);
		assetHistory(ASSET,FROM_GOOGLE);
		asset(ASSET);
	}
	vars Close = series(priceClose());
	HistVol = Volatility(Close,20);
	UnderL = Close[0];
	Multiplier = 100;

	if(!is(LOOKBACK)) 
	{
		optionAdd(0,0,0); // reset the graphs
		combo();
		quit("Ok!");
	}
}</pre>
<p>This script plots the above diagrams. The core of the script is the <strong>combo()</strong> function at the begin. It contains one or several <strong>optionAdd</strong> calls that get as parameters the number of options, the type (BUY, SELL, CALL, PUT, EUROPEAN, BINARY), and the strike difference to the current price. In the example above you can see the combination for the long butterfly. The asset and expiration can be set up in the <strong>#define</strong> lines above. The script downloads the current asset prices from Google and calculates the volatility that is needed for getting the options values and premiums. For running it you need Zorro, R, and the <strong>RQuantLib</strong> package from <a href="https://cran.r-project.org/bin/windows/contrib/3.3/RQuantLib_0.4.2.zip" target="_blank" rel="noopener">https://cran.r-project.org/bin/windows/contrib/3.3/RQuantLib_0.4.2.zip</a>.</p>
<p>Some more examples of popular option combos:</p>
<pre class="prettyprint">// Call Spread
void combo()
{
	optionAdd(1, BUY|CALL, -5);
	optionAdd(1, SELL|CALL, 5);
}</pre>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s5.png"><img loading="lazy" decoding="async" class="alignnone wp-image-2502" src="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s5.png" alt="" width="423" height="257" srcset="https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s5.png 846w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s5-300x182.png 300w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s5-768x466.png 768w" sizes="auto, (max-width: 423px) 85vw, 423px" /></a></p>
<pre class="prettyprint">// Put Spread
void combo()
{
	optionAdd(1, BUY|PUT, 5);
	optionAdd(1, SELL|PUT, -5);
}</pre>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s6.png"><img loading="lazy" decoding="async" class="alignnone wp-image-2503" src="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s6.png" alt="" width="423" height="257" srcset="https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s6.png 846w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s6-300x182.png 300w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s6-768x466.png 768w" sizes="auto, (max-width: 423px) 85vw, 423px" /></a></p>
<p>Call or Put Spreads limit our risk as well as our profit to a fixed amount. The steepness of the center slope can be controlled with the strike difference. We can see from the diagrams that Spreads are (almost) equivalent to <a href="http://www.financial-hacker.com/binary-options-scam-or-opportunity/" target="_blank" rel="noopener">binary options</a> &#8211; but with a much better payout factor. The diagrams are not completely symmetrical, and the Call Spread above has $514 potential profit and $486 potential loss &#8211; equivalent to a binary option with 105% payout. If the asset has the same likeliness of going up and going down, a Call Spread gives us a statistical advantage similar to the seller&#8217;s advantage of single options. With a Put Spread it&#8217;s the other way around.</p>
<p>The green line shows us whether it makes sense to sell the combo prematurely. Suppose we learned that the new iPhone tends to sudden explosions, and opened an AAPL Put Spread. When the AAPL price goes down and falls below $120 after 2 months, it makes no sense to wait until expiration, since the green line at 120 has almost the same value than the blue line. Only problem is that selling reduces our profit by the bid/ask spread and commission. An option expiration has no bid/ask spread and, if out of the money, also no commission.</p>
<p>Some more combos:</p>
<pre class="prettyprint">// Strangle
void combo()
{
	optionAdd(1, BUY|CALL, 5);
	optionAdd(1, BUY|PUT, -5);
}</pre>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s7.png"><img loading="lazy" decoding="async" class="alignnone wp-image-2511" src="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s7.png" alt="" width="423" height="257" srcset="https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s7.png 846w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s7-300x182.png 300w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s7-768x466.png 768w" sizes="auto, (max-width: 423px) 85vw, 423px" /></a></p>
<pre class="prettyprint">// Condor
void combo()
{
	optionAdd(1, BUY|CALL, -10);
	optionAdd(1, SELL|CALL, -5);
	optionAdd(1, SELL|CALL, 5);
	optionAdd(1, BUY|CALL, 10);
}</pre>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s8.png"><img loading="lazy" decoding="async" class="alignnone wp-image-2514" src="http://www.financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s8.png" alt="" width="423" height="257" srcset="https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s8.png 846w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s8-300x182.png 300w, https://financial-hacker.com/wp-content/uploads/2018/01/OptionsCurve_AAPL_s8-768x466.png 768w" sizes="auto, (max-width: 423px) 85vw, 423px" /></a></p>
<p>Combos that involve both selling and buying options &#8211; such as Spreads, Condors, or Butterflys &#8211; are especially attractive. Their investment is only the difference of the premiums, and the broker&#8217;s margin requirement is also accordingly smaller due to the limited risk. This allows trading with small capital and high leverage.</p>
<h3>Get rich quick</h3>
<p>Here&#8217;s my today&#8217;s get-rich-quick tip, this time for brokers. The problem with options is that you often need to wait weeks, months, or years until they finally expire and you can book your profit. Dear brokers, how about opening a market for <strong>short-term options</strong>? Options that expire at the end of each trading day, with strike prices in steps of cents, not dollars? Those options would be a very interesting instrument especially for short-term algorithmic trading. They would become very popular and produce a lot of commissions. Of course, 10% of those commissions are mine. I just patented this concept. Contact me for license conditions.</p>
<h3>Conclusion</h3>
<ul style="list-style-type: square;">
<li>Options can be clever combined for reducing the investment, limiting the risk, increasing the leverage, and generating profit diagrams of any shape.</li>
<li>Depending on premiums, profit diagrams are often not perfectly symmetrical. This results in a statistial advantage (or disadvantage) of option combos with nondirectional assets.</li>
</ul>
<p>I&#8217;ve included the <strong>OptionsCurve</strong> script in the 2017 script repository. Since price data download from Google rather than <a href="http://www.financial-hacker.com/bye-yahoo-and-thank-you-for-the-fish/" target="_blank" rel="noopener">Yahoo</a> was only recently implemented, you&#8217;ll need Zorro 1.59 or above. You&#8217;ll also need R and the RQuantLib package. In the final article of this series we&#8217;ll test a real options trading strategy.</p>
<p style="text-align: right;"><a href="http://www.financial-hacker.com/algorithmic-options-trading-part-3/">Options Trading, Part 3</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/algorithmic-options-trading-2/feed/</wfw:commentRss>
			<slash:comments>32</slash:comments>
		
		
			</item>
		<item>
		<title>Algorithmic Options Trading 1</title>
		<link>https://financial-hacker.com/algorithmic-options-trading/</link>
					<comments>https://financial-hacker.com/algorithmic-options-trading/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Thu, 26 Jan 2017 12:22:22 +0000</pubDate>
				<category><![CDATA[Introductory]]></category>
		<category><![CDATA[System Development]]></category>
		<category><![CDATA[Black-Scholes Formula]]></category>
		<category><![CDATA[Call]]></category>
		<category><![CDATA[Implied Volatility]]></category>
		<category><![CDATA[Options]]></category>
		<category><![CDATA[Put]]></category>
		<category><![CDATA[SPY]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=2198</guid>

					<description><![CDATA[Despite the many interesting features of options, private traders rarely take advantage of them (of course I&#8217;m talking here of serious options, not binary options). Maybe options are unpopular due to their reputation of being complex. Or because they are unsupported by most trading software. Or due to the price tags of the few options &#8230; <a href="https://financial-hacker.com/algorithmic-options-trading/" class="more-link">Continue reading<span class="screen-reader-text"> "Algorithmic Options Trading 1"</span></a>]]></description>
										<content:encoded><![CDATA[<p>Despite the many interesting features of options, private traders rarely take advantage of them (of course I&#8217;m talking here of serious options, not <a href="http://www.financial-hacker.com/binary-options-scam-or-opportunity/" target="_blank" rel="noopener noreferrer">binary options</a>). Maybe options are unpopular due to their reputation of being <strong>complex</strong>. Or because they are unsupported by most trading software. Or due to the <strong>price tags</strong> of the few options trading tools and of the historical data that you need for algorithmic trading. Whatever &#8211; we recently did several programming contracts for algorithmic options trading systems, and I was surprised that even simple systems seemed to produce <strong>relatively consistent profit</strong>. Especially selling options appears more lucrative than trading &#8216;conventional&#8217; instruments. This article is the first one of a mini-series about earning money with algorithmic options trading.  <span id="more-2198"></span></p>
<h3>Options 101</h3>
<p>Options are explained on many websites and in many trading books, so here&#8217;s just a quick overview. An option is a contract that gives its owner the right to buy (<strong>call</strong> option) or sell (<strong>put</strong> option) a financial asset (the <strong>underlying</strong>) at a fixed price (the <strong>strike</strong> price) at or before a fixed date (the <strong>expiry</strong> date). If you sell short (<strong>write</strong>) an option, you&#8217;re taking the other side of the trade. So you can enter a position in 4 different ways:</p>
<p>Buy a call &#8211; pay for the right to buy the underlying.<br />
Buy a put &#8211; pay for the right to sell the underlying.<br />
Write a call &#8211; get paid for the obligation to sell the underlying.<br />
Write a put &#8211; get paid for the obligation to buy the underlying.</p>
<p>And this with all possible combinations of strike prices and expiry dates.</p>
<p>The <strong>premium</strong> is the price that you pay or collect for buying or selling an option. It is far less than the price of the underlying stock. Major option markets are usually liquid, so you can anytime buy, write, or sell an option with any reasonable strike price and expiry date. If the current underlying price (the <strong>spot</strong> price) of a call option lies above the strike price, the option is <strong>in the money</strong>; otherwise it&#8217;s <strong>out of the money</strong>. The opposite is true for put options. In-the-money is good for the buyer and bad for the seller. Options in the money can be <strong>exercised</strong> and are then exchanged for the underlying at the strike price. The difference of spot and strike is the buyer&#8217;s profit and the seller&#8217;s loss. <strong>American</strong> style options can be exercised anytime, <strong>European</strong> style options only at expiration.</p>
<p>Out-of-the-money options can not be exercised, at least not at a profit. But they are not worthless, since they have still a chance to walk into the money before expiration. The <strong>value</strong> of an option depends on that chance, and can be calculated for European options from spot price, strike, expiry, riskless yield rate, dividend rate, and underlying volatility with the famous <a href="https://www.investopedia.com/terms/b/blackscholes.asp" target="_blank" rel="noopener noreferrer"><strong>Black-Scholes formula</strong></a>. This value is the basis of the option <strong>premium</strong>. The real premium might deviate slightly dependent on supply, demand, and belief in the underlying&#8217;s future price.</p>
<p>By reversing the formula with an approximation process, the volatility can be calculated from the real premium. This <strong>implied volatility</strong> is how the market expects the underlying to fluctuate in the next time. The partial derivatives of the option value are the <a href="https://en.wikipedia.org/wiki/Greeks_(finance)" target="_blank" rel="noopener noreferrer"><strong>Greeks</strong></a> (Delta, Vega &#8211; don&#8217;t know what Greek letter that&#8217;s supposed to be &#8211; and Theta). They determine in which direction, and how strong, the value will change when a market parameter changes.</p>
<p>That&#8217;s all basic info needed for trading options. By the way, it&#8217;s interesting to compare the performances of strategies from trading books. While the forex or stock trading systems described in those books are <a href="http://www.financial-hacker.com/seventeen-popular-trade-strategies-that-i-dont-really-understand/" target="_blank" rel="noopener noreferrer">mostly bunk</a> and lose already in a simple backtest, it is not so with option systems. They often win in backtests. And this even though apparently almost no book author has really backtested his system. Are options trading book authors just more intelligent than other trading book authors? Maybe, but we&#8217;ll see that there is an alternative explanation.</p>
<h3>Why trading options at all?</h3>
<p>They are more complex and more difficult to trade, and you need a Nobel prize winning formula to calculate a value that otherwise would simply be a difference of entry and exit price. Despite all this, options offer many wonderful advantages over other financial instruments:</p>
<ul style="list-style-type: square;">
<li><strong>High leverage.</strong> With $100 you can buy only a few shares, but options of several hundred shares.</li>
<li><strong>Controlled risk.</strong> A short position in a stock can wipe your account; positions in options can be clever combined to limit the risk in any desired way. And unlike a stop loss it&#8217;s a real risk limit.</li>
<li><strong>Additional dimensions.</strong> Stock profits just depend on rising or falling prices. Option profits can be achieved with rising volatility, falling volatility, prices moving in a range, out of a range, or almost any other imaginable price behavior.</li>
<li><strong>Fire and forget.</strong> Options expire, so you don&#8217;t need an algorithm for closing them (unless you want to sell or exercise them on special conditions). And you pay no exit commission for an expired option.</li>
<li><b>Seller advantage.</b> Due to the premium, options can still produce a profit to their seller even if the underlying moves in the wrong direction.</li>
</ul>
<p>Hacker ethics requires that you not just claim something, but prove it. For getting familiar with options, let&#8217;s put the last claim, the seller advantage, to the test:</p>
<pre class="prettyprint">void run() 
{
	BarPeriod = 1440;
	assetList("assetsIB");
	assetHistory("SPY",FROM_YAHOO|UNADJUSTED);
	asset("SPY");
	if(is(INITRUN)) dataLoad(1,"SPY_Options.t8",9);

	Multiplier = 100;
	contractUpdate("SPY",1,CALL|PUT);	
	int Type = ifelse(random() &gt; 0,CALL,PUT);
	contract(Type,30,priceClose());
	static int LastExpiry = 0;
	if(ContractType &amp;&amp; LastExpiry != ContractExpiry) {
		enterShort();
		LastExpiry = ContractExpiry;
	}
}</pre>
<p>This is a very simple option trading system. It randomly writes call or put options and keeps the positions open until they expire. Due to the put/call randomness it is trend agnostic. Before looking into code details, just run it in [Test] mode a couple times (you&#8217;ll need <a href="http://www.financial-hacker.com/hackers-tools-zorro-and-r/" target="_blank" rel="noopener noreferrer">Zorro</a> version 1.53 or above). You&#8217;ll notice that the result is different any time, but it is more often positive than negative, even though commission is subtracted from the profit. A typical outcome:</p>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2017/03/OptionsSellRandom_SPY.png"><img loading="lazy" decoding="async" class="alignnone wp-image-2270 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2017/03/OptionsSellRandom_SPY.png" width="649" height="401" srcset="https://financial-hacker.com/wp-content/uploads/2017/03/OptionsSellRandom_SPY.png 649w, https://financial-hacker.com/wp-content/uploads/2017/03/OptionsSellRandom_SPY-300x185.png 300w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a></p>
<p>You can see that most trades win, but when they lose, they lose big. Now reverse the strategy and buy the options instead of selling them: Replace <strong>enterShort()</strong> by <strong>enterLong()</strong>. Run it again a couple times (the script needs about 3 seconds for a backtest). You will now see that the result is more often negative &#8211; in fact almost any time.</p>
<p>It seems that options, at least the tested SPY contracts, indeed favor the seller. This is somewhat similar to the <a href="http://www.financial-hacker.com/get-rich-slowly/" target="_blank" rel="noopener noreferrer">positive expectancy</a> of long positions in stocks, ETFs, or index futures, but the options seller advantage is stronger and independent of the market direction. It might explain a large part of the positive results of option systems in trading books. Why are there then option buyers at all? Options are often purchased not for profit, but as an insurance against unfavorable price trends of the underlying. And why is the seller advantage not arbitraged away by the market sharks? Maybe because there&#8217;s yet not much algorithmic trading with options, and because there are anyway <a href="http://www.financial-hacker.com/build-better-strategies/" target="_blank" rel="noopener noreferrer">more whales than sharks</a> in the financial markets.</p>
<h3>Functions for options</h3>
<p>We can see that options trading and backtesting requires a couple more functions than just trading the underlying. Without options, the same random trading system would be reduced to this short script:</p>
<pre class="prettyprint">void run() 
{
	BarPeriod = 1440;
	assetList("assetsIB");
	assetHistory("SPY",FROM_YAHOO);
	asset("SPY");

	if(random() &gt; 0)
		enterLong();
	else
		enterShort();
}</pre>
<p>Options require (at least) three additional functions:</p>
<ul style="list-style-type: square;">
<li><strong>dataLoad(1,&#8221;SPY_Options.t8&#8243;,9)</strong> loads historical options data from the file <strong>&#8220;SPY_Options.t8&#8221;</strong> into a data set. Options data includes not only the ask and bid prices, but also the strike price, the expiration date, the type &#8211; put or call, American or European &#8211; of any option, and some rarely used additional data such as the open interest. Unlike historical price data, options data is usually expensive. You can purchase it from vendors such as <a href="http://www.ivolatility.com/" target="_blank" rel="noopener noreferrer">iVolatility</a>. But there&#8217;s an alternative way to get it for free, which I&#8217;ll describe below.</li>
<li><strong>contractUpdate(&#8220;SPY&#8221;,1,CALL|PUT)</strong> loads the current <strong>option chain</strong>. In backtest mode it&#8217;s loaded from the above data set, in live trading mode it&#8217;s loaded from the broker. The option chain is a list of all available option contracts of the selected underlying, with all available strike prices and all expiration dates. If you open it manually in the IB trading platform, it looks like this:</li>
</ul>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2017/03/optionchain.png"><img loading="lazy" decoding="async" class="alignnone wp-image-2257 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2017/03/optionchain.png" width="743" height="582" srcset="https://financial-hacker.com/wp-content/uploads/2017/03/optionchain.png 743w, https://financial-hacker.com/wp-content/uploads/2017/03/optionchain-300x235.png 300w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a></p>
<p>The center column lists different strike prices and expiry dates, the right and left parts are the ask and bid prices and order book sizes for their assigned call (left) and put options (right). The prices are per share; an option contract always covers a certain number of shares, normally 100. So you can see in the list above that you&#8217;ll collect $15 premium when you write a SPY call option expiring next week (Feb 03, 2017) with a $230 strike price. If SPY won&#8217;t rise above $230 until that date, the $15 are your profit. If it rised to $230 and 10 cents and the option is exercised (happens automatically when it expires in the money), you still keep $5. But if it suddenly soared to $300 (maybe Trump announced 100-ft. walls all around the US, all paid by himself), you have to bear a $6985 loss.</p>
<p>The image displays 54 contracts, but this is only a small part of the option chain, since there are many more expiry dates and strike prices available. The SPY option chain can contain up to 10,000 different options. They all are downloaded to the PC with the above <strong>contractUpdate</strong> function, which can thus take a couple seconds to complete<strong>.</strong></p>
<ul style="list-style-type: square;">
<li><strong>contract(Type,30,priceClose())</strong> selects a particular option from the previously downloaded option chain. The type (<strong>PUT</strong> or <strong>CALL</strong>), the days until expiration (<strong>30</strong>), and the strike (<strong>priceClose()</strong> is the current price of the underlying) are enough information to select the best fitting option. Note that for getting correct strike prices in the backtest, we downloaded the underlying price data with the <strong>UNADJUSTED</strong> flag. Strike prices are always unadjusted.</li>
</ul>
<p>Once a contract is selected, the next <strong>enterLong()</strong> or <strong>enterShort()</strong> buys or sells the option at market. The <strong>if()</strong> clause checks that the contract is available and its expiry date is different to the previous one (for ensuring that only different contracts are traded). Entry, stop, or profit limits would work as usual, they now only apply to the option value, the premium, instead of the underlying price. The backtest assumes that when an option is exercised or expires in the money, the underlying is immediately sold, and the profit is booked into the buyer&#8217;s account and deducted from the seller&#8217;s account. If the option expires out of the money, the position just vanishes. So we don&#8217;t care about exiting positions in this strategy. Apart from those differences, trading options works just as trading any other financial instrument.</p>
<h3>Backtesting option strategies</h3>
<p>Here&#8217;s an easy way to get rich. Open an IB account and run a software that records the options chains and contract prices in one-minute intervals. That&#8217;s what some data vendors did in the last 5 years, and now they are dear selling their data treasures. Although you can easily pay several thousand dollars for a few year&#8217;s option chains of major stocks, I am not sure who really owns the copyright of this data &#8211; the vendor, the broker, the exchange, or the market participants? This might be a legal grey area. Anyway, you need historical data for developing options strategies, otherwise you could not backtest them.</p>
<p>Here&#8217;s a method to get it for free and without any legal issues:</p>
<pre class="prettyprint">#include &lt;contract.c&gt;

string Code = "SPY"; 
string FileName = "History\\SPY_Options.t8";
var StrikeMax[3] = { 5,25,100 }; // strike ranges
var StrikeStep[3] = { 1,5,10 }; // strike step widths
int DaysMax = 180;  // max contract life in days
var BidAskSpread = 2.5; // bid/ask spread in percent
var Dividend = 2.0; // annual dividend in percent
int Type = 0; // or EUROPEAN, or FUTURE 

/////////////////////////////////////////////////////////

CONTRACT* c;
int N = 0;

void run() 
{
	BarPeriod = 1440;
	StartDate = 2011;
	EndDate = 2017;
	LookBack = 21;
	assetList("AssetsIB");
	assetHistory(Code,FROM_YAHOO|UNADJUSTED);
	asset(Code);
	if(is(INITRUN)) {
		initRQL();
		int MaxContractsPerDay = 2*(1+2*(StrikeMax[0]/StrikeStep[0] + StrikeMax[1]/StrikeStep[1] + StrikeMax[2]/StrikeStep[2])) * (1+DaysMax/7);
		int TotalContracts = (1+EndDate-StartDate)*252*MaxContractsPerDay;
		printf("\nAllocating %d Contracts",TotalContracts);
		c = (CONTRACT*)dataNew(1,TotalContracts,9);
		N = 0;
	}

	vars Close = series(priceClose());
	var HistVolOV = VolatilityOV(20);
	var Unl = Close[0];
	var Interest = yield();

	if(!is(LOOKBACK)) {
		var Strike;
		int i, Days = 1;
		while((dow()+Days)%7 != FRIDAY) Days++;
		for(; Days &lt;= DaysMax; Days += 7)
		for(Strike = max(10,round(Unl-StrikeMax[2],StrikeStep[2])); Strike &lt;= Unl+StrikeMax[2]; Strike)
		for(i = 0; i &lt; 2; i++)
		{
			c-&gt;time = wdate();
			c-&gt;fUnl = Unl;
			c-&gt;fStrike = Strike;
			c-&gt;Type = Type | ifelse(i,PUT,CALL);
			c-&gt;Expiry = ymd(c-&gt;time+Days);
			c-&gt;fBid = contractVal(c,Unl,HistVolOV,0.01*Dividend,0.01*Interest);
			if(c-&gt;fBid &lt; 0.01) continue; // probably no liquidity
			c-&gt;fAsk = (1.0+BidAskSpread/100)*c-&gt;fBid;

			if(abs(Unl-Strike) &lt; StrikeMax[0]) Strike += StrikeStep[0];
			else if(abs(Unl-Strike) &lt; StrikeMax[1]) Strike += StrikeStep[1];
			else Strike += StrikeStep[2];
			N++; c++;
		}
	}
	
	if(is(EXITRUN)) {
		printf("\nSaving %d Records",N);
		dataSort(1);	// reverse the entry order
		dataSave(1,FileName,0,N);
		printf("\nOk!");
	}
}
</pre>
<p>This script is a bit longer than the usual Zorro scripts that I post here, so I won&#8217;t explain it in detail. It generates artificial option chains for any day from 2011-2017, and stores them in a historical data file. The option prices are calculated from the underlying price, the volatility, the current risk free interest rate, and the dividend rate of the underlying. It uses three ranges of strike prices, and expiry dates at any Friday of the next 180 days. You need <a href="http://www.financial-hacker.com/hackers-tools-zorro-and-r/" target="_blank" rel="noopener noreferrer">R</a> installed for running it, and also the <a href="https://cran.r-project.org/web/packages/RQuantLib/RQuantLib.pdf" target="_blank" rel="noopener noreferrer">RQuantlib</a> package for calculating option values. All functions are described in the Zorro manual. The <strong>yield()</strong> function returns the current yield rate of US treasury bills, and <strong>contractVal()</strong> calculates the premium by solving a differential equation with all option parameters. The source code of both functions can be found in the <strong>contract.c</strong> include file.</p>
<p>Due to the slow differential equation solver and the huge number of options, the script needs several hours to complete. Here&#8217;s a comparison of the generated data with real SPY options data:</p>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2017/03/OptionsTest7_SPY.png"><img loading="lazy" decoding="async" class="alignnone wp-image-2278 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2017/03/OptionsTest7_SPY.png" width="1099" height="568" srcset="https://financial-hacker.com/wp-content/uploads/2017/03/OptionsTest7_SPY.png 1099w, https://financial-hacker.com/wp-content/uploads/2017/03/OptionsTest7_SPY-300x155.png 300w, https://financial-hacker.com/wp-content/uploads/2017/03/OptionsTest7_SPY-768x397.png 768w, https://financial-hacker.com/wp-content/uploads/2017/03/OptionsTest7_SPY-1024x529.png 1024w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a></p>
<p>The blue line are the artificial option prices, the black line are the real prices purchased from an options data vendor, both for 3-weeks SPY contracts with 10 points spot-strike distance. You can see that the prices match quite well. There are some tiny differences that might be partially random, partially caused by anomalies in supply and demand. For strategies that exploit those anomalies &#8211; that includes all strategies based on implied volatility &#8211; you&#8217;ll need real historical options prices. For option strategies that exploit only price or volatility changes of the underlying, the artificial data will most likely do. See, reading this article up to the end already saved you a couple thousand dollars.</p>
<h3>Conclusion</h3>
<ul style="list-style-type: square;">
<li>Options and option combinations can be used to create artificial financial instruments with very interesting properties.</li>
<li>Option strategies, especially options selling, are more likely to be profitable than other strategies.</li>
<li>Algorithmic option strategies are a bit, but not much more complex than strategies with other financial instruments.</li>
</ul>
<p>I&#8217;ve included all scripts in the 2017 script repository, and also a historical data set with the yield rates (otherwise you needed the Quandl bridge or Zorro S for downloading them). You&#8217;ll need Zorro 1.53 or above, which is currently available under the &#8220;Beta&#8221; link of the Zorro download page. The error message from the free Zorro version about the not supported Quandl bridge can be ignored, due to the included yield rates the script will run nevertheless.</p>
<p>In the next article we&#8217;ll look more closely into option values and into methods to combine options for limiting risk or trading arbitrary price ranges. Those combinations with funny names like &#8220;Iron Condor&#8221; or &#8220;Butterfly&#8221; are often referred to as option strategies, but they are not &#8211; they are just artificial financial instruments. How you trade them is up to the real strategy. Some simple, but consistently profitable option strategies will be the topic of the third article of this mini-series.</p>
<p style="text-align: right;"><a href="http://www.financial-hacker.com/algorithmic-options-trading-2/"><strong>=&gt; Part 2</strong></a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/algorithmic-options-trading/feed/</wfw:commentRss>
			<slash:comments>57</slash:comments>
		
		
			</item>
		<item>
		<title>Build Better Strategies!</title>
		<link>https://financial-hacker.com/build-better-strategies/</link>
					<comments>https://financial-hacker.com/build-better-strategies/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Mon, 09 Nov 2015 10:27:03 +0000</pubDate>
				<category><![CDATA[Introductory]]></category>
		<category><![CDATA[No Math]]></category>
		<category><![CDATA[System Development]]></category>
		<category><![CDATA[CHF]]></category>
		<category><![CDATA[Economy]]></category>
		<category><![CDATA[Grid trading]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=799</guid>

					<description><![CDATA[Enough blog posts, papers, and books deal with how to properly optimize and test trading systems. But there is little information about how to get to such a system in the first place. The described strategies often seem to have appeared out of thin air. Does a trading system require some sort of epiphany? Or is &#8230; <a href="https://financial-hacker.com/build-better-strategies/" class="more-link">Continue reading<span class="screen-reader-text"> "Build Better Strategies!"</span></a>]]></description>
										<content:encoded><![CDATA[<p>Enough blog posts, papers, and books deal with how to properly optimize and test trading systems. But there is little information about how to get to such a system in the first place. The described strategies often seem to have appeared out of thin air. Does a trading system require some sort of epiphany? Or is there a systematic approach to developing it?<br />   This post is the first of a small series in which I&#8217;ll attempt a methodical way to build trading strategies. The first part deals with the two main methods of strategy development, with market hypotheses and with a Swiss Franc case study.<span id="more-799"></span></p>
<h3>Strategies come in two flavors</h3>
<p>You can use mainly two methods to develop trading systems: <strong>model-based</strong> and <strong>data-mining</strong>. A model-based system starts with a model of a <strong>market inefficiency</strong> &#8211; based on trader psychology, economy, market microstructure, or any other price affecting force. The inefficiency produces a price curve anomaly or pattern that deviates from the random walk and can &#8211; when predictive &#8211; be used for a trade algorithm. Examples of model based trading methods are trend following, mean reversion, price cycles, price clusters, statistical arbitrage, and seasonality.</p>
<p>The problem: A model is not the reality. It is a simplified image of it. It can not be proven and can often not even be falsified. Its validity can only be determined by its effects on the price curve. The usefulness of this method thus depends on the significance and long-term stability of its price curve anomalies. For judging this you need good test algorithms. </p>
<p>The <strong>pure data mining method</strong> works the other way around. It just looks for price curve patterns and attempts to fit an algorithm to them. By which market forces the patterns are caused is of no interest; only assumption is that patterns of the past will repeat in the future. This allows the generation of trade systems, often, but not always with machine learning software. The most popular methods in this approach are trial-and-error TA, candle patterns, regression, autocorrelation, k-means clustering, neural networks, support vector machines, and decision trees.</p>
<p>The advantage of data mining is that you do not need to care about market hypotheses. The disadvantage: those methods usually find a vast amount of random patterns and thus generate a vast amount of worthless strategies. Since mere data mining is a blind approach, distinguishing real patterns &#8211; caused by real market inefficiencies &#8211; from random patterns is a challenging task. Even sophisticated <a href="http://www.financial-hacker.com/whites-reality-check/">reality checks</a> can normally not eliminate all data mining bias. Not many successful trading systems generated by data mining methods are known today.</p>
<h3>Are you cleverer than the market?</h3>
<p>Obviously, no trading system would work when market inefficiencies do not exist. And it would not work either when they exist, but can not be exploited since better equipped players are doing that already. In this first part of the mini-series I look into the possibility of <strong>trading better than the majority</strong> of market participants, a prerequisite of a successful strategy. </p>
<p>The three hypotheses of market efficiency that you&#8217;ll hear from time to time are as follows: </p>
<ul style="list-style-type: square;">
<li><strong>Hypothesis A: The markets are efficient.</strong> Prices follow real events, such as the publication of company results, and reflect the real value of the asset. All traders are &#8216;informed&#8217;, decide rationally and act immediately. Price curves are mostly random-walk curves with no information for predicting future prices. Technical trading systems can not work, or if they do, it&#8217;s just luck.<br />  </li>
<li><strong>Hypothesis B: The markets are not efficient, but their inefficiencies are of no value</strong> for private traders. Only large trading firms and hedge funds can exploit them successfully, since they have lots of capital, very fast computers, very experienced analysts and very clever quants &#8211; much more intelligent than you. Beware of entering their terrain, or else you&#8217;ll become their prey.<br />  </li>
<li><strong>Hypothesis C: Enough market inefficiencies are free for you to exploit.</strong> Large trading firms and hedge funds are too slow and cumbersome to tackle them effectively. Their capital and their fast computers give them no real advantage in the game that you&#8217;re going to play. Neither do their clueless analysts, overpaid traders, and overestimated quants.</li>
</ul>
<p>Not many today do still believe in hypothesis A. It can be easily shown that most price curves do not follow a random walk (a fellow blogger recently posted a great article about <a href="http://www.turingfinance.com/hacking-the-random-walk-hypothesis/" target="_blank">Hacking the Random Walk Hypothesis</a>). And the markets are anything but rational or effective. Counter-examples are plenty. Jack Schwager, in his book &#8216;Market Sense and Nonsense&#8217;, listed cases of <strong>blatant market dumbness and grotesque analyst failures</strong>. More often than not, asset prices are far, far away from their true value. Although all this is anecdotical evidence, a pattern is visible. The markets react fast and firm when rumors or news give them a clear direction. But when the information is a little more subtle and requires a minimum of interpretation, they react slow or not at all. Here&#8217;s the story of a typical example.</p>
<h3>The Swiss Franc case</h3>
<p>In September 2011 the Swiss National Bank established a price cap to the Swiss Franc. Purpose was protecting the tourism and export industries against an overvalued currency. The limit was set to an EUR/CHF price of 1.20, and the SNB vowed to defend it against all enemies.</p>
<p>A price cap is a <strong>rare and striking market inefficiency</strong>. It can immediately be translated into a highly profitable, almost risk-free trading system (how this works is explained below). So you would normally expect a strong market reaction after the EUR/CHF price move to 1.20. But the reaction was a long time in the coming.</p>
<p>No doubt, Switzerland is an obscure European country and for the major US trading firms probably known for cheese, if at all. They did either not notice the price cap, or they had just forgotten to equip their European offices with modern communication gear. So it took the mounted messenger from Europe three months riding over hill and dale, sailing over the Atlantic Ocean, maybe fighting off brigands, pirates, and indians on his way, to reach New York City and shout: &#8220;The Swiss have a price cap!&#8221;.</p>
<p>But what the heck can you do with a price cap? By January 2012, large market participants had finally come up with an idea. Not something as subtle as a trading system. Instead, they began to buy mad amounts of Francs for bringing pressure on the EUR/CHF price: </p>
<p><figure style="width: 879px" class="wp-caption alignnone"><img loading="lazy" decoding="async" class="alignnone wp-image-869 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/11/chf1.png" alt="" width="879" height="321" /><figcaption class="wp-caption-text">EUR/CHF price curve, September 2011 &#8211; August 2012</figcaption></figure></p>
<p>The obvious idea was that when there is a price boundary, there must be some profit in breaking it. A lot of effort, patience and money was put in that game. From May 2012 on the EUR/CHF price was nailed shut to its 1.20 limit. But alas, the price cap collapse did not happen. You do not mess with the SNB. During 2012 the Swiss erected a <strong>wall of 200 billion dollars</strong> for defending the price cap. The attackers never had a chance. The first gave up in September 2012, and by the end of January 2013 all had retreated with their tails between their legs (and probably painful losses):</p>
<p><figure id="attachment_869" aria-describedby="caption-attachment-869" style="width: 879px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/11/chf2.png"><img loading="lazy" decoding="async" class="wp-image-869 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/11/chf2.png" alt="" width="879" height="321" srcset="https://financial-hacker.com/wp-content/uploads/2015/11/chf2.png 879w, https://financial-hacker.com/wp-content/uploads/2015/11/chf2-300x110.png 300w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-869" class="wp-caption-text">EUR/CHF price curve, September 2012 &#8211; May 2013</figcaption></figure></p>
<p>Now the way was free for algorithmic systems. During the 2012 CHF battle they were forced to inactivity, since private traders and hackers lack the capital to participate in a market manipulation game. In January 2013 the first hackers started to exploit the market inefficiency with a specific method, a <strong>Grid Trader</strong>.<a id="gridtrader"></a> This turned out a money-printing machine.</p>
<h3>The money press algorithm</h3>
<p>A grid trader is a very simple system. It places pending long and short trades at a fixed grid above and below the current price, with profit targets of the same grid distance. So trades are opened and closed whenever the price crosses a grid line in any direction. Such a system has a hypothetical 100% win rate, since trades close either in profit or not at all. But grid traders normally use a <strong>virtual hedging mechanism</strong> that closes an open position instead of opening a new one in opposite direction. This improves the total profit by reducing trade costs and margin. But it allows trades to be closed with a loss. So the real win rate of a grid trader is in the 60% area.</p>
<p>This is the Zorro script of such a grid trader:</p>
<pre class="prettyprint">// helper function to check if the grid line has no trade
bool isFree(var Price,var Grid,bool IsShort)
{
  bool result = true;
  for(open_trades) {
    if(TradeIsShort == IsShort
      &amp;&amp; between(TradeEntryLimit,Price-Grid/2,Price+Grid/2))
        result = false;
  }
  return result;
}

// EUR/CHF grid trader main function
int run() 
{
  BarPeriod = 60;
  Hedge = 5; // activate virtual hedging

  var Grid = 20*PIP; // set grid distance to 20 pips
  var Close = priceClose();
 
// place pending trades at 5 grid lines above and below the Close
  int i;
  for(i = Close/Grid - 5; i &lt; Close/Grid + 5; i++)
  {
    var Price = i*Grid;
// place short trades with profit target below the current price
    if(Price &lt; Close &amp;&amp; isFree(Price,Grid,true))
      enterShort(1,Price,0,Grid); 
// place long trades with profit target above the current price
    else if(Price &gt; Close &amp;&amp; isFree(Price,Grid,false))
      enterLong(1,Price,0,Grid);
  }
}</pre>
<p>A grid trader is a typical <strong>model-based system</strong>. It assumes that some market force keeps the price inside a channel. This is the case here: The cap prevents the EUR/CHF from falling below 1.20, but it also prevents it from rising too high, since the SNB must eventually buy back all the Francs they have sold for defending the cap. The mathematical model of this would be a random walk with a 1.20 boundary and some drift term that pulls the price down. Such a constraint is a prerequisite for a grid trader; without it grid trading would be just high-risk gambling and is consequently listed in the <a href="http://www.financial-hacker.com/seventeen-popular-trade-strategies-that-i-dont-really-understand/">irrational trade methods</a> collection.</p>
<p>This is the P&amp;L-curve (blue) of the above script applied to the EUR/CHF in 2013:</p>
<p><figure id="attachment_894" aria-describedby="caption-attachment-894" style="width: 879px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/11/chf3.png"><img loading="lazy" decoding="async" class="wp-image-894 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/11/chf3.png" alt="" width="879" height="401" srcset="https://financial-hacker.com/wp-content/uploads/2015/11/chf3.png 879w, https://financial-hacker.com/wp-content/uploads/2015/11/chf3-300x137.png 300w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-894" class="wp-caption-text">EUR/CHF grid trading P&amp;L curve 2013</figcaption></figure></p>
<p>We can see that large price fluctuations, as in January and May, cause large drawdowns (the red underwater peaks in the chart). But since the fluctuations have a limit, we can estimate the maximum loss and just keep enough capital on the account. This way the above script produces an annual return of 130% and a Sharpe Ratio of 1.7 &#8211; with virtually no risk ( as long as the price cap stays in place).</p>
<p>The news of such a trading strategy slowly spread in 2013. More and more private traders and financial hackers, and also more and more large market participants jumped on the bandwagon. Three years after installation of the price cap, thousands of such systems sat on the EUR/CHF price curve like leeches and sucked off money. The result was a continuously falling price volatility:</p>
<p><figure id="attachment_902" aria-describedby="caption-attachment-902" style="width: 879px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/11/chf4.png"><img loading="lazy" decoding="async" class="wp-image-902 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/11/chf4.png" alt="" width="879" height="438" srcset="https://financial-hacker.com/wp-content/uploads/2015/11/chf4.png 879w, https://financial-hacker.com/wp-content/uploads/2015/11/chf4-300x149.png 300w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-902" class="wp-caption-text">EUR/CHF price and volatility, July 2013 &#8211; Dec 2014</figcaption></figure></p>
<p>Lower volatility means lower profits to a grid trader. More capital must be invested and the grid must be tightened for compensating. But there is a natural limit. You can not have a grid size smaller than the trading costs. By autumn 2014 the volatility was close to zero. And this was accompanied by an ominous price downwards drift, as if some large market participant (possibly the SNB itself) would continously sell EUR and buy CHF in anticipation of some future event. That would have been high time for private traders to retreat from the game. Of course, thickheads like me didn&#8217;t. It is well known what then happened to the Swiss Franc:</p>
<p><figure id="attachment_917" aria-describedby="caption-attachment-917" style="width: 879px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/11/chf5.png"><img loading="lazy" decoding="async" class="wp-image-917 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/11/chf5.png" alt="" width="879" height="321" srcset="https://financial-hacker.com/wp-content/uploads/2015/11/chf5.png 879w, https://financial-hacker.com/wp-content/uploads/2015/11/chf5-300x110.png 300w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-917" class="wp-caption-text">EUR/CHF price, January 2015</figcaption></figure></p>
<p>In the morning of 15 January 2015, the SNB gave a press conference and announced the cancellation of the price cap. The EUR/CHF fell in minutes like a stone from the 1.20 limit to below parity. Obviously a fast and extreme market reaction &#8211; very different to the introduction of the price cap 4 years before. The price drop killed many accounts and even a few brokers. By the way, the &#8216;real value&#8217; of the EUR/CHF, based on the relative buying power of the two currencies, was in the 1.50 area all the time. </p>
<p>What can we learn from this and from similar examples?</p>
<h3>Conclusions</h3>
<ul>
<li>The financial markets react immediately and often hysterically on news with a clear price upwards/downwards direction.</li>
<li>The markets react slow or not at all on more subtle information. It can take years until they become aware of new inefficiencies or trading methods.</li>
<li>The markets prefer brute-force methods. Complex strategies are normally only used by a small part of market participants.</li>
<li>Simple systems based on very obvious inefficiencies can be extremely profitable, but have a limited lifetime. </li>
</ul>
<p>The next parts of the <strong>Build Better Strategies</strong> series will deal with model-based systems, with known market inefficiencies and with a methodical approach of exploiting them. </p>
<p style="text-align: right;"><strong>⇒ <a href="http://www.financial-hacker.com/build-better-strategies-part-2-model-based-systems/">Build Better Strategies &#8211; Part 2</a></strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/build-better-strategies/feed/</wfw:commentRss>
			<slash:comments>17</slash:comments>
		
		
			</item>
		<item>
		<title>Hacker&#8217;s Tools</title>
		<link>https://financial-hacker.com/hackers-tools-zorro-and-r/</link>
					<comments>https://financial-hacker.com/hackers-tools-zorro-and-r/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Sat, 03 Oct 2015 08:01:30 +0000</pubDate>
				<category><![CDATA[3 Most Useful]]></category>
		<category><![CDATA[Introductory]]></category>
		<category><![CDATA[No Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Aronson]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[TSSB]]></category>
		<category><![CDATA[Vector-based test]]></category>
		<category><![CDATA[Zorro]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=89</guid>

					<description><![CDATA[For our financial hacking experiments (and for harvesting their financial fruits) we need some software machinery for research, testing, training, and live trading financial algorithms. There are many tools for algo trading, but no existing software platform today is really up to all those tasks. You have to put together your system from different software &#8230; <a href="https://financial-hacker.com/hackers-tools-zorro-and-r/" class="more-link">Continue reading<span class="screen-reader-text"> "Hacker&#8217;s Tools"</span></a>]]></description>
										<content:encoded><![CDATA[<p>For our financial hacking experiments (and for harvesting their financial fruits) we need some software machinery for research, testing, training, and live trading financial algorithms. There are many <a href="https://zorro-project.com/algotradingtools.php" target="_blank" rel="noopener">tools for algo trading</a>, but no existing software platform today is really up to all those tasks. You have to put together your system from different software packages. Fortunately, two are normally sufficient. I&#8217;ll use <strong>Zorro</strong> and <strong>R</strong> for most articles on this blog, but will also occasionally look into other tools.<span id="more-89"></span></p>
<h3>Choice of languages</h3>
<p>Algo trading systems are normally based on a script in some programming language. You can avoid writing scripts entirely by using a visual &#8216;strategy builder&#8217;, &#8216;code wizard&#8217; or spreadsheet program for defining your strategy. But this is also some sort of programming, just in a different language that you have to master. And visual builders can only create rather simple &#8216;indicator soup&#8217; systems that are unlikely to produce consistent trading profit. For serious algo trading sytems, real development, and real research, there&#8217;s no stepping around &#8216;real programming&#8217;.</p>
<p>You&#8217;re also not free to select the programming language with the nicest or easiest syntax. One of the best compromises of simplicity and object orientation is probably <strong>Python</strong>. It also offers libraries with useful statistics and indicator functions. Consequently, many strategy developers start with programming their systems in Python&#8230; and soon run into serious limitations. There&#8217;s another criterion that is more relevant for system development than syntax: <strong>execution speed</strong>.</p>
<p>Speed mostly depends on whether a computer language is <strong>compiled </strong>or <strong>interpreted</strong>. <strong>C</strong>,<strong> Pascal</strong>, and <strong>Java </strong>are compiled languages, meaning that the code runs directly on the processor (C, C++, Pascal) or on a &#8216;virtual machine&#8217; (Java). <strong>Python</strong>, <strong>R</strong>, and <strong>Matlab </strong>is interpreted: The code won&#8217;t run by itself, but is executed by an interpreter software. Interpreted languages are much slower and need more CPU and memory resources than compiled languages. It won&#8217;t help much for trading strategies that they have fast C-programmed libraries. All backtests or optimization processes must still run through the bottleneck of interpreted trading logic. Theoretically the slowness can be worked around with &#8216;vectorized coding&#8217; &#8211; see below &#8211; but that has little practical use.</p>
<p>R and Python have other advantages. They are <strong>interactive</strong>: you can enter commands directly at a console. This allows quick code or function testing. Some languages, such as <strong>C#</strong>, are inbetween: They are compiled to a machine-independent interim code that is then, dependent on implementation, either interpreted or converted to machine code. C# is about 4 times slower than C, but still 30 times faster than Python.</p>
<p>Here&#8217;s a benchmark table of the same two test programs written in several languages: a sudoku solver and a loop with a 1000 x 1000 matrix multiplication (in seconds):</p>
<table>
<tbody>
<tr>
<td>Language</td>
<td>Sudoku</td>
<td>Matrix</td>
</tr>
<tr>
<td>C, C++</td>
<td>1.0</td>
<td>1.8</td>
</tr>
<tr>
<td>Java</td>
<td>1.7</td>
<td>2.6</td>
</tr>
<tr>
<td>Pascal</td>
<td>&#8212;</td>
<td>4</td>
</tr>
<tr>
<td>C#</td>
<td>3.8</td>
<td>9</td>
</tr>
<tr>
<td>JavaScript</td>
<td>18.1</td>
<td>16</td>
</tr>
<tr>
<td>Basic (VBA)</td>
<td>&#8212;</td>
<td>25</td>
</tr>
<tr>
<td>Erlang</td>
<td>18</td>
<td>31</td>
</tr>
<tr>
<td>Python</td>
<td>119</td>
<td>121</td>
</tr>
<tr>
<td>Ruby</td>
<td>98</td>
<td>628</td>
</tr>
<tr>
<td>Matlab</td>
<td>&#8212;</td>
<td>621</td>
</tr>
<tr>
<td>R</td>
<td>&#8212;</td>
<td>1738</td>
</tr>
</tbody>
</table>
<p>Speed becomes important as soon as you want to develop a short-term trading system. In the development process you&#8217;re all the time testing system variants. A 10-years backtest with M1 historical data executes the strategy about 3 million times. If a C-written strategy needs 1 minute for this, the same strategy in EasyLanguage would need about 30 minutes, in Python 2 hours, and in R more than 10 hours! And that&#8217;s only a backtest, no optimization or WFO run. If I had coded the <a href="http://www.financial-hacker.com/trend-and-exploiting-it/">trend experimen</a>t in Python or R, I would today still wait for the results. You can see why trade platforms normally use a C variant or a proprietary compiled language for their strategies. <a href="http://www.financial-hacker.com/hacking-hft-systems/">HFT systems</a> are anyway written in C or directly in machine language.</p>
<p>Even compiled languages can have large speed differences due to different implementation of trading and analysis functions. When we compare not Sudoku or a matrix multiplication, but a real trading system &#8211; the small RSI strategy from <a href="http://manual.zorro-project.com/conversion.htm">this page</a> &#8211; we find very different speeds on different trading platforms (10 years backtest, ticks resolution):</p>
<ul style="list-style-type: square;">
<li>Zorro: ~ 0.5 seconds (compiled C)</li>
<li>MT4:  ~ 110 seconds (MQL4, a C variant)</li>
<li>MultiCharts: ~ 155 seconds (EasyLanguage, a C/Pascal mix)</li>
</ul>
<p>However, the differences are not as bad as suggested by the benchmark table. In most cases the slow language speed is partically compensated by fast vector function libraries. A script that does not go step by step through historical data, but only calls library functions that process all data simultaneously, would run with comparable speed in all languages. Indeed some trading systems can be coded in this <strong>vectorized</strong> method, but <b>u</b>nfortunately this works only with simple systems and requires entirely different scripts for backtests and live trading.</p>
<h3>Choice of tools</h3>
<p><strong>Zorro</strong> is a software for financial analysis and algo-trading &#8211; a sort of Swiss Knife tool since you can use it not only for live trading, but also for all sorts of quick tests. It&#8217;s my software of choice for financial hacking because:</p>
<ul style="list-style-type: square;">
<li>It&#8217;s free (unless you&#8217;re rich).</li>
<li>Scripts are in C, event driven and very fast. You can code a system or an idea in 5 minutes.</li>
<li>Open architecture &#8211; you can add anything with DLL plugins.</li>
<li>Minimalistic &#8211; just a frontend to a programming language.</li>
<li>Can be automatized for experiments.</li>
<li>Very stable &#8211; I rarely found bugs and they were fixed fast.</li>
<li>Very accurate, realistic trading simulation, including HFT.</li>
<li>Supports also options and futures, and portfolios of multiple assets.</li>
<li>Has a library with 100s of indicators, statistics and machine learning functions, most with source code.</li>
<li>Is continuously developed and supported (new versions usually come out every 2..3 months).</li>
<li>Last but not least: I know it quite well, as I&#8217;ve written its tutorial&#8230;</li>
</ul>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/Zorro.png"><img loading="lazy" decoding="async" class="aligncenter wp-image-117 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/Zorro-e1441536629470.png" alt="Zorro" width="294" height="582" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/Zorro-e1441536629470.png 294w, https://financial-hacker.com/wp-content/uploads/2015/09/Zorro-e1441536629470-152x300.png 152w" sizes="auto, (max-width: 294px) 85vw, 294px" /></a></p>
<p>A strategy example coded in C, the classic SMA crossover:</p>
<pre class="prettyprint">void run()
{
  double* Close = series(priceClose());
  double* MA30 = series(SMA(Close,30));	
  double* MA100 = series(SMA(Close,100));
	
  Stop = 4*ATR(100);
  if(crossOver(MA30,MA100))
    enterLong();
  if(crossUnder(MA30,MA100))
    enterShort();
}</pre>
<p>More code can be found among the <a href="https://zorro-project.com/code.php" target="_blank" rel="noopener">script examples</a> on the Zorro website. You can see that Zorro offers a relatively easy trading implementation. But here comes the drawback of the C language: You can not as easy drop in external libraries as in Python or R. Using a C/C++ based data analysis or machine learning package involves sometimes a lengthy implementation. Fortunately, Zorro can also call R and Python functions for those purposes.</p>
<p><strong>R</strong> is a script interpreter for data analysis and charting. It is not a real language with consistent syntax, but more a conglomerate of operators and data structures that has grown over 20 years. It&#8217;s harder to learn than a normal computer language, but offers some unique advantages. I&#8217;ll use it in this blog when it comes to complex analysis or machine learning tasks. It&#8217;s my tool of choice for financial hacking because:</p>
<ul style="list-style-type: square;">
<li>It&#8217;s free. (&#8220;Software is like sex: it&#8217;s better when it&#8217;s free.&#8221;)</li>
<li>R scripts can be very short and effective (once you got used to the syntax).</li>
<li>It&#8217;s the global standard for data analysis and machine learning.</li>
<li>Open architecture &#8211; you can add modules for almost anything.</li>
<li>Minimalistic &#8211; just a console with a language interpreter.</li>
<li>Very stable &#8211; I found a few bugs in external libraries, but so far never in the main program.</li>
<li>Has tons of &#8220;packages&#8221; for all imaginable mathematical and statistical tasks, and especially for machine learning.</li>
<li>Is continuously developed and supported by the global scientific community (about 15 new packages usually come out every day).</li>
</ul>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/r.jpg"><img loading="lazy" decoding="async" class="alignnone wp-image-115 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/r-e1441536432531.jpg" alt="r" width="693" height="576" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/r-e1441536432531.jpg 693w, https://financial-hacker.com/wp-content/uploads/2015/09/r-e1441536432531-300x249.jpg 300w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a></p>
<p>This is the SMA crossover in R for a &#8216;vectorized&#8217; backtest:</p>
<pre class="prettyprint">require(quantmod)
require(PerformanceAnalytics)

Data &lt;- xts(read.zoo("EURUSD.csv", tz="UTC", format="%Y-%m-%d %H:%M", sep=",", header=TRUE))
Close &lt;- Cl(Data)
MA30 &lt;- SMA(Close,30)
MA100 &lt;- SMA(Close,100)
 
Dir &lt;- ifelse(MA30 &gt; MA100,1,-1) # calculate trade direction
Dir.1 &lt;- c(NA,Dir[-length(Dir)]) # shift by 1 for avoiding peeking bias
Return &lt;- ROC(Close)*Dir.1 
charts.PerformanceSummary(na.omit(Return))</pre>
<p>You can see that the vectorized code just consists of function calls. It runs almost as fast as the C equivalent. But it is difficult to read, it can not be used for live trading, and many parts of a trading logic &#8211; even a simple stop loss &#8211; cannot be coded for a vectorized test. Thus, so good R is for interactive data analysis, so hopeless is it for writing trade strategies &#8211; although some R packages (for instance, <strong>quantstrat</strong>) even offer rudimentary optimization and test functions. They all require an awkward coding style and do not simulate trading very realistically, but are still too slow for serious backtests.</p>
<p>Although R can not replace a serious backtest and trading platform, Zorro and R complement each other perfectly: <a href="http://www.financial-hacker.com/build-better-strategies-part-5-developing-a-machine-learning-system/" target="_blank" rel="noopener noreferrer">Here</a> is an example of a machine learning system build together with a deep learning package from R and the training and trading framework from Zorro.</p>
<h3>More hacker&#8217;s tools</h3>
<p>Aside from languages and platforms, you&#8217;ll often need auxiliary tools that may be small, simple, cheap, but all the more important since you&#8217;re using them all the time. For editing not only scripts, but even short CSV lists I use <a href="https://notepad-plus-plus.org/" target="_blank" rel="noopener noreferrer"><strong>Notepad++</strong></a>. For interactive working with R I recommend <a href="https://www.rstudio.com" target="_blank" rel="noopener noreferrer"><strong>RStudio</strong></a>. Very helpful for strategy development is a <strong>file comparison</strong> tool: You often have to compare trade logs of different system variants and check which variant opened which trade a little earlier or later, and which consequences that had. For this I use <a href="http://www.scootersoftware.com/" target="_blank" rel="noopener noreferrer"><strong>Beyond Compare</strong></a>.</p>
<p>Aside from Zorro and R, there&#8217;s also a relatively new system development software that I plan to examine closer at some time in the future, <strong><a href="http://www.tssbsoftware.com/" target="_blank" rel="noopener noreferrer">TSSB</a></strong> for generating and testing bias-free trading systems with advanced machine learning algorithms. David Aronson and Timothy Masters were involved in its development, so it certainly won&#8217;t be as useless as most other &#8220;trade system generating&#8221; software. However, there&#8217;s again a limitation: TSSB can not trade or export, so you can not really use the ingenious systems that you developed with it. Maybe I&#8217;ll find a solution to combine TSSB with Zorro.</p>
<h3>References</h3>
<p><a href="https://www.tiobe.com/tiobe-index/">TIOBE index</a> of top programming languages</p>
<p><a href="http://attractivechaos.github.io/plb/">Speed comparison</a> of programming languages</p>
<hr />
<p><strong>Update (November 2017).</strong> The release of new deep learning packages has made TSSB sort of obsolete. For instance, the H2O package natively supports several ways of features filtering and dimensionality reduction, as well as ensembles, both so far the strength of TSSB. H2O is supported with Zorro&#8217;s <strong>advise</strong> function. Still, the TSSB book by Davin Aronson is a valuable source of methods, approaches, and tips about machine learning for financial prediction.</p>
<p>Download links to the latest versions of Zorro and R are placed on the side bar. A brief tutorial to both Zorro an R is contained in the Zorro manual; a more comprehensive introduction into working with Zorro can be found in the <a href="https://www.createspace.com/7147886" target="_blank" rel="noopener noreferrer">Black Book</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/hackers-tools-zorro-and-r/feed/</wfw:commentRss>
			<slash:comments>19</slash:comments>
		
		
			</item>
		<item>
		<title>Money and How to Get It</title>
		<link>https://financial-hacker.com/money-and-how-to-get-it/</link>
					<comments>https://financial-hacker.com/money-and-how-to-get-it/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Wed, 02 Sep 2015 10:45:51 +0000</pubDate>
				<category><![CDATA[Introductory]]></category>
		<category><![CDATA[No Math]]></category>
		<category><![CDATA[Economy]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Money]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=62</guid>

					<description><![CDATA[Contrary to popular belief, money is no material good. It is created out of nothing by banks lending it. Therefore, for each newly created lot of money there&#8217;s the same amount of debt. You&#8217;re destroying the money by repaying your credits. Since this requires a higher sum due to interest and compound interest, and since &#8230; <a href="https://financial-hacker.com/money-and-how-to-get-it/" class="more-link">Continue reading<span class="screen-reader-text"> "Money and How to Get It"</span></a>]]></description>
										<content:encoded><![CDATA[<p>Contrary to popular belief, <strong>money</strong> is no material good. It is created out of nothing by banks lending it. Therefore, for each newly created lot of money there&#8217;s the same amount of <strong>debt</strong>. You&#8217;re destroying the money by repaying your credits. Since this requires a higher sum due to interest and compound interest, and since money is also permanently withdrawn from circulation by hoarding, the entire money supply must constantly grow. It must never shrink. If it still does, as in the 1930 economic crisis, loan defaults, bank crashes and bankruptcies are the result. The monetary system is therefore a classic <strong>Ponzi scheme</strong>.<span id="more-62"></span></p>
<p>Because the money amount always corresponds to the same amount of private and public debt, this debt amount also must inevitably grow, in spite of all the political lamentoes. Reducing public debt would either destroy money or increase private debt proportionately. This happened in fact in the United States around the turn of the millennium, when then-President <strong>Bill Clinton</strong> managed to get by without borrowing, and even achieved a budget surplus. Which caused interests to drop and banks to look elsewhere for distributing their money. The indirect result of Clinton&#8217;s good deed was a massive increase in private debt that eventually led to the mortgage crash of 2007.</p>
<h3>How to acquire it in large amounts</h3>
<p>Money is considered a good thing in almost all cultures. After all, it allows you to do the things you want, and &#8211; even more important &#8211; not to do things you don&#8217;t want to do. It thus represents freedom. You can get to it with different methods. The most obvious is taking away other people&#8217;s money. Here&#8217;s the Top Ten fortunes by known villains, according to Forbes (in US $):</p>
<ol>
<li>Hugo Drax &#8211; <strong>7.6 billion</strong></li>
<li>Auric Goldfinger &#8211; <strong>6.5 billion</strong></li>
<li>Max Zorin &#8211; <strong>5.3 billion</strong></li>
<li>Lex Luthor &#8211; <strong>4.7 billion</strong></li>
<li>Franz Sanchez &#8211; <strong>1 billion</strong></li>
<li>Ernst Stavro Blofeld &#8211; <strong>640 million</strong></li>
<li>Karl Stromberg &#8211; <strong>640 million</strong></li>
<li>Elektra King &#8211; <strong>420 million</strong></li>
<li>Francisco Scaramanga &#8211; <strong>115 million</strong></li>
<li>Dr. Julius No &#8211; <strong>110 million</strong></li>
</ol>
<p>But the most successful in money taking are not, as you might think, drug cartel bosses or leaders of criminal underground organizations, but <strong>presidents and other heads of state</strong>. They can take their share of money with no risk, since they need not fear the law. Here&#8217;s the Top Ten of the acquired fortunes by this way (in US $):</p>
<ol>
<li>Muammar Gaddafi, Libya &#8211; <strong>55 billion</strong></li>
<li>Hosni Mubarak, Egypt &#8211; <strong>50 billion</strong></li>
<li>Mohamed Suharto, Indonesia &#8211; <strong>25 billion</strong></li>
<li>Alexander Lukashenko, Belarus &#8211; <strong>12 billion</strong></li>
<li>Mobutu Sese Seko, Congo &#8211; <strong>7 billion</strong></li>
<li>Ben Ali, Tunisia &#8211; <strong>4 billion</strong></li>
<li>Gnassingbé Eyadéma, Togo &#8211; <strong>4 billion</strong></li>
<li>Obiang Nguema, Equatorial Guinea &#8211; <strong>3 billion</strong></li>
<li>Slobodan Milosevic, Serbia &#8211; <strong>1 billion</strong></li>
<li>&#8216;Baby Doc&#8217; Duvalier, Haiti &#8211; <strong>600 million</strong></li>
</ol>
<p>This list does naturally not include assets of monarchs such as the Sultan of Brunei, who have no need of pilfering because the country belongs to them by law anyway. Or of dictators like Wladimir Putin, whose estimated 125 billion booty (plus a 17,000 sqft palace) officially does not belong to them, but is kept for them by friendly oligarchs. The listed sums must also be considered in relation to the economy of the country. To bag 600 million in grinding poor Haiti is a much more impressive performance than the lousy one billion that Milosevic could siphon off in industrialized Serbia. But as long as you&#8217;re neither a supervillain, nor a head of state, nor both at the same time, you have no choice but to use other means to acquire money. There&#8217;s also the method of buying something cheap and selling it dear. Not as profitable as being a head of state, but it still can produce some handsome gains (annual income in US $):</p>
<ol>
<li>Jim Simons, Renaissance &#8211; <strong>1.7 billion</strong></li>
<li>Ken Griffin, Citadel &#8211; <strong>1.7 billion</strong></li>
<li>Raymond Dalio, Bridgewater &#8211; <strong>1.4 billion</strong></li>
<li>David Tepper, Apaloosa &#8211; <strong>1.4 billion</strong></li>
<li>Izzy Englander, Millenium &#8211; <strong>1.1 billion</strong></li>
<li>David Shaw, Shaw Group &#8211; <strong>750 million</strong></li>
<li>John Overdeck, Two Sigma &#8211; <strong>500 million</strong></li>
<li>David Siegel, Two Sigma &#8211; <strong>500 million</strong></li>
<li>Andreas Halvorsen, Viking &#8211; <strong>370 million</strong></li>
<li>Joseph Edelman, Perceptive &#8211; <strong>300 million</strong></li>
</ol>
<p>All in this list acquired their wealth with <a href="https://zorro-project.com/algotrading.php" target="_blank" rel="noopener">algorithmic trading</a>. Which is the topic of most of the rest of this blog. It does not produce any goods. But on the other hand, it does not steal from anyone. On the contrary, private, small-scale financial trading can boost demand and soften economic inequality. It can redistribute money from the rich to the poor. So it should be rewarded by the government, for instance by a tax exemption. Well, one can dream, at least&#8230;<a id="why"></a></p>
<h3>Why financial hacking?</h3>
<p>Part of my job is developing financial tools and trading systems for clients. So far we coded hundreds of trading strategies with all sorts of algorithms for all sorts of financial instruments. Some worked and fulfilled the client&#8217;s expectations. Some failed miserably. And some worked in the backtest, but not in live trading. Coming from a background of theoretical physics and computer game programming, I wondered why trading seems not to be an exact science at all. What is the difference between a successful and a doomed strategy? And how can you determine that before actually trading it?</p>
<p>On this blog I&#8217;ll attempt a <strong>hacking approach to algorithmic trading</strong>. Hacking is nothing illegal, it&#8217;s just a pragmatic way to solve problems. Hackers prefer experiment over theory. They don&#8217;t give a damn about the wisdom of gurus or authorities. So I&#8217;ll start with considering all praised trade systems worthless and all &#8220;trader&#8217;s wisdom&#8221; irrational and nonsense until proven otherwise. I will try to evaluate <strong>by systematic experimenting </strong>whether, why, when, and how algorithmic trading does work. My goal is to find out how it can be a reliable income source for a private trader. This might require complex statistical or machine learning algorithms &#8211; but that&#8217;s no big deal with today&#8217;s software tools. All scripts and software to the articles will be put up for download, so anyone interested can reproduce all the results and use the strategies. After all, successful private trading is for the common good.</p>
<p>As this blog is about algorithmic trading, I&#8217;m going to post here a lot of algorithms and source code. Naturally not any trader is able to read code. On the other hand, some basic code and math understanding is required for making sense of the articles. To go from zero to a full understanding of the articles on this blog, here&#8217;s a <a href="http://manual.zorro-project.com/links.htm" target="_blank" rel="noopener noreferrer">list of Useful Books</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/money-and-how-to-get-it/feed/</wfw:commentRss>
			<slash:comments>24</slash:comments>
		
		
			</item>
	</channel>
</rss>
