<?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>Put &#8211; The Financial Hacker</title>
	<atom:link href="https://financial-hacker.com/tag/put/feed/" rel="self" type="application/rss+xml" />
	<link>https://financial-hacker.com</link>
	<description>A new view on algorithmic trading</description>
	<lastBuildDate>Mon, 27 Oct 2025 08:51:47 +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>Put &#8211; The Financial Hacker</title>
	<link>https://financial-hacker.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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>
<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>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>
<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>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>
<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>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>
	</channel>
</rss>
