<?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>Gekko Quant – Quantitative Trading</title>
	<atom:link href="http://gekkoquant.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://gekkoquant.com</link>
	<description>Quantitative Trading, Statistical Arbitrage, Machine Learning and Binary Options</description>
	<lastBuildDate>Mon, 18 Mar 2013 01:39:00 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<item>
		<title>Analysis of returns after n consecutive up/down days &#8211; Predicting the Sign of Open to Close Returns</title>
		<link>http://gekkoquant.com/2013/03/18/analysis-of-returns-after-n-consecutive-updown-days-predicting-the-sign-of-open-to-close-returns/</link>
		<comments>http://gekkoquant.com/2013/03/18/analysis-of-returns-after-n-consecutive-updown-days-predicting-the-sign-of-open-to-close-returns/#comments</comments>
		<pubDate>Mon, 18 Mar 2013 01:39:00 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=372</guid>
		<description><![CDATA[This weekend I was spammed for a &#8220;binary option trading system with 90% accuracy&#8221;. The advert caught my curiosity  in essence it detailed a method that was a variation of the well known roulette playing strategy that mathematically guarantees a profit (assuming infinite &#8230; <a href="http://gekkoquant.com/2013/03/18/analysis-of-returns-after-n-consecutive-updown-days-predicting-the-sign-of-open-to-close-returns/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This weekend I was spammed for a &#8220;binary option trading system with 90% accuracy&#8221;. The advert caught my curiosity  in essence it detailed a method that was a variation of the well known roulette playing strategy that mathematically guarantees a profit (assuming infinite money, and no table limit).</p>
<p>Roulette Strategy</p>
<p>If you double your bet size after a loss and repeat the same bet you are guaranteed a profit, your next winning will cover all the preceding loses.</p>
<p>e.g Bet $1 on red, lose, Bet $2 on red, Win get $4 back ($2 is your stake, and $1 covers the loss from your first bet) giving $1 profit.</p>
<p>Exponential growth of lot size, no thanks <img src='http://gekkoquant.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Binary options are analogous to betting on red, they offer virtually fixed odds for up or down directional bets. Naturally I want to know whats is the maximum number of consecutive up or down days in the market, how much pain would I have to suffer with this strategy.</p>
<p><strong>Occurrences of n Consecutive Up or Down Days</strong></p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-consecutive-dir-vs-num-of-occurances.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-373" title="gspc consecutive dir vs num of occurances" src="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-consecutive-dir-vs-num-of-occurances.jpeg"  alt="" width="1366" height="696" /></a></p>
<p>Analysing the last 12 years of returns data for the S&amp;P 500, the maximum consecutive number of up days is 9 (occurred in 2004-2005), the maximum consecutive number of down days is -8 which, you guessed it, occurred in 2008-2009.</p>
<p>So 9 days of pain should we always short the direction of the market.</p>
<p>Instead of enduring the 9 days of draw down, it is interesting to see what the consecutive number of up/down days says about the probability the next day is an up day. The maximum likelihood probability of an up day is count(up days)/count(up and down days). Naturally we will condition this data on the consecutive number of up/down days.</p>
<p><strong>Consecutive Up or Down Days vs Maximum Likelihood Probability the next day is up</strong></p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-consecutive-dir-vs-prob-of-up-day.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-374" title="gspc consecutive dir vs prob of up day" src="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-consecutive-dir-vs-prob-of-up-day.jpeg"  alt="" width="1366" height="696" /></a></p>
<p>This data is fairly nice looking, for example in 2012-2013 there is a clear relationship. The more down days in a row the higher the likelihood of an up day. 6 down days implied the probability of an up day is 80%! I must raise a note of caution here, 6 down days in a row was seen less than 5 times in the year. Hence the probability estimate is based on 5 points and not statistically significant, perhaps looking at 5 years of returns might be better.</p>
<p>I appreciate that most people don&#8217;t trade binary options can we trade the index/stock out right, it is interesting to see what the consecutive number of up/down days says about future Open to Close Returns. The image below regresses Open to Close Returns (time t) with Consecutive Up/Down days (time t-1).</p>
<p><strong>Consecutive Up or Down Days vs Next Day Open to Close Returns</strong></p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-boxplot-consecutive-dir-vs-open-close-return.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-375" title="gspc boxplot consecutive dir vs open close return" src="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-boxplot-consecutive-dir-vs-open-close-return.jpeg"  alt="" width="1366" height="696" /></a></p>
<div>Very disappointing chart, doesn&#8217;t really show much relationship between returns and consecutive up/down days. For some of the data points the up move is more probable than a down move but the magnitude of the up moves are significantly smaller than that of the down moves. These charts vary greatly by asset class and by security, single stocks have much more favorable plots.</div>
<p><strong>Prediction Accuracy</strong></p>
<p>The plot below shows the accuracy of using this maximum likelihood estimate approach. The model takes the last 250 days of returns and calculates the probability of an up move given that the current day has seen n consecutive days of trading. If the prob of an up move or is over a certain threshold go long, if its below a certain threshold go short.</p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-cumsum-of-prediction-performance-p0.7.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-377" title="gspc cumsum of prediction performance p0.7" src="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-cumsum-of-prediction-performance-p0.7.jpeg"  alt="" width="1366" height="696" /></a></p>
<p><strong>Heatmap of Accuracy vs Model Parameters</strong></p>
<div> <a href="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-heatmap.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-378" title="gspc heatmap" src="http://gekkoquant.com/wp-content/uploads/2013/03/gspc-heatmap.jpeg"  alt="" width="1366" height="696" /></a></div>
<p>The histogram on the heatmap shows that approximately half of the parameter combinations can predict the direction with accuracy greater than 50%.</p>
<p><strong>Final Comments</strong></p>
<p>The beauty of this approach is that it&#8217;s simple, it can be applied to any asset class but most importantly it can be applied across different time frames.</p>
<p>Onto the code:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p372code2'); return false;">View Code</a> RSPLUS</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p3722"><td class="code" id="p372code2"><pre class="rsplus" style="font-family:monospace;"><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;quantmod&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;reshape&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;gplots&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Control Parameters</span>
dataStartDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2000-01-01&quot;</span><span style="color: #080;">&#41;</span>
symbol<span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;^GSPC&quot;</span>
longThreshold <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.70</span>  <span style="color: #228B22;">#If the probability of an upday is greater than this limit go long</span>
shortThreshold <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">1</span><span style="color: #080;">-</span>longThreshold  <span style="color: #228B22;">#If the probability of an upday is lower than this limit go short</span>
nLookback<span style="color: #080;">&lt;-</span><span style="color: #ff0000;">250</span> <span style="color: #228B22;">#Days to look back when generating the rolling probability distribution (approx 250 trading days in a year)</span>
&nbsp;
<span style="color: #228B22;">#Function to turn a boolean vector into a vector containing the consecutive num of trues or falses seen</span>
<span style="color: #228B22;">#Will be used to calculate the consecutive number of up and down days</span>
consecutiveTruesExtractor <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">data</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
        genNumOfConsecutiveTrues <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>x, y<span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span> <span style="color: #080;">&#40;</span>x<span style="color: #080;">+</span>y<span style="color: #080;">&#41;</span><span style="color: #080;">*</span>y  <span style="color: #080;">&#125;</span> <span style="color: #228B22;">#Y is either 0 or 1</span>
        upDaysCount <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/Reduce.html"><span style="color: #0000FF; font-weight: bold;">Reduce</span></a><span style="color: #080;">&#40;</span>genNumOfConsecutiveTrues,<span style="color: #0000FF; font-weight: bold;">data</span>,accumulate<span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span>
        upDaysCount <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.vector.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">vector</span></span></a><span style="color: #080;">&#40;</span>Lag<span style="color: #080;">&#40;</span>upDaysCount<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
        upDaysCount<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>upDaysCount<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0</span>
&nbsp;
&nbsp;
        downDaysCount <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/Reduce.html"><span style="color: #0000FF; font-weight: bold;">Reduce</span></a><span style="color: #080;">&#40;</span>genNumOfConsecutiveTrues,<span style="color: #080;">!</span><span style="color: #0000FF; font-weight: bold;">data</span>,accumulate<span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span>
        downDaysCount <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.vector.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">vector</span></span></a><span style="color: #080;">&#40;</span>Lag<span style="color: #080;">&#40;</span>downDaysCount<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
        downDaysCount<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>downDaysCount<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0</span>
        consecutiveTruesExtractor <span style="color: #080;">&lt;-</span> upDaysCount<span style="color: #080;">-</span>downDaysCount
<span style="color: #080;">&#125;</span>
&nbsp;
<span style="color: #228B22;">#Function to plot data and add regression line</span>
doPlot <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>x,y,<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a>,xlabel,ylabel,ylimit<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  x<span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.vector.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">vector</span></span></a><span style="color: #080;">&#40;</span>x<span style="color: #080;">&#41;</span>
  y<span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.vector.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">vector</span></span></a><span style="color: #080;">&#40;</span>y<span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/boxplot.html"><span style="color: #0000FF; font-weight: bold;">boxplot</span></a><span style="color: #080;">&#40;</span>y~x,main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a>, xlab<span style="color: #080;">=</span>xlabel,ylab<span style="color: #080;">=</span>ylabel,ylim<span style="color: #080;">=</span>ylimit<span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/abline.html"><span style="color: #0000FF; font-weight: bold;">abline</span></a><span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">lm</span><span style="color: #080;">&#40;</span>y~x<span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span>,lwd<span style="color: #080;">=</span><span style="color: #ff0000;">1.5</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
<span style="color: #228B22;">#Function to calculate the percentage of updays from returns set</span>
calcPercentageOfUpdaysFromReturnsSet <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">data</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  calcPercentageOfUpdaysFromReturnsSet <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sum.html"><span style="color: #0000FF; font-weight: bold;">sum</span></a><span style="color: #080;">&#40;</span>data<span style="color: #080;">&gt;</span><span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span><span style="color: #080;">/</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">data</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
<span style="color: #228B22;">#Function takes a set of returns and consecutive up down day data and aggregates it into a probability distribution</span>
<span style="color: #228B22;">#Generated a matrix of consecutive Direction vs prob of up move</span>
generateProbOfUpDayDistribution <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>dataBlock<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
&nbsp;
 y <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/by.html"><span style="color: #0000FF; font-weight: bold;">by</span></a><span style="color: #080;">&#40;</span>dataBlock<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">&quot;OpClRet&quot;</span><span style="color: #080;">&#93;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/list.html"><span style="color: #0000FF; font-weight: bold;">list</span></a><span style="color: #080;">&#40;</span>ConsecutiveDir <span style="color: #080;">=</span> dataBlock<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">&quot;ConsecutiveDir&quot;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>,calcPercentageOfUpdaysFromReturnsSet<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Prob of upmove</span>
 x <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.numeric.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">numeric</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rownames.html"><span style="color: #0000FF; font-weight: bold;">rownames</span></a><span style="color: #080;">&#40;</span>y<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
&nbsp;
 res <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>x,y<span style="color: #080;">&#41;</span>
 <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>res<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;ConsecutiveDir&quot;</span>,<span style="color: #ff0000;">&quot;Prob&quot;</span><span style="color: #080;">&#41;</span>
 generateProbOfUpDayDistribution <span style="color: #080;">&lt;-</span> res
<span style="color: #080;">&#125;</span>
&nbsp;
<span style="color: #228B22;">#Given current consecutive up down day data, what is the probability the current day is an up day</span>
<span style="color: #228B22;">#For use with the rollapply function (since needs to use the past n days worth of data for generating probability distribution)</span>
probOfUpDayForUseWithRollApply <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>dataBlock<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  <span style="color: #0000FF; font-weight: bold;">dist</span> <span style="color: #080;">&lt;-</span> generateProbOfUpDayDistribution<span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">head</span><span style="color: #080;">&#40;</span>dataBlock,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Use head to drop the last row, prevents a lookforward issue</span>
&nbsp;
  currentConsecutiveRun <span style="color: #080;">&lt;-</span> last<span style="color: #080;">&#40;</span>dataBlock<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">&quot;ConsecutiveDir&quot;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
  probOfUpDay <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">dist</span><span style="color: #080;">&#91;</span><span style="color: #0000FF; font-weight: bold;">dist</span><span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">&quot;ConsecutiveDir&quot;</span><span style="color: #080;">&#93;</span> <span style="color: #080;">==</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rep.html"><span style="color: #0000FF; font-weight: bold;">rep</span></a><span style="color: #080;">&#40;</span>coredata<span style="color: #080;">&#40;</span>currentConsecutiveRun<span style="color: #080;">&#41;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">dist</span><span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">&quot;ConsecutiveDir&quot;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>,<span style="color: #ff0000;">&quot;Prob&quot;</span><span style="color: #080;">&#93;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span><span style="color: #080;">!</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.numeric.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">numeric</span></span></a><span style="color: #080;">&#40;</span>probOfUpDay<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span>probOfUpDay <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.5</span> <span style="color: #080;">&#125;</span> <span style="color: #228B22;">#Never this many consecutive days before, dont know what will happen make up and down events equally likely</span>
  <span style="color: #228B22;">#print(paste(&quot;Current Run:&quot;,coredata(currentConsecutiveRun),&quot;Prob of up day:&quot;,probOfUpDay ))</span>
  probOfUpDayForUseWithRollApply <span style="color: #080;">&lt;-</span> probOfUpDay
<span style="color: #080;">&#125;</span>
&nbsp;
<span style="color: #228B22;">#Just a quick test to check that the consecutiveTruesExtractor is working as expected</span>
<span style="color: #228B22;">#Define the input data, and define the expected output</span>
<span style="color: #228B22;">#Check that the output of the function equals the expected output</span>
<span style="color: #0000FF; font-weight: bold;">data</span> <span style="color: #080;">&lt;-</span>           <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0</span>, <span style="color: #ff0000;">0</span>, <span style="color: #ff0000;">0</span>, <span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">0</span>, <span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">0</span>,<span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span>  <span style="color: #228B22;">#0 is down day, 1 is up day</span>
expectedOutput <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">2</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">3</span>,<span style="color: #ff0000;">1</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">2</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span>
res <span style="color: #080;">&lt;-</span> consecutiveTruesExtractor<span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">data</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/identical.html"><span style="color: #0000FF; font-weight: bold;">identical</span></a><span style="color: #080;">&#40;</span>res,expectedOutput<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Match consecutiveTruesExtractor is correct&quot;</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span> <span style="color: #0000FF; font-weight: bold;">else</span> <span style="color: #080;">&#123;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Error consecutiveTruesExtractor contains bugs&quot;</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
<span style="color: #228B22;">#Download the data</span>
symbolData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/new.env.html"><span style="color: #0000FF; font-weight: bold;">new.<span style="">env</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Make a new environment for quantmod to store data in</span>
getSymbols<span style="color: #080;">&#40;</span>symbol, env <span style="color: #080;">=</span> symbolData, src <span style="color: #080;">=</span> <span style="color: #ff0000;">&quot;yahoo&quot;</span>, from <span style="color: #080;">=</span> dataStartDate<span style="color: #080;">&#41;</span>
mktdata <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/eval.html"><span style="color: #0000FF; font-weight: bold;">eval</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/parse.html"><span style="color: #0000FF; font-weight: bold;">parse</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/text.html"><span style="color: #0000FF; font-weight: bold;">text</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;symbolData$&quot;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sub.html"><span style="color: #0000FF; font-weight: bold;">sub</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;^&quot;</span>,<span style="color: #ff0000;">&quot;&quot;</span>,symbol,fixed<span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
opClRet <span style="color: #080;">&lt;-</span> <span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">/</span>Op<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">-</span><span style="color: #ff0000;">1</span>
consecutiveDir <span style="color: #080;">&lt;-</span> consecutiveTruesExtractor<span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span>opClRet<span style="color: #080;">&gt;</span><span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
completeData<span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>opClRet,consecutiveDir<span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>completeData<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;OpClRet&quot;</span>,<span style="color: #ff0000;">&quot;ConsecutiveDir&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
<span style="color: #228B22;">#Plot of consecutive up down days vs next day Open Close Returns</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>oma<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0</span>,<span style="color: #ff0000;">0</span>,<span style="color: #ff0000;">2</span>,<span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>mfrow<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">3</span>,<span style="color: #ff0000;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/for.html"><span style="color: #0000FF; font-weight: bold;">for</span></a><span style="color: #080;">&#40;</span>i <span style="color: #0000FF; font-weight: bold;">in</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/seq.html"><span style="color: #0000FF; font-weight: bold;">seq</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">2012</span>,<span style="color: #ff0000;">2004</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  windowedData <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">window</span><span style="color: #080;">&#40;</span>completeData,<span style="color: #0000FF; font-weight: bold;">start</span><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span>i,<span style="color: #ff0000;">&quot;-01-01&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>,<span style="color: #0000FF; font-weight: bold;">end</span><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span>i<span style="color: #080;">+</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">&quot;-01-01&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
  doPlot<span style="color: #080;">&#40;</span>windowedData$ConsecutiveDir,windowedData$OpClRet,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Consecutive Up / Down days vs Open close Return (&quot;</span>,i,<span style="color: #ff0000;">&quot;,&quot;</span>,i<span style="color: #080;">+</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">&quot;)&quot;</span><span style="color: #080;">&#41;</span>,<span style="color: #ff0000;">&quot;Consecutive Up or Down days&quot;</span>,<span style="color: #ff0000;">&quot;Open Close Returns&quot;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #080;">-</span><span style="color: #ff0000;">0.07</span>,<span style="color: #ff0000;">0.07</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a><span style="color: #080;">&#40;</span>main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Symbol&quot;</span>,symbol<span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/outer.html"><span style="color: #0000FF; font-weight: bold;">outer</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/T.html"><span style="color: #0000FF; font-weight: bold;">T</span></a><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Plot of consecutive up down days vs the maximum likelihood probability that the next day is an up day</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>oma<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0</span>,<span style="color: #ff0000;">0</span>,<span style="color: #ff0000;">2</span>,<span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>mfrow<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">3</span>,<span style="color: #ff0000;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/for.html"><span style="color: #0000FF; font-weight: bold;">for</span></a><span style="color: #080;">&#40;</span>i <span style="color: #0000FF; font-weight: bold;">in</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/seq.html"><span style="color: #0000FF; font-weight: bold;">seq</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">2012</span>,<span style="color: #ff0000;">2004</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  windowedData <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">window</span><span style="color: #080;">&#40;</span>completeData,<span style="color: #0000FF; font-weight: bold;">start</span><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span>i,<span style="color: #ff0000;">&quot;-01-01&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>,<span style="color: #0000FF; font-weight: bold;">end</span><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span>i<span style="color: #080;">+</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">&quot;-01-01&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
  y <span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/by.html"><span style="color: #0000FF; font-weight: bold;">by</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.vector.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">vector</span></span></a><span style="color: #080;">&#40;</span>windowedData$OpClRet<span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/list.html"><span style="color: #0000FF; font-weight: bold;">list</span></a><span style="color: #080;">&#40;</span>ConsecutiveDir <span style="color: #080;">=</span> windowedData$ConsecutiveDir<span style="color: #080;">&#41;</span>,calcPercentageOfUpdaysFromReturnsSet<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Prob of upmove</span>
  x <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.numeric.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">numeric</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rownames.html"><span style="color: #0000FF; font-weight: bold;">rownames</span></a><span style="color: #080;">&#40;</span>y<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Consecutive up or down days</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>x,y<span style="color: #080;">&#41;</span>,main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Consecutive Up / Down days vs Next day Dir (&quot;</span>,i,<span style="color: #ff0000;">&quot;,&quot;</span>,i<span style="color: #080;">+</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">&quot;)&quot;</span><span style="color: #080;">&#41;</span>, xlab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Consecutive Up or Down days&quot;</span>,ylab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Conditional Probability of an Up day&quot;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/abline.html"><span style="color: #0000FF; font-weight: bold;">abline</span></a><span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">lm</span><span style="color: #080;">&#40;</span>y~x<span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span>,lwd<span style="color: #080;">=</span><span style="color: #ff0000;">1.5</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a><span style="color: #080;">&#40;</span>main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Symbol&quot;</span>,symbol<span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/outer.html"><span style="color: #0000FF; font-weight: bold;">outer</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/T.html"><span style="color: #0000FF; font-weight: bold;">T</span></a><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Plot of consecutive up down days vs the number of occurences seen</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>oma<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0</span>,<span style="color: #ff0000;">0</span>,<span style="color: #ff0000;">2</span>,<span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>mfrow<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">3</span>,<span style="color: #ff0000;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/for.html"><span style="color: #0000FF; font-weight: bold;">for</span></a><span style="color: #080;">&#40;</span>i <span style="color: #0000FF; font-weight: bold;">in</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/seq.html"><span style="color: #0000FF; font-weight: bold;">seq</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">2012</span>,<span style="color: #ff0000;">2004</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  windowedData <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">window</span><span style="color: #080;">&#40;</span>completeData,<span style="color: #0000FF; font-weight: bold;">start</span><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span>i,<span style="color: #ff0000;">&quot;-01-01&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>,<span style="color: #0000FF; font-weight: bold;">end</span><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span>i<span style="color: #080;">+</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">&quot;-01-01&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
  y <span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/abs.html"><span style="color: #0000FF; font-weight: bold;">abs</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/by.html"><span style="color: #0000FF; font-weight: bold;">by</span></a><span style="color: #080;">&#40;</span>windowedData$ConsecutiveDir,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/list.html"><span style="color: #0000FF; font-weight: bold;">list</span></a><span style="color: #080;">&#40;</span>ConsecutiveDir <span style="color: #080;">=</span> windowedData$ConsecutiveDir<span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sum.html"><span style="color: #0000FF; font-weight: bold;">sum</span></a><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Count the number of occurences of each consecutive run</span>
  x <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.numeric.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">numeric</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rownames.html"><span style="color: #0000FF; font-weight: bold;">rownames</span></a><span style="color: #080;">&#40;</span>y<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>y,xaxt<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;n&quot;</span>,main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Consecutive Up / Down days vs Next day Dir (&quot;</span>,i,<span style="color: #ff0000;">&quot;,&quot;</span>,i<span style="color: #080;">+</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">&quot;)&quot;</span><span style="color: #080;">&#41;</span>, xlab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Consecutive Up or Down days&quot;</span>,ylab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Occurences of consecutive run&quot;</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;l&quot;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/axis.html"><span style="color: #0000FF; font-weight: bold;">axis</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">1</span>, at<span style="color: #080;">=</span><span style="color: #ff0000;">1</span><span style="color: #080;">:</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span>x<span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/labels.html"><span style="color: #0000FF; font-weight: bold;">labels</span></a><span style="color: #080;">=</span>x<span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a><span style="color: #080;">&#40;</span>main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Symbol&quot;</span>,symbol<span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/outer.html"><span style="color: #0000FF; font-weight: bold;">outer</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/T.html"><span style="color: #0000FF; font-weight: bold;">T</span></a><span style="color: #080;">&#41;</span>
&nbsp;
predictionPerformance <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>completeData,longThreshold,shortThreshold,nLookback,displayPlot<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
    <span style="color: #228B22;">#Calcuate the probabiliy of an up day using a nLookback day window</span>
    rollingProbOfAnUpday <span style="color: #080;">&lt;-</span> rollapply<span style="color: #080;">&#40;</span>completeData,FUN<span style="color: #080;">=</span>probOfUpDayForUseWithRollApply,align<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;right&quot;</span>,fill<span style="color: #080;">=</span>NA,width<span style="color: #080;">=</span>nLookback,by.<span style="">column</span><span style="color: #080;">=</span>FALSE<span style="color: #080;">&#41;</span>
    rollingProbOfAnUpday <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span>rollingProbOfAnUpday<span style="color: #080;">&#41;</span>
    <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">head</span><span style="color: #080;">&#40;</span>rollingProbOfAnUpday<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
    <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>rollingProbOfAnUpday<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;ProbTodayIsAnUpDay&quot;</span>
    completeData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>completeData,rollingProbOfAnUpday<span style="color: #080;">&#41;</span>
&nbsp;
    suggestedTradeDir <span style="color: #080;">&lt;-</span> rollingProbOfAnUpday <span style="color: #228B22;">#Just to copy the structure</span>
    <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>suggestedTradeDir<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;SuggestedTradeDir&quot;</span>
    suggestedTradeDir<span style="color: #080;">&#91;</span>rollingProbOfAnUpday<span style="color: #080;">&gt;</span>longThreshold<span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">1</span>  <span style="color: #228B22;">#Long Trade</span>
    suggestedTradeDir<span style="color: #080;">&#91;</span>rollingProbOfAnUpday<span style="color: #080;">&lt;</span>shortThreshold<span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #080;">-</span><span style="color: #ff0000;">1</span> <span style="color: #228B22;">#Short Trade</span>
    suggestedTradeDir<span style="color: #080;">&#91;</span>rollingProbOfAnUpday<span style="color: #080;">&lt;</span>longThreshold <span style="color: #080;">&amp;</span> rollingProbOfAnUpday<span style="color: #080;">&gt;</span>shortThreshold<span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0</span> <span style="color: #228B22;">#Do nothing</span>
    completeData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>completeData,suggestedTradeDir<span style="color: #080;">&#41;</span>
&nbsp;
    isPredictionCorrect <span style="color: #080;">&lt;-</span> suggestedTradeDir <span style="color: #228B22;">#Just to copy structure</span>
    isPredictionCorrect <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sign.html"><span style="color: #0000FF; font-weight: bold;">sign</span></a><span style="color: #080;">&#40;</span>completeData$SuggestedTradeDir <span style="color: #080;">*</span> completeData$OpClRet<span style="color: #080;">&#41;</span> <span style="color: #228B22;">#sign(0) is 0 so will capture no trades as well</span>
    isPredictionCorrect<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0</span>
    isPredictionCorrect<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.nan.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">nan</span></span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0</span>
    <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span>displayPlot<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
      <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
      <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cumsum.html"><span style="color: #0000FF; font-weight: bold;">cumsum</span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#41;</span>, main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Market Direction Prediction Performance for&quot;</span>,symbol,<span style="color: #ff0000;">&quot;(Probability Threshold, Long=&quot;</span>,longThreshold,<span style="color: #ff0000;">&quot;Short=&quot;</span>,shortThreshold,<span style="color: #ff0000;">&quot;Lookback=&quot;</span>,nLookback,<span style="color: #ff0000;">&quot;)&quot;</span><span style="color: #080;">&#41;</span>,xlab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Date&quot;</span>,ylab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Cumulative Sum of Correct (+1) and Wrong(-1) Predictions&quot;</span><span style="color: #080;">&#41;</span>
      msgIncorrectPred <span style="color: #080;">&lt;-</span> <span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Incorrect Predictions (out of the days when a prediction was made)&quot;</span>,<span style="color: #ff0000;">100</span><span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/abs.html"><span style="color: #0000FF; font-weight: bold;">abs</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sum.html"><span style="color: #0000FF; font-weight: bold;">sum</span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#91;</span>isPredictionCorrect<span style="color: #080;">==-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">/</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#91;</span>isPredictionCorrect<span style="color: #080;">!=</span><span style="color: #ff0000;">0</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>,<span style="color: #ff0000;">&quot;%&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
      msgCorrectPred <span style="color: #080;">&lt;-</span> <span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Correct Predictions (out of the days when a prediction was made)&quot;</span>,<span style="color: #ff0000;">100</span><span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sum.html"><span style="color: #0000FF; font-weight: bold;">sum</span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#91;</span>isPredictionCorrect<span style="color: #080;">==</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">/</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#91;</span>isPredictionCorrect<span style="color: #080;">!=</span><span style="color: #ff0000;">0</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>,<span style="color: #ff0000;">&quot;%&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
      msgPercOfDaysWithPred <span style="color: #080;">&lt;-</span> <span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Percent of days when a prediction was made&quot;</span>,<span style="color: #ff0000;">100</span><span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sum.html"><span style="color: #0000FF; font-weight: bold;">sum</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/abs.html"><span style="color: #0000FF; font-weight: bold;">abs</span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#91;</span>isPredictionCorrect<span style="color: #080;">!=</span><span style="color: #ff0000;">0</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">/</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#41;</span>,<span style="color: #ff0000;">&quot;%&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
      <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/legend.html"><span style="color: #0000FF; font-weight: bold;">legend</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;topleft&quot;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span>msgIncorrectPred,msgCorrectPred,msgPercOfDaysWithPred<span style="color: #080;">&#41;</span>,bg<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;lightblue&quot;</span><span style="color: #080;">&#41;</span>
    <span style="color: #080;">&#125;</span>
    predictionPerformance <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sum.html"><span style="color: #0000FF; font-weight: bold;">sum</span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#91;</span>isPredictionCorrect<span style="color: #080;">==</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">/</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span>isPredictionCorrect<span style="color: #080;">&#91;</span>isPredictionCorrect<span style="color: #080;">!=</span><span style="color: #ff0000;">0</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
&nbsp;
predictionPerformance<span style="color: #080;">&#40;</span>completeData,longThreshold,shortThreshold,nLookback,TRUE<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Parameter search</span>
resultsMat <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/matrix.html"><span style="color: #0000FF; font-weight: bold;">matrix</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/numeric.html"><span style="color: #0000FF; font-weight: bold;">numeric</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span>, <span style="color: #ff0000;">0</span>,<span style="color: #ff0000;">3</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>resultsMat<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Lookback&quot;</span>,<span style="color: #ff0000;">&quot;LongProbThreshold&quot;</span>,<span style="color: #ff0000;">&quot;Accuracy&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/for.html"><span style="color: #0000FF; font-weight: bold;">for</span></a><span style="color: #080;">&#40;</span>nLookback <span style="color: #0000FF; font-weight: bold;">in</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/seq.html"><span style="color: #0000FF; font-weight: bold;">seq</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">30</span>,<span style="color: #ff0000;">240</span>,<span style="color: #ff0000;">30</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/for.html"><span style="color: #0000FF; font-weight: bold;">for</span></a><span style="color: #080;">&#40;</span>longThreshold <span style="color: #0000FF; font-weight: bold;">in</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/seq.html"><span style="color: #0000FF; font-weight: bold;">seq</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0.55</span>,<span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">0.05</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
    shortThreshold <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">1</span><span style="color: #080;">-</span>longThreshold
    accuracy <span style="color: #080;">&lt;-</span> predictionPerformance<span style="color: #080;">&#40;</span>completeData,longThreshold,shortThreshold,nLookback<span style="color: #080;">*</span><span style="color: #ff0000;">2</span>,FALSE<span style="color: #080;">&#41;</span>
    resultsMat <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rbind.html"><span style="color: #0000FF; font-weight: bold;">rbind</span></a><span style="color: #080;">&#40;</span>resultsMat,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>nLookback,longThreshold,accuracy<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
    <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span>resultsMat<span style="color: #080;">&#41;</span>
  <span style="color: #080;">&#125;</span>
<span style="color: #080;">&#125;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span>resultsMat<span style="color: #080;">&#41;</span>
tt <span style="color: #080;">&lt;-</span><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.data.frame.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">data</span>.<span style="">frame</span></span></a><span style="color: #080;">&#40;</span>cast<span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.data.frame.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">data</span>.<span style="">frame</span></span></a><span style="color: #080;">&#40;</span>resultsMat<span style="color: #080;">&#41;</span>,Lookback~LongProbThreshold<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rownames.html"><span style="color: #0000FF; font-weight: bold;">rownames</span></a><span style="color: #080;">&#40;</span>tt<span style="color: #080;">&#41;</span><span style="color: #080;">&lt;-</span>tt<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">&quot;Lookback&quot;</span><span style="color: #080;">&#93;</span>
heatmap.2<span style="color: #080;">&#40;</span>tt<span style="color: #080;">&#91;</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span>,key<span style="color: #080;">=</span>TRUE,Rowv<span style="color: #080;">=</span>FALSE,Colv<span style="color: #080;">=</span>FALSE,xlab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Prob of Up Day Threshold&quot;</span>,ylab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Lookback&quot;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/trace.html"><span style="color: #0000FF; font-weight: bold;">trace</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;none&quot;</span>,main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Prediction Accuracy (correct predictions as % of all predictions) for &quot;</span>,symbol<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span></pre></td></tr></table></div>

<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2013/03/18/analysis-of-returns-after-n-consecutive-updown-days-predicting-the-sign-of-open-to-close-returns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Skewness Revisited</title>
		<link>http://gekkoquant.com/2013/03/16/skewness-revisited/</link>
		<comments>http://gekkoquant.com/2013/03/16/skewness-revisited/#comments</comments>
		<pubDate>Sat, 16 Mar 2013 00:55:43 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=367</guid>
		<description><![CDATA[In my last post http://gekkoquant.com/2013/03/03/trend-following-skewness-signal/ I suggested that measuring the skewness of asset returns can possibly be used to identify trends. Or mathematically more accurately put, it can identify when the return distribution is symmetric and hence NOT in a trending environment (assuming returns are Gaussian with 0 &#8230; <a href="http://gekkoquant.com/2013/03/16/skewness-revisited/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In my last post <a title="trend following using a skewness signal" href="http://gekkoquant.com/2013/03/03/trend-following-skewness-signal/">http://gekkoquant.com/2013/03/03/trend-following-skewness-signal/</a> I suggested that measuring the skewness of asset returns can possibly be used to identify trends. Or mathematically more accurately put, it can identify when the return distribution is symmetric and hence NOT in a trending environment (assuming returns are Gaussian with 0 mean).</p>
<p>This post presents a simple regression of Skewness vs Asset returns. The skewness is calculated at time t using OpenCloseReturns[t-1,t-2,.....,t-lookback]. It is then regressed against OpenCloseReturn[t]. Where t donates today, and t-1 donates yesterday.</p>
<p>The data set is 2000 to present.</p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2013/03/skewness-returns-regression.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-369" title="skewness returns regression" src="http://gekkoquant.com/wp-content/uploads/2013/03/skewness-returns-regression.jpeg"  alt="" width="1366" height="696" /></a></p>
<p>The red line in the above plot is a linear regression. It&#8217;s clear to see that the skewness doesn&#8217;t explain the Open Close Returns. I must eat humble pie, the returns seen in the previous post are down to a lucky parameter selection. Thanks must go to Pietro for testing over a longer period.</p>
<p>Onto the code:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p367code4'); return false;">View Code</a> RSPLUS</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p3674"><td class="code" id="p367code4"><pre class="rsplus" style="font-family:monospace;"><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;quantmod&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;PerformanceAnalytics&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span>e1071<span style="color: #080;">&#41;</span>     <span style="color: #228B22;">#For the skewness command</span>
&nbsp;
&nbsp;
<span style="color: #228B22;">#Script parameters</span>
symbol <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;^GSPC&quot;</span>     <span style="color: #228B22;">#Symbol</span>
&nbsp;
<span style="color: #228B22;">#Specify dates for downloading data</span>
startDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2000-01-01&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Specify what date to get the prices from</span>
symbolData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/new.env.html"><span style="color: #0000FF; font-weight: bold;">new.<span style="">env</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Make a new environment for quantmod to store data in</span>
getSymbols<span style="color: #080;">&#40;</span>symbol, env <span style="color: #080;">=</span> symbolData, src <span style="color: #080;">=</span> <span style="color: #ff0000;">&quot;yahoo&quot;</span>, from <span style="color: #080;">=</span> startDate<span style="color: #080;">&#41;</span>
mktdata <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/eval.html"><span style="color: #0000FF; font-weight: bold;">eval</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/parse.html"><span style="color: #0000FF; font-weight: bold;">parse</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/text.html"><span style="color: #0000FF; font-weight: bold;">text</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;symbolData$&quot;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sub.html"><span style="color: #0000FF; font-weight: bold;">sub</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;^&quot;</span>,<span style="color: #ff0000;">&quot;&quot;</span>,symbol,fixed<span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
mktdata <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">head</span><span style="color: #080;">&#40;</span>mktdata,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Hack to fix some stupid duplicate date problem with yahoo</span>
OpClRet  <span style="color: #080;">&lt;-</span> <span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">/</span>Op<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>    <span style="color: #080;">-</span> <span style="color: #ff0000;">1</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>OpClRet<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;OpClRet&quot;</span>
mktdata <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>mktdata,OpClRet<span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
getSkewnessFromReturns <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>mktdata,skewLookback<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
   <span style="color: #228B22;">#Calculate the skew</span>
  rollingSkew <span style="color: #080;">&lt;-</span> Lag<span style="color: #080;">&#40;</span>rollapply<span style="color: #080;">&#40;</span>mktdata$OpClRet ,FUN<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;skewness&quot;</span>,width<span style="color: #080;">=</span>skewLookback, align<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;right&quot;</span>,na.<span style="">pad</span><span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span>
   <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>rollingSkew<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;Skew&quot;</span>
  getSkewnessFromReturns <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">na.<span style="">omit</span></span><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>mktdata$OpClRet,rollingSkew<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>mfrow<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">3</span>,<span style="color: #ff0000;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
startSkew <span style="color: #080;">&lt;-</span><span style="color: #ff0000;">30</span>
stepSize <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">30</span>
numOfSteps <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">9</span>
&nbsp;
doPlot <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>x,y,<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a>,xlabel,ylabel<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  <span style="color: #228B22;">#Function to plot data and add regression line</span>
  plotData <span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>x,y<span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">head</span><span style="color: #080;">&#40;</span>plotData<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>plotData<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;x&quot;</span>,<span style="color: #ff0000;">&quot;y&quot;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>coredata<span style="color: #080;">&#40;</span>plotData<span style="color: #080;">&#41;</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;p&quot;</span>,main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a>, xlab<span style="color: #080;">=</span>xlabel,ylab<span style="color: #080;">=</span>ylabel<span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/abline.html"><span style="color: #0000FF; font-weight: bold;">abline</span></a><span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">lm</span><span style="color: #080;">&#40;</span>y~x<span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span>,lwd<span style="color: #080;">=</span><span style="color: #ff0000;">1.5</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/for.html"><span style="color: #0000FF; font-weight: bold;">for</span></a><span style="color: #080;">&#40;</span>i <span style="color: #0000FF; font-weight: bold;">in</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/seq.html"><span style="color: #0000FF; font-weight: bold;">seq</span></a><span style="color: #080;">&#40;</span>startSkew,numOfSteps<span style="color: #080;">*</span>stepSize,stepSize<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
dat <span style="color: #080;">&lt;-</span> getSkewnessFromReturns<span style="color: #080;">&#40;</span>mktdata,i<span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>dat<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;OpClRet&quot;</span>,<span style="color: #ff0000;">&quot;Skew&quot;</span><span style="color: #080;">&#41;</span>
doPlot<span style="color: #080;">&#40;</span>dat$Skew,dat$OpClRet,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Skewness vs Open Close Returns (lookback=&quot;</span>,i,<span style="color: #ff0000;">&quot;)&quot;</span><span style="color: #080;">&#41;</span>,<span style="color: #ff0000;">&quot;Skewness&quot;</span>,<span style="color: #ff0000;">&quot;Open Close Returns&quot;</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span></pre></td></tr></table></div>

<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2013/03/16/skewness-revisited/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>$20mm seed capital tournament, “The Sharpe Ratio Shootout”</title>
		<link>http://gekkoquant.com/2013/03/09/20mm-seed-capital-tournament-the-sharpe-ratio-shootout/</link>
		<comments>http://gekkoquant.com/2013/03/09/20mm-seed-capital-tournament-the-sharpe-ratio-shootout/#comments</comments>
		<pubDate>Sat, 09 Mar 2013 14:00:20 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=363</guid>
		<description><![CDATA[Hi, I&#8217;ve been asked to advertise this seed capital tournament. I get asked to advertise all sorts of things but this looks very promising for beginner quant traders to launch their careers. Looking forwards to competing against some of you &#8230; <a href="http://gekkoquant.com/2013/03/09/20mm-seed-capital-tournament-the-sharpe-ratio-shootout/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hi, I&#8217;ve been asked to advertise this seed capital tournament. I get asked to advertise all sorts of things but this looks very promising for beginner quant traders to launch their careers.</p>
<p>Looking forwards to competing against some of you <img src='http://gekkoquant.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Announcing: $20mm seed capital tournament, “The Sharpe Ratio Shootout” Registration ends March 15<sup>th</sup>, 2013.</strong></p>
<p>Battle-Fin is launching its 4<sup>th</sup> systematic trading tournament.  Tournament Sponsors have pledged up to $20mm in allocations.</p>
<p>Battle-Fin uses cutting edge real-time tournaments to democratically identify tomorrow&#8217;s best trading strategies across asset classes.</p>
<p>The idea is to harness the power of the internet to identify trading strategies.</p>
<p>If you are a quantitative trader with a successful investment strategy, register for our next tournament by March 15th, 2013. There is no cost to enter and we do not ask to own trader IP.</p>
<p>REGISTER AT: <a href="http://www.battlefin.com/" target="_blank">www.battlefin.com</a></p>
<p>You can also contact us at <a href="tel:%28212%29%20201-5376" target="_blank">(212) 201-5376</a> or <a href="mailto:info@battlefin.com" target="_blank">info@battlefin.com</a></p>
<p>BATTE-FIN IN THE NEWS</p>
<p>Business Week recently wrote a feature article on Battle-Fin highlighting the 4 winners that are currently trading their allocations.<br />
Click: <a href="http://www.businessweek.com/articles/2012-12-20/the-hedge-fund-hunger-games" target="_blank">http://www.<wbr>businessweek.com/articles/<wbr>2012-12-20/the-hedge-fund-<wbr>hunger-games</wbr></wbr></wbr></a></p>
<p>Here is a recent Bloomberg TV interview on Market Makers with Battle Fin.</p>
<p><a href="http://bloom.bg/XFIluz" target="_blank">http://bloom.bg/XFIluz</a><br />
Like us on Facebook at: <a href="http://www.facebook.com/BattleFin" target="_blank">http://www.facebook.com/<wbr>BattleFin</wbr></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2013/03/09/20mm-seed-capital-tournament-the-sharpe-ratio-shootout/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Trend Following &#8211; Skewness Signal</title>
		<link>http://gekkoquant.com/2013/03/03/trend-following-skewness-signal/</link>
		<comments>http://gekkoquant.com/2013/03/03/trend-following-skewness-signal/#comments</comments>
		<pubDate>Sun, 03 Mar 2013 21:05:41 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=352</guid>
		<description><![CDATA[Oxford Dictionary Definition of a trend noun: a general direction in which something is developing or changing Often people try to capture a trend using technical indicators such as moving average cross overs. If there is a trend this technique &#8230; <a href="http://gekkoquant.com/2013/03/03/trend-following-skewness-signal/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Oxford Dictionary Definition of a trend</p>
<ul>
<li>noun: <strong>a general direction in which something is developing or changing</strong></li>
</ul>
<div>Often people try to capture a trend using technical indicators such as moving average cross overs. If there is a trend this technique is generally good at capturing it. However if there isn&#8217;t a trend it becomes difficult to identify side ways markets with moving averages (see <a href="http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part-2/">http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part-2/</a> moving averages performing excellently well during 2009 when there was a real trend).</div>
<div></div>
<p></p>
<div>Is there a better way to identify a trend? Potentially. A common modelling assumption in finance is to say that stock returns follow Brownian motion and that over short periods the mean return is 0, or in other words daily returns are Gaussian distributed with 0 mean.</div>
<div></div>
<p></p>
<div>This post will use the same assumption, asset returns are Guassian and hence returns are <strong>symmetrically distributed around their mean (</strong>assume 0 mean). Symmetric distributions have a skewness of 0, any deviation from 0 indicates that one of the tails is beginning to get bigger and possibly that the stock is trending.</div>
<div></div>
<p></p>
<div>Skewness is a measure of assymetery for a probability distribution, the skewness tells us the amount and direction of the skew. This strategy will take a rolling distribution of returns and calculate the skew for those returns. The skew will then be used to take trades.</div>
<div></div>
<p></p>
<div>Strategy:</div>
<div>
<ul>
<li>If skewness &gt; UptrendSkewLimit then go Long</li>
<li>If skewness &lt; DowntrendSkewLimit then go Short</li>
<li>If skewness between UptrendSkewLimit and DowntrendSkewLimit then returns are symmetrical, it&#8217;s a sideways market do nothing</li>
</ul>
<div></div>
</div>
<div> <a href="http://gekkoquant.com/wp-content/uploads/2013/02/trend-following-trade-signals.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-354" title="trend following trade signals" src="http://gekkoquant.com/wp-content/uploads/2013/02/trend-following-trade-signals.jpeg"  alt="" width="653" height="653" /></a></div>
<div><a href="http://gekkoquant.com/wp-content/uploads/2013/02/trend-following-performance.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-353" title="trend following performance" src="http://gekkoquant.com/wp-content/uploads/2013/02/trend-following-performance.jpeg"  alt="" width="653" height="653" /></a></div>
<div>
<p>&nbsp;</p>
<p>Trend Following - Annualized Sharpe Ratio (Rf=0%) <span style="color: #ff0000;">0.7162438</span></p>
<p>S&amp;P500 Long Open Close Returns - Annualized Sharpe Ratio (Rf=0%) 0.2129997</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p352code6'); return false;">View Code</a> RSPLUS</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p3526"><td class="code" id="p352code6"><pre class="rsplus" style="font-family:monospace;"><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;quantmod&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;PerformanceAnalytics&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span>e1071<span style="color: #080;">&#41;</span>     <span style="color: #228B22;">#For the skewness command</span>
&nbsp;
<span style="color: #228B22;">#Model paramters</span>
nLookback <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">30</span> <span style="color: #228B22;">#When calculating the rolling skew use the nLookback number of days</span>
UptrendSkewLimit <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.3</span> <span style="color: #228B22;">#If the rolling skew is greater than this value go long</span>
DowntrendSkewLimit <span style="color: #080;">&lt;-</span> <span style="color: #080;">-</span><span style="color: #ff0000;">0.5</span> <span style="color: #228B22;">#If the rolling skew is lower than this value go short</span>
<span style="color: #228B22;">#If the rolling skew is between the two limits do nothing, the skew is too weak to indicate a trend</span>
&nbsp;
<span style="color: #228B22;">#Script parameters</span>
symbol <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;^GSPC&quot;</span>     <span style="color: #228B22;">#Symbol</span>
&nbsp;
<span style="color: #228B22;">#Specify dates for downloading data</span>
startDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2005-01-01&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Specify what date to get the prices from</span>
symbolData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/new.env.html"><span style="color: #0000FF; font-weight: bold;">new.<span style="">env</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Make a new environment for quantmod to store data in</span>
getSymbols<span style="color: #080;">&#40;</span>symbol, env <span style="color: #080;">=</span> symbolData, src <span style="color: #080;">=</span> <span style="color: #ff0000;">&quot;yahoo&quot;</span>, from <span style="color: #080;">=</span> startDate<span style="color: #080;">&#41;</span>
mktdata <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/eval.html"><span style="color: #0000FF; font-weight: bold;">eval</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/parse.html"><span style="color: #0000FF; font-weight: bold;">parse</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/text.html"><span style="color: #0000FF; font-weight: bold;">text</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;symbolData$&quot;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sub.html"><span style="color: #0000FF; font-weight: bold;">sub</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;^&quot;</span>,<span style="color: #ff0000;">&quot;&quot;</span>,symbol,fixed<span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
mktdata <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">head</span><span style="color: #080;">&#40;</span>mktdata,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Hack to fix some stupid duplicate date problem with yahoo</span>
dayOpClRet <span style="color: #080;">&lt;-</span> Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">/</span>Op<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span>    <span style="color: #080;">-</span> <span style="color: #ff0000;">1</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cat.html"><span style="color: #0000FF; font-weight: bold;">cat</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;About to calculate the rolling skew&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Lets calculate the rolling skew</span>
<span style="color: #228B22;">#Lag the rolling skew by one day so the skew measured at the close of day T is sifted to day T+1</span>
<span style="color: #228B22;">#The skew will be used to determine the trade at the open</span>
rollingSkew <span style="color: #080;">&lt;-</span> Lag<span style="color: #080;">&#40;</span>rollapply<span style="color: #080;">&#40;</span>dayOpClRet,FUN<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;skewness&quot;</span>,width<span style="color: #080;">=</span>nLookback, align<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;right&quot;</span><span style="color: #080;">&#41;</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Possible improvement - Do a exponential moving average on the skew signal to smooth it</span>
<span style="color: #228B22;">#rollingSkew &lt;- EMA(rollingSkew,n=nLookback)</span>
&nbsp;
longSignals <span style="color: #080;">&lt;-</span> <span style="color: #080;">&#40;</span>rollingSkew<span style="color: #080;">&gt;</span>UptrendSkewLimit<span style="color: #080;">&#41;</span>
longReturns <span style="color: #080;">&lt;-</span> longSignals<span style="color: #080;">*</span>dayOpClRet
shortSignals <span style="color: #080;">&lt;-</span> <span style="color: #080;">&#40;</span>rollingSkew<span style="color: #080;">&lt;</span>DowntrendSkewLimit<span style="color: #080;">&#41;</span>
shortReturns <span style="color: #080;">&lt;-</span> <span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">*</span>shortSignals<span style="color: #080;">*</span>dayOpClRet
totalReturns <span style="color: #080;">&lt;-</span> longReturns <span style="color: #080;">+</span> shortReturns
<span style="color: #228B22;">#Uncomment the line below to increase the position size for larger skews</span>
<span style="color: #228B22;">#totalReturns &lt;- totalReturns * (abs(rollingSkew)+1)</span>
totalReturns<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>totalReturns<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0</span>
&nbsp;
GEKKORed <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">rgb</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">255</span><span style="color: #080;">/</span><span style="color: #ff0000;">255</span>, <span style="color: #ff0000;">0</span><span style="color: #080;">/</span><span style="color: #ff0000;">255</span>, <span style="color: #ff0000;">0</span><span style="color: #080;">/</span><span style="color: #ff0000;">255</span>, <span style="color: #ff0000;">0.1</span><span style="color: #080;">&#41;</span>
GEKKOGreen <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">rgb</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0</span><span style="color: #080;">/</span><span style="color: #ff0000;">255</span>, <span style="color: #ff0000;">255</span><span style="color: #080;">/</span><span style="color: #ff0000;">255</span>, <span style="color: #ff0000;">0</span><span style="color: #080;">/</span><span style="color: #ff0000;">255</span>, <span style="color: #ff0000;">0.1</span><span style="color: #080;">&#41;</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>mfrow<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">3</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span>, main<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Close of S&amp;P 500&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/lines.html"><span style="color: #0000FF; font-weight: bold;">lines</span></a><span style="color: #080;">&#40;</span>longSignals<span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/max.html"><span style="color: #0000FF; font-weight: bold;">max</span></a><span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #080;">&#40;</span>GEKKOGreen<span style="color: #080;">&#41;</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;h&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/lines.html"><span style="color: #0000FF; font-weight: bold;">lines</span></a><span style="color: #080;">&#40;</span>shortSignals<span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/max.html"><span style="color: #0000FF; font-weight: bold;">max</span></a><span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #080;">&#40;</span>GEKKORed<span style="color: #080;">&#41;</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;h&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>rollingSkew<span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/abline.html"><span style="color: #0000FF; font-weight: bold;">abline</span></a><span style="color: #080;">&#40;</span>UptrendSkewLimit,<span style="color: #ff0000;">0</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;green&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/abline.html"><span style="color: #0000FF; font-weight: bold;">abline</span></a><span style="color: #080;">&#40;</span>DowntrendSkewLimit,<span style="color: #ff0000;">0</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cumsum.html"><span style="color: #0000FF; font-weight: bold;">cumsum</span></a><span style="color: #080;">&#40;</span>totalReturns<span style="color: #080;">&#41;</span>, main<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Cumulative Returns - Trend Following&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
<span style="color: #228B22;">#### Performance Analysis ###</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>dayOpClRet<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;Long IndexOpCloseRet&quot;</span>
zooTradeVec <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>as.<span style="">zoo</span><span style="color: #080;">&#40;</span>totalReturns<span style="color: #080;">&#41;</span>,as.<span style="">zoo</span><span style="color: #080;">&#40;</span>dayOpClRet<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Convert to zoo object</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Trend Following&quot;</span>,<span style="color: #ff0000;">&quot;S&amp;P500 Long Open Close Returns&quot;</span><span style="color: #080;">&#41;</span>
zooTradeVec <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">na.<span style="">omit</span></span><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">#Lets see how all the strategies faired against the index</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
charts.<span style="">PerformanceSummary</span><span style="color: #080;">&#40;</span>zooTradeVec,main<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Performance of Trend Following&quot;</span>,geometric<span style="color: #080;">=</span>FALSE<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Calculate the sharpe ratio</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cat.html"><span style="color: #0000FF; font-weight: bold;">cat</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Sharpe Ratio&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span>SharpeRatio.<span style="">annualized</span><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span></pre></td></tr></table></div>

</div>
<div></div>
]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2013/03/03/trend-following-skewness-signal/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Statistical Arbitrage &#8211; Trading a cointegrated pair</title>
		<link>http://gekkoquant.com/2013/01/21/statistical-arbitrage-trading-a-cointegrated-pair/</link>
		<comments>http://gekkoquant.com/2013/01/21/statistical-arbitrage-trading-a-cointegrated-pair/#comments</comments>
		<pubDate>Mon, 21 Jan 2013 00:13:14 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=342</guid>
		<description><![CDATA[In my last post http://gekkoquant.com/2012/12/17/statistical-arbitrage-testing-for-cointegration-augmented-dicky-fuller/ I demonstrated cointegration, a mathematical test to identify stationary pairs where the spread by definition must be mean reverting. In this post I intend to show how to trade a cointegrated pair and will continue analysing Royal Dutch Shell &#8230; <a href="http://gekkoquant.com/2013/01/21/statistical-arbitrage-trading-a-cointegrated-pair/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In my last post <a href="http://gekkoquant.com/2012/12/17/statistical-arbitrage-testing-for-cointegration-augmented-dicky-fuller/">http://gekkoquant.com/2012/12/17/statistical-arbitrage-testing-for-cointegration-augmented-dicky-fuller/</a> I demonstrated cointegration, a mathematical test to identify stationary pairs where the spread by definition must be mean reverting.</p>
<p>In this post I intend to show how to trade a cointegrated pair and will continue analysing Royal Dutch Shell A vs B shares (we know they&#8217;re cointegrated from my last post). Trading a cointegrated pair is straight forward, we know the mean and variance of the spread, we know that those values are constant. The entry point for a stat arb is to simply look for a large deviation away from the mean.</p>
<p>A basic strategy is:</p>
<ul>
<li>If spread(t) &gt;= Mean Spread + 2*Standard Deviation then go Short</li>
<li>If spread(t) &lt;= Mean Spread &#8211; 2*Standard Deviation then go Long</li>
</ul>
<div>There are many variations of this strategy</div>
<div></div>
<div>Moving average / moving standard deviation (this will be explored later):</div>
<div>
<ul>
<li>If spread(t) &gt;= nDay Moving Average + 2*nDay Rolling Standard deviation then go Short</li>
<li>If spread(t) &lt;= nDay Moving Average &#8211; 2*nDay Rolling Standard deviation then go long</li>
</ul>
<div>Wait for mean reversion:</div>
<div>
<ul>
<li>If spread(t) &lt;= Mean Spread + 2*Std AND spread(t-1)&gt; Mean Spread + 2*Std</li>
<li>If spread(t) &gt;= Mean Spread &#8211; 2*Std AND spread(t-1)&lt; Mean Spread &#8211; 2*Std</li>
<li>Advantage is that we only trade when we see the mean reversion, where as the other models are hoping for mean reversion on a large deviation from the mean (is the spread blowing up?)</li>
</ul>
<div>All the above strategies look to exit their position when the spread has reverted to the mean. Personally I wouldn&#8217;t trade any of the above as they don&#8217;t specify an exit strategy for adverse trades. Ie if there is a 6 standard deviation move in the spread is this an amazing trade opportunity? OR more likely did the spread just blow up.</div>
</div>
</div>
<p>This post will look at the moving average and rolling standard deviation model for Royal Dutch Shell A vs B shares, it will use the hedge ratio found in the last post.</p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2013/01/shellAvsB-bollinger-bands.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-344" title="shellAvsB bollinger bands" src="http://gekkoquant.com/wp-content/uploads/2013/01/shellAvsB-bollinger-bands.jpeg"  alt="" width="653" height="653" /></a></p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2013/01/shellAvsB-bollinger-bands-statarb-trade-results.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-343" title="shellAvsB bollinger bands statarb trade results" src="http://gekkoquant.com/wp-content/uploads/2013/01/shellAvsB-bollinger-bands-statarb-trade-results.jpeg"  alt="" width="653" height="653" /></a></p>
<p>Sharpe Ratio Shell A &amp; B Stat Arb Shell A<br />
Annualized Sharpe Ratio (Rf=0%):</p>
<p>Shell A&amp;B Stat Arb <span style="color: #ff0000;">0.8224211</span></p>
<p>Shell A <span style="color: #ff0000;">0.166307</span></p>
<p>The stat arb has a Superior Sharpe ratio over simply investing in Shell A. At a first glance the sharpe ratio of 0.8 looks disappointing, however since the strategy spends most of it&#8217;s time out of the market it will have a low annualized sharpe ratio. To increase the sharpe ratio one can look at trading higher frequencies or have a portfolio pairs so that more time is spent in the market.</p>
<p>Onto the code:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p342code8'); return false;">View Code</a> RSPLUS</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p3428"><td class="code" id="p342code8"><pre class="rsplus" style="font-family:monospace;"><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;quantmod&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;PerformanceAnalytics&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
&nbsp;
backtestStartDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2010-01-02&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Starting date for the backtest</span>
&nbsp;
symbolLst<span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;RDS-A&quot;</span>,<span style="color: #ff0000;">&quot;RDS-B&quot;</span><span style="color: #080;">&#41;</span>
title<span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Royal Dutch Shell A vs B Shares&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">### SECTION 1 - Download Data &amp; Calculate Returns ###</span>
<span style="color: #228B22;">#Download the data</span>
symbolData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/new.env.html"><span style="color: #0000FF; font-weight: bold;">new.<span style="">env</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Make a new environment for quantmod to store data in</span>
getSymbols<span style="color: #080;">&#40;</span>symbolLst, env <span style="color: #080;">=</span> symbolData, src <span style="color: #080;">=</span> <span style="color: #ff0000;">&quot;yahoo&quot;</span>, from <span style="color: #080;">=</span> backtestStartDate<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#We know this pair is cointegrated from the tutorial</span>
<span style="color: #228B22;">#http://gekkoquant.com/2012/12/17/statistical-arbitrage-testing-for-cointegration-augmented-dicky-fuller/</span>
<span style="color: #228B22;">#The tutorial found the hedge ratio to be 0.9653</span>
stockPair <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/list.html"><span style="color: #0000FF; font-weight: bold;">list</span></a><span style="color: #080;">&#40;</span>
 a <span style="color: #080;">=</span> coredata<span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/eval.html"><span style="color: #0000FF; font-weight: bold;">eval</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/parse.html"><span style="color: #0000FF; font-weight: bold;">parse</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/text.html"><span style="color: #0000FF; font-weight: bold;">text</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;symbolData$<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,symbolLst<span style="color: #080;">&#91;</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span>,<span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">#Stock A</span>
,b <span style="color: #080;">=</span> coredata<span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/eval.html"><span style="color: #0000FF; font-weight: bold;">eval</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/parse.html"><span style="color: #0000FF; font-weight: bold;">parse</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/text.html"><span style="color: #0000FF; font-weight: bold;">text</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;symbolData$<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,symbolLst<span style="color: #080;">&#91;</span><span style="color: #ff0000;">2</span><span style="color: #080;">&#93;</span>,<span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Stock B</span>
,hedgeRatio <span style="color: #080;">=</span> <span style="color: #ff0000;">0.9653</span>
,name<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a><span style="color: #080;">&#41;</span>
&nbsp;
simulateTrading <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>stockPair<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
<span style="color: #228B22;">#Generate the spread</span>
spread <span style="color: #080;">&lt;-</span> stockPair$a <span style="color: #080;">-</span> stockPair$hedgeRatio<span style="color: #080;">*</span>stockPair$b
&nbsp;
<span style="color: #228B22;">#Strategy is if the spread is greater than +/- nStd standard deviations of it's rolling 'lookback' day standard deviation</span>
<span style="color: #228B22;">#Then go long or short accordingly</span>
lookback <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">90</span> <span style="color: #228B22;">#look back 90 days</span>
nStd <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">1.5</span> <span style="color: #228B22;">#Number of standard deviations from the mean to trigger a trade</span>
&nbsp;
movingAvg <span style="color: #080;">=</span> rollmean<span style="color: #080;">&#40;</span>spread,lookback, na.<span style="">pad</span><span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Moving average</span>
movingStd <span style="color: #080;">=</span> rollapply<span style="color: #080;">&#40;</span>spread,lookback,<span style="color: #0000FF; font-weight: bold;">sd</span>,align<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;right&quot;</span>, na.<span style="">pad</span><span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Moving standard deviation / bollinger bands</span>
&nbsp;
upperThreshold <span style="color: #080;">=</span> movingAvg <span style="color: #080;">+</span> nStd<span style="color: #080;">*</span>movingStd
lowerThreshold <span style="color: #080;">=</span> movingAvg <span style="color: #080;">-</span> nStd<span style="color: #080;">*</span>movingStd
&nbsp;
aboveUpperBand <span style="color: #080;">&lt;-</span> spread<span style="color: #080;">&gt;</span>upperThreshold
belowLowerBand <span style="color: #080;">&lt;-</span> spread<span style="color: #080;">&lt;</span>lowerThreshold
&nbsp;
aboveMAvg <span style="color: #080;">&lt;-</span> spread<span style="color: #080;">&gt;</span>movingAvg
belowMAvg <span style="color: #080;">&lt;-</span> spread<span style="color: #080;">&lt;</span>movingAvg
&nbsp;
aboveUpperBand<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>aboveUpperBand<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&lt;-</span><span style="color: #ff0000;">0</span>
belowLowerBand<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>belowLowerBand<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&lt;-</span><span style="color: #ff0000;">0</span>
aboveMAvg<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>aboveMAvg<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&lt;-</span><span style="color: #ff0000;">0</span>
belowMAvg<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>belowMAvg<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&lt;-</span><span style="color: #ff0000;">0</span>
&nbsp;
<span style="color: #228B22;">#The cappedCumSum function is where the magic happens</span>
<span style="color: #228B22;">#Its a nice trick to avoid writing a while loop</span>
<span style="color: #228B22;">#Hence since using vectorisation is faster than the while loop</span>
<span style="color: #228B22;">#The function basically does a cumulative sum, but caps the sum to a min and max value</span>
<span style="color: #228B22;">#It's used so that if we get many 'short sell triggers' it will only execute a maximum of 1 position</span>
<span style="color: #228B22;">#Short position - Go short if spread is above upper threshold and go long if below the moving avg</span>
<span style="color: #228B22;">#Note: shortPositionFunc only lets us GO short or close the position</span>
cappedCumSum <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>x, y,max_value,min_value<span style="color: #080;">&#41;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/max.html"><span style="color: #0000FF; font-weight: bold;">max</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/min.html"><span style="color: #0000FF; font-weight: bold;">min</span></a><span style="color: #080;">&#40;</span>x <span style="color: #080;">+</span> y, max_value<span style="color: #080;">&#41;</span>, min_value<span style="color: #080;">&#41;</span>
shortPositionFunc <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>x,y<span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span> cappedCumSum<span style="color: #080;">&#40;</span>x,y,<span style="color: #ff0000;">0</span>,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#125;</span>
longPositionFunc <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>x,y<span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span> cappedCumSum<span style="color: #080;">&#40;</span>x,y,<span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#125;</span>
shortPositions <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/Reduce.html"><span style="color: #0000FF; font-weight: bold;">Reduce</span></a><span style="color: #080;">&#40;</span>shortPositionFunc,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">*</span>aboveUpperBand<span style="color: #080;">+</span>belowMAvg,accumulate<span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span>
longPositions <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/Reduce.html"><span style="color: #0000FF; font-weight: bold;">Reduce</span></a><span style="color: #080;">&#40;</span>longPositionFunc,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">*</span>aboveMAvg<span style="color: #080;">+</span>belowLowerBand,accumulate<span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span>
positions <span style="color: #080;">=</span> longPositions <span style="color: #080;">+</span> shortPositions
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>mfrow<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">2</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>movingAvg,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span>,ylab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Spread&quot;</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">'l'</span>,lty<span style="color: #080;">=</span><span style="color: #ff0000;">2</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Shell A vs B spread with bollinger bands&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/lines.html"><span style="color: #0000FF; font-weight: bold;">lines</span></a><span style="color: #080;">&#40;</span>upperThreshold, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/lines.html"><span style="color: #0000FF; font-weight: bold;">lines</span></a><span style="color: #080;">&#40;</span>lowerThreshold, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/lines.html"><span style="color: #0000FF; font-weight: bold;">lines</span></a><span style="color: #080;">&#40;</span>spread, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;blue&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/legend.html"><span style="color: #0000FF; font-weight: bold;">legend</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;topright&quot;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/legend.html"><span style="color: #0000FF; font-weight: bold;">legend</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Spread&quot;</span>,<span style="color: #ff0000;">&quot;Moving Average&quot;</span>,<span style="color: #ff0000;">&quot;Upper Band&quot;</span>,<span style="color: #ff0000;">&quot;Lower Band&quot;</span><span style="color: #080;">&#41;</span>, inset <span style="color: #080;">=</span> .02,
lty<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">2</span>,<span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;blue&quot;</span>,<span style="color: #ff0000;">&quot;red&quot;</span>,<span style="color: #ff0000;">&quot;red&quot;</span>,<span style="color: #ff0000;">&quot;red&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;"># gives the legend lines the correct color and width</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#40;</span>positions<span style="color: #080;">&#41;</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">'l'</span><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Calculate spread daily ret</span>
 stockPair$a <span style="color: #080;">-</span> stockPair$hedgeRatio<span style="color: #080;">*</span>stockPair$b
aRet <span style="color: #080;">&lt;-</span> Delt<span style="color: #080;">&#40;</span>stockPair$a,k<span style="color: #080;">=</span><span style="color: #ff0000;">1</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;arithmetic&quot;</span><span style="color: #080;">&#41;</span>
bRet <span style="color: #080;">&lt;-</span> Delt<span style="color: #080;">&#40;</span>stockPair$b,k<span style="color: #080;">=</span><span style="color: #ff0000;">1</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;arithmetic&quot;</span><span style="color: #080;">&#41;</span>
dailyRet <span style="color: #080;">&lt;-</span> aRet <span style="color: #080;">-</span> stockPair$hedgeRatio<span style="color: #080;">*</span>bRet
dailyRet<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>dailyRet<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0</span>
&nbsp;
tradingRet <span style="color: #080;">&lt;-</span> dailyRet <span style="color: #080;">*</span> positions
    simulateTrading <span style="color: #080;">&lt;-</span> tradingRet
<span style="color: #080;">&#125;</span>
&nbsp;
tradingRet <span style="color: #080;">&lt;-</span> simulateTrading<span style="color: #080;">&#40;</span>stockPair<span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
<span style="color: #228B22;">#### Performance Analysis ###</span>
<span style="color: #228B22;">#Calculate returns for the index</span>
indexRet <span style="color: #080;">&lt;-</span> Delt<span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/eval.html"><span style="color: #0000FF; font-weight: bold;">eval</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/parse.html"><span style="color: #0000FF; font-weight: bold;">parse</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/text.html"><span style="color: #0000FF; font-weight: bold;">text</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;symbolData$<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,symbolLst<span style="color: #080;">&#91;</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span>,<span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>,k<span style="color: #080;">=</span><span style="color: #ff0000;">1</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;arithmetic&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Daily returns</span>
indexRet <span style="color: #080;">&lt;-</span> as.<span style="">zoo</span><span style="color: #080;">&#40;</span>indexRet<span style="color: #080;">&#41;</span>
tradingRetZoo <span style="color: #080;">&lt;-</span> indexRet
tradingRetZoo<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> tradingRet
zooTradeVec <span style="color: #080;">&lt;-</span> as.<span style="">zoo</span><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>tradingRetZoo,indexRet<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Convert to zoo object</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Shell A &amp; B Stat Arb&quot;</span>,<span style="color: #ff0000;">&quot;Shell A&quot;</span><span style="color: #080;">&#41;</span>
zooTradeVec <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">na.<span style="">omit</span></span><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Lets see how all the strategies faired against the index</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
charts.<span style="">PerformanceSummary</span><span style="color: #080;">&#40;</span>zooTradeVec,main<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Performance of Shell Statarb Strategy&quot;</span>,geometric<span style="color: #080;">=</span>FALSE<span style="color: #080;">&#41;</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cat.html"><span style="color: #0000FF; font-weight: bold;">cat</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Sharpe Ratio&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span>SharpeRatio.<span style="">annualized</span><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2013/01/21/statistical-arbitrage-trading-a-cointegrated-pair/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Statistical Arbitrage &#8211; Testing for Cointegration &#8211; Augmented Dicky Fuller</title>
		<link>http://gekkoquant.com/2012/12/17/statistical-arbitrage-testing-for-cointegration-augmented-dicky-fuller/</link>
		<comments>http://gekkoquant.com/2012/12/17/statistical-arbitrage-testing-for-cointegration-augmented-dicky-fuller/#comments</comments>
		<pubDate>Mon, 17 Dec 2012 01:11:03 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=308</guid>
		<description><![CDATA[In my last post &#8220;Statistical Arbitrage Correlation vs Cointegration&#8220;, we discussed what statistical arbitrage is and what property between two pairs we aim to exploit. The mathematics essentially showed that if you go long stock A and short stock B &#8230; <a href="http://gekkoquant.com/2012/12/17/statistical-arbitrage-testing-for-cointegration-augmented-dicky-fuller/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In my last post &#8220;<a href="http://gekkoquant.com/2012/10/21/statistical-arbitrage-correlation-vs-cointegration/">Statistical Arbitrage Correlation vs Cointegration</a>&#8220;, we discussed what statistical arbitrage is and what property between two pairs we aim to exploit. The mathematics essentially showed that if you go long stock A and short stock B with some appropriate hedging factor to cancel out the drift/growth terms in the Brownian motion equation then you are left with a stationary signal which is the spread between the two stocks. The maths also showed that <em>in expectation</em> the daily change in the spread is zero (<img src="http://l.wordpress.com/latex.php?latex=E_%7Bt%7D%5B%5CDelta%20Spread%5D%3D0&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="E_{t}[\Delta Spread]=0" style="vertical-align:-20%;" class="tex" alt="E_{t}[\Delta Spread]=0" />) and hence any deviation from this presents the opportunity for a trade.</p>
<p>It was assumed that the stock growth terms <img src="http://l.wordpress.com/latex.php?latex=%5Cmu_%7Ba%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\mu_{a}" style="vertical-align:-20%;" class="tex" alt="\mu_{a}" /> and <img src="http://l.wordpress.com/latex.php?latex=%5Cmu_%7Bb%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\mu_{b}" style="vertical-align:-20%;" class="tex" alt="\mu_{b}" /> are constant (or drifting slowly over time both at the same rate) or in other words the hedge ratio is constant. This post will detail how to find the hedge ratio and present the Augmented Dicky Fuller test which can be used to identify with a certain level of confidence if the spread is stationary and hence cointegrated.</p>
<p><strong>Determining the hedge factor</strong></p>
<p><img src="http://l.wordpress.com/latex.php?latex=Spread%3DA-nB&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="Spread=A-nB" style="vertical-align:-20%;" class="tex" alt="Spread=A-nB" /> set the spread to <img src="http://l.wordpress.com/latex.php?latex=0&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="0" style="vertical-align:-20%;" class="tex" alt="0" /></p>
<p>It is required to find the hedge factor, n, to satisfy the above equation. The hedge factor is easily found by regressing the <img src="http://l.wordpress.com/latex.php?latex=A%20vs%20B&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="A vs B" style="vertical-align:-20%;" class="tex" alt="A vs B" />. Notice that it is the prices being regressed and not the daily returns.</p>
<p><strong>Examining the residuals</strong></p>
<p><strong></strong>Once the hedge factor has been found the residuals of the regression must be analysed. The residual is how much the spread has changed for a given day, the whole idea of the regression was to identify the hedge factor that keeps the daily change of the spread as close to zero as possible (we want the residuals to be zero).</p>
<ul>
<li>If the residuals contain a trend then this implies that the daily change of the spread has a net direction and will cause the spread to consistently widen or contract.</li>
<li>If the residuals contain no trend then this implies that the daily change of the spread will oscillate around zero (is stationary).</li>
</ul>
<p>What residuals to analyse is open to debate, you may want to take another data set from a different point in time and apply the hedge factor you calculated in the above regression to this new set and analyse the residuals, this helps to identify an over fitting during the regression.</p>
<p><strong>Dicky Fuller Test</strong></p>
<p>For an AR(1) process <img src="http://l.wordpress.com/latex.php?latex=y_%7Bt%7D%3Day_%7Bt-1%7D%2B%5Cepsilon_%7Bt%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="y_{t}=ay_{t-1}+\epsilon_{t}" style="vertical-align:-20%;" class="tex" alt="y_{t}=ay_{t-1}+\epsilon_{t}" /> where <img src="http://l.wordpress.com/latex.php?latex=y_%7B0%7D%3D0&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="y_{0}=0" style="vertical-align:-20%;" class="tex" alt="y_{0}=0" /> and <img src="http://l.wordpress.com/latex.php?latex=%5Cepsilon%20%5Csim%20N%280%2C%5Csigma%5E%7B2%7D%29&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\epsilon \sim N(0,\sigma^{2})" style="vertical-align:-20%;" class="tex" alt="\epsilon \sim N(0,\sigma^{2})" /> what value of <img src="http://l.wordpress.com/latex.php?latex=a&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="a" style="vertical-align:-20%;" class="tex" alt="a" /> results in a stationary signal?</p>
<p><img src="http://l.wordpress.com/latex.php?latex=y_%7B1%7D%3Day_%7B0%7D%2B%5Cepsilon_%7B0%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="y_{1}=ay_{0}+\epsilon_{0}" style="vertical-align:-20%;" class="tex" alt="y_{1}=ay_{0}+\epsilon_{0}" /></p>
<p><img src="http://l.wordpress.com/latex.php?latex=y_%7B2%7D%3Day_%7B1%7D%2B%5Cepsilon_%7B1%7D%3Da%28ay_%7B0%7D%2B%5Cepsilon_%7B0%7D%29%2B%5Cepsilon%7B1%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="y_{2}=ay_{1}+\epsilon_{1}=a(ay_{0}+\epsilon_{0})+\epsilon{1}" style="vertical-align:-20%;" class="tex" alt="y_{2}=ay_{1}+\epsilon_{1}=a(ay_{0}+\epsilon_{0})+\epsilon{1}" /></p>
<p><img src="http://l.wordpress.com/latex.php?latex=y_%7Bt%7D%3Da%5E%7Bt%7Dy_%7B0%7D%2B%5CSigma_%7Bj%3D0%7D%5E%7Bt-1%7Da%5E%7Bj%7D%5Cepsilon_%7Bj%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="y_{t}=a^{t}y_{0}+\Sigma_{j=0}^{t-1}a^{j}\epsilon_{j}" style="vertical-align:-20%;" class="tex" alt="y_{t}=a^{t}y_{0}+\Sigma_{j=0}^{t-1}a^{j}\epsilon_{j}" /></p>
<p>Take expectations, already know <img src="http://l.wordpress.com/latex.php?latex=E%5By_%7B0%7D%5D%3D0&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="E[y_{0}]=0" style="vertical-align:-20%;" class="tex" alt="E[y_{0}]=0" /> and <img src="http://l.wordpress.com/latex.php?latex=E%5B%5Cepsilon_%7Bt%7D%5D%3D0&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="E[\epsilon_{t}]=0" style="vertical-align:-20%;" class="tex" alt="E[\epsilon_{t}]=0" /></p>
<p><img src="http://l.wordpress.com/latex.php?latex=E%5By_%7Bt%7D%5D%3Da%5E%7Bt%7DE%5By_%7B0%7D%5D%2B%5CSigma_%7Bj%3D0%7D%5E%7Bt-1%7Da%5E%7Bj%7DE%5B%5Cepsilon_%7Bj%7D%5D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="E[y_{t}]=a^{t}E[y_{0}]+\Sigma_{j=0}^{t-1}a^{j}E[\epsilon_{j}]" style="vertical-align:-20%;" class="tex" alt="E[y_{t}]=a^{t}E[y_{0}]+\Sigma_{j=0}^{t-1}a^{j}E[\epsilon_{j}]" /></p>
<div><img src="http://l.wordpress.com/latex.php?latex=E%5By_%7Bt%7D%5D%3Da%5E%7Bt%7D%2A0%2B%5CSigma_%7Bj%3D0%7D%5E%7Bt-1%7Da%5E%7Bj%7D%2A0%3D0&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="E[y_{t}]=a^{t}*0+\Sigma_{j=0}^{t-1}a^{j}*0=0" style="vertical-align:-20%;" class="tex" alt="E[y_{t}]=a^{t}*0+\Sigma_{j=0}^{t-1}a^{j}*0=0" /> the mean is zero and constant</div>
<div></div>
<div>Examining the variance</div>
<div></div>
<div><img src="http://l.wordpress.com/latex.php?latex=V%5By_%7Bt%7D%5D%3D0%2B%5CSigma_%7Bj%3D0%7D%5E%7Bt-1%7Da%5E%7Bj%7DV%5B%5Cepsilon_%7Bj%7D%5D%3D%5Csigma%5E%7B2%7D%5CSigma_%7Bj%3D0%7D%5E%7Bt-1%7Da%5E%7Bj%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="V[y_{t}]=0+\Sigma_{j=0}^{t-1}a^{j}V[\epsilon_{j}]=\sigma^{2}\Sigma_{j=0}^{t-1}a^{j}" style="vertical-align:-20%;" class="tex" alt="V[y_{t}]=0+\Sigma_{j=0}^{t-1}a^{j}V[\epsilon_{j}]=\sigma^{2}\Sigma_{j=0}^{t-1}a^{j}" /></div>
<div></div>
<div>
<ul>
<li>If <img src="http://l.wordpress.com/latex.php?latex=a&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="a" style="vertical-align:-20%;" class="tex" alt="a" /> &lt; <img src="http://l.wordpress.com/latex.php?latex=1&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="1" style="vertical-align:-20%;" class="tex" alt="1" /> then as <img src="http://l.wordpress.com/latex.php?latex=t%20%5Cto%20%5Cinf&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="t \to \inf" style="vertical-align:-20%;" class="tex" alt="t \to \inf" /> then <img src="http://l.wordpress.com/latex.php?latex=V%5By_%7Bt%7D%5D%5Cto%20constant&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="V[y_{t}]\to constant" style="vertical-align:-20%;" class="tex" alt="V[y_{t}]\to constant" /></li>
<li>If <img src="http://l.wordpress.com/latex.php?latex=a&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="a" style="vertical-align:-20%;" class="tex" alt="a" /> &gt;= <img src="http://l.wordpress.com/latex.php?latex=1&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="1" style="vertical-align:-20%;" class="tex" alt="1" /> then <img src="http://l.wordpress.com/latex.php?latex=V%5By_%7Bt%7D%5D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="V[y_{t}]" style="vertical-align:-20%;" class="tex" alt="V[y_{t}]" /> grows with time, hence is not stationary</li>
</ul>
</div>
<div> This forms the premise of the Dicky Fuller test, perform a linear regression on the residuals and see what the value of <img src="http://l.wordpress.com/latex.php?latex=a&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="a" style="vertical-align:-20%;" class="tex" alt="a" /> is, if it&#8217;s greater than or equal to one this indicates the signal isn&#8217;t stationary and therefore isn&#8217;t suitable to stat arb. The dicky fuller test was invented by D.A Dickey and W.A Fuller, they produced the dickey-fuller distribution relating number of test samples and the value of <img src="http://l.wordpress.com/latex.php?latex=a&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="a" style="vertical-align:-20%;" class="tex" alt="a" /> to a probability of a unit root. Further reading can be found at <a href="http://en.wikipedia.org/wiki/Dickey%E2%80%93Fuller_test">Dickey Fuller Test &#8211; Wikipedia</a>. The dickey fuller test is a hypothesis test that a signal contains a unit root,we want to reject this hypothesis (a unit root means our signal is non-stationary). The test gives a pValue, the lower this number the more confident we can be that we have found a stationary signal. pValues less than 0.1 are considered to be good candidates.</div>
<div></div>
<p></p>
<div><strong>Royal Dutch Shell Case Study</strong></div>
<div>As mentioned in the previous post, two different shares for the same company are usually good stat arb candidates. Here the hypothesis that Royal Dutch Shell A &amp; B shares are cointegrated will be tested.</div>
<div><a href="http://gekkoquant.com/wp-content/uploads/2012/12/royal-dutch-shell-spread1.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-332" title="royal dutch shell spread" src="http://gekkoquant.com/wp-content/uploads/2012/12/royal-dutch-shell-spread1.jpeg"  alt="" width="653" height="653" /></a></div>
<div></div>
<div>
<p>The beta or Hedge Ratio is: 0.965378555498888</p>
<p>Augmented Dickey-Fuller Test</p>
<p>Dickey-Fuller = -3.6192, Lag order = 0, <span style="color: #ff0000;">p-value = 0.03084</span><br />
alternative hypothesis: stationary</p>
<p>The low pValue indicates that this pair is cointegrated.</p>
<div><strong>Royal Bank of Scotland vs Barclays Case Study</strong></div>
<p><a href="http://gekkoquant.com/wp-content/uploads/2012/12/royal-bank-of-scotland-vs-barclays.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-333" title="royal bank of scotland vs barclays" src="http://gekkoquant.com/wp-content/uploads/2012/12/royal-bank-of-scotland-vs-barclays.jpeg"  alt="" width="653" height="653" /></a></p>
<p>The beta or Hedge Ratio is: 0.645507426925485</p>
<p>Augmented Dickey-Fuller Test</p>
<p>Dickey-Fuller = -1.6801, Lag order = 0, <span style="color: #ff0000;">p-value = 0.7137</span><br />
alternative hypothesis: stationary</p>
</div>
<div>The pValue indicates that the spread isn&#8217;t stationary, and the bottom right graph of the spread is definitely in a strong trend and isn&#8217;t range bound. This would have been a horrific stat arb!</div>
<div></div>
<div>On to the code:</div>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p308code10'); return false;">View Code</a> RSPLUS</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p30810"><td class="code" id="p308code10"><pre class="rsplus" style="font-family:monospace;"><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;quantmod&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;PerformanceAnalytics&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;fUnitRoots&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;tseries&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Specify dates for downloading data, training models and running simulation</span>
hedgeTrainingStartDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2008-01-01&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Start date for training the hedge ratio</span>
hedgeTrainingEndDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2010-01-01&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#End date for training the hedge ratio</span>
&nbsp;
symbolLst<span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;RDS-A&quot;</span>,<span style="color: #ff0000;">&quot;RDS-B&quot;</span><span style="color: #080;">&#41;</span>
title<span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Royal Dutch Shell A vs B Shares&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
symbolLst<span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;RBS.L&quot;</span>,<span style="color: #ff0000;">&quot;BARC.L&quot;</span><span style="color: #080;">&#41;</span>
title<span style="color: #080;">&lt;-</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Royal Bank of Scotland vs Barclays&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">### SECTION 1 - Download Data &amp; Calculate Returns ###</span>
<span style="color: #228B22;">#Download the data</span>
symbolData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/new.env.html"><span style="color: #0000FF; font-weight: bold;">new.<span style="">env</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Make a new environment for quantmod to store data in</span>
getSymbols<span style="color: #080;">&#40;</span>symbolLst, env <span style="color: #080;">=</span> symbolData, src <span style="color: #080;">=</span> <span style="color: #ff0000;">&quot;yahoo&quot;</span>, from <span style="color: #080;">=</span> hedgeTrainingStartDate, to<span style="color: #080;">=</span>hedgeTrainingEndDate<span style="color: #080;">&#41;</span>
&nbsp;
stockPair <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/list.html"><span style="color: #0000FF; font-weight: bold;">list</span></a><span style="color: #080;">&#40;</span>
 a <span style="color: #080;">=</span> coredata<span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/eval.html"><span style="color: #0000FF; font-weight: bold;">eval</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/parse.html"><span style="color: #0000FF; font-weight: bold;">parse</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/text.html"><span style="color: #0000FF; font-weight: bold;">text</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;symbolData$<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,symbolLst<span style="color: #080;">&#91;</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span>,<span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">#Stock A</span>
,b <span style="color: #080;">=</span> coredata<span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/eval.html"><span style="color: #0000FF; font-weight: bold;">eval</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/parse.html"><span style="color: #0000FF; font-weight: bold;">parse</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/text.html"><span style="color: #0000FF; font-weight: bold;">text</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;symbolData$<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,symbolLst<span style="color: #080;">&#91;</span><span style="color: #ff0000;">2</span><span style="color: #080;">&#93;</span>,<span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Stock B</span>
,name<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/title.html"><span style="color: #0000FF; font-weight: bold;">title</span></a><span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
testForCointegration <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>stockPairs<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
<span style="color: #228B22;">#Pass in a pair of stocks and do the necessary checks to see if it is cointegrated</span>
&nbsp;
<span style="color: #228B22;">#Plot the pairs</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/par.html"><span style="color: #0000FF; font-weight: bold;">par</span></a><span style="color: #080;">&#40;</span>mfrow<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">2</span>,<span style="color: #ff0000;">2</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0.99</span><span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/min.html"><span style="color: #0000FF; font-weight: bold;">min</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rbind.html"><span style="color: #0000FF; font-weight: bold;">rbind</span></a><span style="color: #080;">&#40;</span>stockPairs$a,stockPairs$b<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>,<span style="color: #080;">&#40;</span><span style="color: #ff0000;">1.01</span><span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/max.html"><span style="color: #0000FF; font-weight: bold;">max</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rbind.html"><span style="color: #0000FF; font-weight: bold;">rbind</span></a><span style="color: #080;">&#40;</span>stockPairs$a,stockPairs$b<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>stockPairs$a, main<span style="color: #080;">=</span>stockPairs$name, ylab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Price&quot;</span>, type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;l&quot;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span>,ylim<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#40;</span><span style="color: #ff0000;">0.99</span><span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/min.html"><span style="color: #0000FF; font-weight: bold;">min</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rbind.html"><span style="color: #0000FF; font-weight: bold;">rbind</span></a><span style="color: #080;">&#40;</span>stockPairs$a,stockPairs$b<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>,<span style="color: #080;">&#40;</span><span style="color: #ff0000;">1.01</span><span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/max.html"><span style="color: #0000FF; font-weight: bold;">max</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rbind.html"><span style="color: #0000FF; font-weight: bold;">rbind</span></a><span style="color: #080;">&#40;</span>stockPairs$a,stockPairs$b<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/lines.html"><span style="color: #0000FF; font-weight: bold;">lines</span></a><span style="color: #080;">&#40;</span>stockPairs$b, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;blue&quot;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span>stockPairs$a<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span>stockPairs$b<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">#Step 1: Calculate the daily returns</span>
dailyRet.<span style="">a</span> <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">na.<span style="">omit</span></span><span style="color: #080;">&#40;</span><span style="color: #080;">&#40;</span>Delt<span style="color: #080;">&#40;</span>stockPairs$a,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;arithmetic&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
dailyRet.<span style="">b</span> <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">na.<span style="">omit</span></span><span style="color: #080;">&#40;</span><span style="color: #080;">&#40;</span>Delt<span style="color: #080;">&#40;</span>stockPairs$b,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;arithmetic&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
dailyRet.<span style="">a</span> <span style="color: #080;">&lt;-</span> dailyRet.<span style="">a</span><span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.finite.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">finite</span></span></a><span style="color: #080;">&#40;</span>dailyRet.<span style="">a</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span> <span style="color: #228B22;">#Strip out any Infs (first ret is Inf)</span>
dailyRet.<span style="">b</span> <span style="color: #080;">&lt;-</span> dailyRet.<span style="">b</span><span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.finite.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">finite</span></span></a><span style="color: #080;">&#40;</span>dailyRet.<span style="">b</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span>dailyRet.<span style="">a</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/length.html"><span style="color: #0000FF; font-weight: bold;">length</span></a><span style="color: #080;">&#40;</span>dailyRet.<span style="">b</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">#Step 2: Regress the daily returns onto each other</span>
<span style="color: #228B22;">#Regression finds BETA and C in the linear regression retA = BETA * retB + C</span>
regression <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">lm</span><span style="color: #080;">&#40;</span>dailyRet.<span style="">a</span> ~ dailyRet.<span style="">b</span> <span style="color: #080;">+</span> <span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/beta.html"><span style="color: #0000FF; font-weight: bold;">beta</span></a> <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">coef</span><span style="color: #080;">&#40;</span>regression<span style="color: #080;">&#41;</span><span style="color: #080;">&#91;</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;The beta or Hedge Ratio is: &quot;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/beta.html"><span style="color: #0000FF; font-weight: bold;">beta</span></a>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>x<span style="color: #080;">=</span>dailyRet.<span style="">b</span>,y<span style="color: #080;">=</span>dailyRet.<span style="">a</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;p&quot;</span>,main<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Regression of RETURNS for Stock A &amp; B&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Plot the daily returns</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/lines.html"><span style="color: #0000FF; font-weight: bold;">lines</span></a><span style="color: #080;">&#40;</span>x<span style="color: #080;">=</span>dailyRet.<span style="">b</span>,y<span style="color: #080;">=</span><span style="color: #080;">&#40;</span>dailyRet.<span style="">b</span><span style="color: #080;">*</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/beta.html"><span style="color: #0000FF; font-weight: bold;">beta</span></a><span style="color: #080;">&#41;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;blue&quot;</span><span style="color: #080;">&#41;</span><span style="color: #228B22;">#Plot in linear line we used in the regression</span>
&nbsp;
&nbsp;
<span style="color: #228B22;">#Step 3: Use the regression co-efficients to generate the spread</span>
spread <span style="color: #080;">&lt;-</span> stockPairs$a <span style="color: #080;">-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/beta.html"><span style="color: #0000FF; font-weight: bold;">beta</span></a><span style="color: #080;">*</span>stockPairs$b <span style="color: #228B22;">#Could actually just use the residual form the regression its the same thing</span>
spreadRet <span style="color: #080;">&lt;-</span> Delt<span style="color: #080;">&#40;</span>spread,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;arithmetic&quot;</span><span style="color: #080;">&#41;</span>
spreadRet <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">na.<span style="">omit</span></span><span style="color: #080;">&#40;</span>spreadRet<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">#spreadRet[!is.na(spreadRet)]</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#40;</span>spreadRet<span style="color: #080;">&#41;</span>, type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;l&quot;</span>,main<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Spread Returns&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Plot the cumulative sum of the spread</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>spread, type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;l&quot;</span>,main<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Spread Actual&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Plot the cumulative sum of the spread</span>
<span style="color: #228B22;">#For a cointegrated spread the cumsum should not deviate very far from 0</span>
<span style="color: #228B22;">#For a none-cointegrated spread the cumsum will likely show some trending characteristics</span>
&nbsp;
<span style="color: #228B22;">#Step 4: Use the ADF to test if the spread is stationary</span>
<span style="color: #228B22;">#can use tSeries library</span>
adfResults <span style="color: #080;">&lt;-</span> adf.<span style="">test</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#40;</span>spread<span style="color: #080;">&#41;</span>,k<span style="color: #080;">=</span><span style="color: #ff0000;">0</span>,alternative<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;stationary&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span>adfResults<span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span>adfResults$p.<span style="">value</span> <span style="color: #080;">&lt;=</span> <span style="color: #ff0000;">0.05</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;The spread is likely Cointegrated with a pvalue of &quot;</span>,adfResults$p.<span style="">value</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span> <span style="color: #0000FF; font-weight: bold;">else</span> <span style="color: #080;">&#123;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;The spread is likely NOT Cointegrated with a pvalue of &quot;</span>,adfResults$p.<span style="">value</span>,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
<span style="color: #080;">&#125;</span>
&nbsp;
&nbsp;
testForCointegration<span style="color: #080;">&#40;</span>stockPair<span style="color: #080;">&#41;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2012/12/17/statistical-arbitrage-testing-for-cointegration-augmented-dicky-fuller/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Statistical Arbitrage &#8211; Correlation vs Cointegration</title>
		<link>http://gekkoquant.com/2012/10/21/statistical-arbitrage-correlation-vs-cointegration/</link>
		<comments>http://gekkoquant.com/2012/10/21/statistical-arbitrage-correlation-vs-cointegration/#comments</comments>
		<pubDate>Sun, 21 Oct 2012 20:24:59 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=279</guid>
		<description><![CDATA[What is statistical arbitrage (stat arb)? The premise of statistical arbitrage, stat arb for short, is that there is a statistical mispricing between a set of securities which we look to exploit. Typically a strategy requires going long a set &#8230; <a href="http://gekkoquant.com/2012/10/21/statistical-arbitrage-correlation-vs-cointegration/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><strong>What is statistical arbitrage (stat arb)?</strong></p>
<p>The premise of statistical arbitrage, stat arb for short, is that there is a statistical mispricing between a set of securities which we look to exploit. Typically a strategy requires going long a set of stocks and short another. StatArb evolved from pairs trading where one would go long a stock and short it&#8217;s competitor as a hedge, in pairs trading the aim is to select a stock that is going to outperform it&#8217;s peers. StatArb is all about mean reversion, in essence you are saying that the spread between any two stocks should be constant (or slowly evolving throughout time), any deviations from the spread present a trading opportunity since in StatArb we believe the spread is mean reverting. Contrary to the name statistical arbitrage isn&#8217;t about making risk free money (deterministic arbitrage is risk free).</p>
<p><strong>What type of stocks make good pairs?</strong></p>
<p>The best stocks to use in StatArb are those where there is a fundamental reason for believing that the spread is mean reverting / stationary. Typically this means that the stocks are in the same market sector or even better the same company (some companies have A and B shares with different voting rights or trade on different exchanges)! Some examples of fundamentally similar pairs would be Royal Dutch Shell A vs Royal Dutch Shell B shares, Goldman Sachs vs JP Morgan, Apple vs ARM (their chip supplier), ARM vs ARM ADR, some cross sector groups may also work such as Gold Mining vs Gold Price.</p>
<p>A poor example would be Royal Bank of Scotland vs Tesco since their businesses are completely different / don&#8217;t impact each other.</p>
<p><strong>What is the mathematical definition of a good pair?</strong></p>
<p>Upon coming up with a good fundamental stock pairing you next need to have a mathematical test for determining if it&#8217;s a good pair. The most common test is to look for cointegration (http://en.wikipedia.org/wiki/Cointegration) as this would imply that the pair is a stationary pair (the spread is fixed) and hence statistically it is mean reverting. When testing for cointegration a Pvalue(http://en.wikipedia.org/wiki/P-value) hypothesis test is performed, so we can express a level of confidence in the pair being mean reverting.</p>
<p><strong>What is the difference between correlation and cointegration?</strong></p>
<p>When talking about statisitical arbitrage many people often get confused between correlation and cointegration.</p>
<ul>
<li>Correlation &#8211; If two stocks are correlated then if stock A has an upday then stock B will have an upday</li>
<li>Cointegration &#8211; If two stocks are cointegrated then it is possible to form a stationary pair from some linear combination of stock A and B</li>
</ul>
<p>One of the best explanations of cointegration is as follows: “A man leaves a pub to go home with his dog, the man is drunk and goes on a random walk, the dog also goes on a random walk. They approach a busy road and the man puts his dog on a lead, the man and the dog are now cointegrated. They can both go on random walks but the maximum distance they can move away from each other is fixed ie length of the lead”. So in essence the distance/spread between the man and his dog is fixed, also note from the story that the man and dog are still on a random walk, there is nothing to say if their movements are correlated or uncorrelated.With correlated stocks they will move in the same direction most of the time however the magnitude of the moves is unknown, this means that if you&#8217;re trading the spread between two stocks then the spread can keep growing and growing showing no signs of mean reversion. This is in contract to cointegration where we say the spread is “fixed” and that if the spread deviates from the “fixing” then it will mean revert.</p>
<p>Lets explore cointegration some more:</p>
<p>Equation for Geometric brownian motion</p>
<p><img src="http://l.wordpress.com/latex.php?latex=A_%7Bt%2BT%7D%20%3D%20A_%7Bt%7D%2BN%28%5Cmu_%7Ba%7DT%2C%5Csigma_%7Ba%7D%5Csqrt%7BT%7D%29&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="A_{t+T} = A_{t}+N(\mu_{a}T,\sigma_{a}\sqrt{T})" style="vertical-align:-20%;" class="tex" alt="A_{t+T} = A_{t}+N(\mu_{a}T,\sigma_{a}\sqrt{T})" /></p>
<p>where A stands for the price of stock A<br />
<img src="http://l.wordpress.com/latex.php?latex=%5CDelta%20A%20%3D%20N%28%5Cmu_%7Ba%7D%5CDelta%20t%2C%5Csigma_%7Ba%7D%5Csqrt%7B%5CDelta%20t%7D%29&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\Delta A = N(\mu_{a}\Delta t,\sigma_{a}\sqrt{\Delta t})" style="vertical-align:-20%;" class="tex" alt="\Delta A = N(\mu_{a}\Delta t,\sigma_{a}\sqrt{\Delta t})" /><br />
<img src="http://l.wordpress.com/latex.php?latex=%5CDelta%20A%20%3D%20%5Cmu_%7Ba%7D%5CDelta%20t%2BN%280%2C%5Csigma_%7Ba%7D%5Csqrt%7B%5CDelta%20t%7D%29&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\Delta A = \mu_{a}\Delta t+N(0,\sigma_{a}\sqrt{\Delta t})" style="vertical-align:-20%;" class="tex" alt="\Delta A = \mu_{a}\Delta t+N(0,\sigma_{a}\sqrt{\Delta t})" /><br />
<img src="http://l.wordpress.com/latex.php?latex=E_%7Bt%7D%5B%5CDelta%20A%5D%20%3D%20%5Cmu_%7Ba%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="E_{t}[\Delta A] = \mu_{a}" style="vertical-align:-20%;" class="tex" alt="E_{t}[\Delta A] = \mu_{a}" /><br />
From the geometric Brownian motion equation we can see that the expected change in A over time <img src="http://l.wordpress.com/latex.php?latex=%28E_%7Bt%7D%5B%5CDelta%20A%5D%29&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="(E_{t}[\Delta A])" style="vertical-align:-20%;" class="tex" alt="(E_{t}[\Delta A])" /> is <img src="http://l.wordpress.com/latex.php?latex=%5Cmu_%7Ba%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\mu_{a}" style="vertical-align:-20%;" class="tex" alt="\mu_{a}" />, in other words A is not stationary  assuming <img src="http://l.wordpress.com/latex.php?latex=%5Cmu_%7Ba%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\mu_{a}" style="vertical-align:-20%;" class="tex" alt="\mu_{a}" /> isnt zero).</p>
<p>We want to find a cointegrated / stationary pair.</p>
<p>Equation for going long stock A and short n lots of Stock B<br />
<img src="http://l.wordpress.com/latex.php?latex=Spread%3DA-nB&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="Spread=A-nB" style="vertical-align:-20%;" class="tex" alt="Spread=A-nB" /></p>
<p><img src="http://l.wordpress.com/latex.php?latex=%5CDelta%20Spread%3D%5CDelta%20A-n%5CDelta%20B&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\Delta Spread=\Delta A-n\Delta B" style="vertical-align:-20%;" class="tex" alt="\Delta Spread=\Delta A-n\Delta B" /><br />
<img src="http://l.wordpress.com/latex.php?latex=%5CDelta%20Spread%3D%5Cmu_%7Ba%7D%5CDelta%20t%2BN%280%2C%5Csigma_%7Ba%7D%5Csqrt%7B%5CDelta%20t%7D%29-n%5Cmu_%7Bb%7D%5CDelta%20t-nN%280%2C%5Csigma_%7Bb%7D%5Csqrt%7B%5CDelta%20t%7D%29&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\Delta Spread=\mu_{a}\Delta t+N(0,\sigma_{a}\sqrt{\Delta t})-n\mu_{b}\Delta t-nN(0,\sigma_{b}\sqrt{\Delta t})" style="vertical-align:-20%;" class="tex" alt="\Delta Spread=\mu_{a}\Delta t+N(0,\sigma_{a}\sqrt{\Delta t})-n\mu_{b}\Delta t-nN(0,\sigma_{b}\sqrt{\Delta t})" /><br />
<img src="http://l.wordpress.com/latex.php?latex=E_%7Bt%7D%5B%5CDelta%20Spread%5D%3DE_%7Bt%7D%5B%5CDelta%20A-n%5CDelta%20B%5D%20%3D%20%5Cmu_%7Ba%7D-n%5Cmu_%7Bb%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="E_{t}[\Delta Spread]=E_{t}[\Delta A-n\Delta B] = \mu_{a}-n\mu_{b}" style="vertical-align:-20%;" class="tex" alt="E_{t}[\Delta Spread]=E_{t}[\Delta A-n\Delta B] = \mu_{a}-n\mu_{b}" /><br />
Setting <img src="http://l.wordpress.com/latex.php?latex=n%3D%5Cfrac%7B%5Cmu_%7Ba%7D%7D%7B%5Cmu_%7Bb%7D%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="n=\frac{\mu_{a}}{\mu_{b}}" style="vertical-align:-20%;" class="tex" alt="n=\frac{\mu_{a}}{\mu_{b}}" /><br />
<img src="http://l.wordpress.com/latex.php?latex=E_%7Bt%7D%5B%5CDelta%20Spread%5D%3DE_%7Bt%7D%5B%5CDelta%20A-n%5CDelta%20B%5D%20%3D%20%5Cmu_%7Ba%7D-%5Cfrac%7B%5Cmu_%7Ba%7D%5Cmu_%7Bb%7D%7D%7B%5Cmu_%7Bb%7D%7D%3D%5Cmu_%7Ba%7D-%5Cmu_%7Ba%7D%3D0&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="E_{t}[\Delta Spread]=E_{t}[\Delta A-n\Delta B] = \mu_{a}-\frac{\mu_{a}\mu_{b}}{\mu_{b}}=\mu_{a}-\mu_{a}=0" style="vertical-align:-20%;" class="tex" alt="E_{t}[\Delta Spread]=E_{t}[\Delta A-n\Delta B] = \mu_{a}-\frac{\mu_{a}\mu_{b}}{\mu_{b}}=\mu_{a}-\mu_{a}=0" /><br />
Hence is stationary <b>assuming that the hedge ratio, <img src="http://l.wordpress.com/latex.php?latex=n&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="n" style="vertical-align:-20%;" class="tex" alt="n" />, remains constant</b>!!!</p>
<p>&nbsp;</p>
<p><strong>Example of correlated stocks : <em>Notice the spread blowing up</em></strong></p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2012/10/correlated-returns.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-300" title="correlated-returns" src="http://gekkoquant.com/wp-content/uploads/2012/10/correlated-returns.jpeg"  alt="" width="653" height="653" /></a></p>
<p><strong>Example of cointegrated stocks: <em>Notice the spread looks oscillatory</em></strong></p>
<p><strong><em></em></strong><a href="http://gekkoquant.com/wp-content/uploads/2012/10/cointegrated-returns.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-299" title="cointegrated-returns" src="http://gekkoquant.com/wp-content/uploads/2012/10/cointegrated-returns.jpeg"  alt="" width="653" height="653" /></a>Onto the code to generate those plots (mainly taken from <a href="http://quant.stackexchange.com/questions/1027/how-are-correlation-and-cointegration-related">http://quant.stackexchange.com/questions/1027/how-are-correlation-and-cointegration-related</a>)</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p279code12'); return false;">View Code</a> RSPLUS</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p27912"><td class="code" id="p279code12"><pre class="rsplus" style="font-family:monospace;"> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span>MASS<span style="color: #080;">&#41;</span>
&nbsp;
 <span style="color: #228B22;">#Code largely copied from http://quant.stackexchange.com/questions/1027/how-are-correlation-and-cointegration-related</span>
&nbsp;
 <span style="color: #228B22;">#The input data</span>
 nsim <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">250</span>  <span style="color: #228B22;">#Number of data points</span>
 mu_a <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.0002</span>  <span style="color: #228B22;">#Mu_a growth rate for stock a</span>
 sigma_a <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.010</span>   <span style="color: #228B22;">#Sigma_a volatility for stock a</span>
 mu_b <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.0005</span>  <span style="color: #228B22;">#Mu_a growth rate for stock a</span>
 sigma_b <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.005</span>   <span style="color: #228B22;">#Sigma_a volatility for stock a</span>
 corxy <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.8</span>    <span style="color: #228B22;">#Correlation coeficient for xy</span>
&nbsp;
 <span style="color: #228B22;">#Calculate a correlated return series</span>
 <span style="color: #228B22;">#Build the covariance matrix and generate the correlated random results</span>
 <span style="color: #080;">&#40;</span>covmat <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/matrix.html"><span style="color: #0000FF; font-weight: bold;">matrix</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span>sigma_a<span style="color: #080;">^</span><span style="color: #ff0000;">2</span>, corxy<span style="color: #080;">*</span>sigma_a<span style="color: #080;">*</span>sigma_b, corxy<span style="color: #080;">*</span>sigma_a<span style="color: #080;">*</span>sigma_b, sigma_b<span style="color: #080;">^</span><span style="color: #ff0000;">2</span><span style="color: #080;">&#41;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/nrow.html"><span style="color: #0000FF; font-weight: bold;">nrow</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">2</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
 res <span style="color: #080;">&lt;-</span> mvrnorm<span style="color: #080;">&#40;</span>nsim, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span>mu_a, mu_b<span style="color: #080;">&#41;</span>, covmat<span style="color: #080;">&#41;</span>    <span style="color: #228B22;">#Calculate multivariate normal distribution</span>
 <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span>, res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">2</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
&nbsp;
 <span style="color: #228B22;">#Calculate the stats of res[] so they can be checked with the input data</span>
 <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/mean.html"><span style="color: #0000FF; font-weight: bold;">mean</span></a><span style="color: #080;">&#40;</span>res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
 <span style="color: #0000FF; font-weight: bold;">sd</span><span style="color: #080;">&#40;</span>res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
 <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/mean.html"><span style="color: #0000FF; font-weight: bold;">mean</span></a><span style="color: #080;">&#40;</span>res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">2</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
 <span style="color: #0000FF; font-weight: bold;">sd</span><span style="color: #080;">&#40;</span>res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">2</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
 <span style="color: #0000FF; font-weight: bold;">cor</span><span style="color: #080;">&#40;</span>res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span>, res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">2</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
&nbsp;
 path_a <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/exp.html"><span style="color: #0000FF; font-weight: bold;">exp</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cumsum.html"><span style="color: #0000FF; font-weight: bold;">cumsum</span></a><span style="color: #080;">&#40;</span>res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
 path_b <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/exp.html"><span style="color: #0000FF; font-weight: bold;">exp</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cumsum.html"><span style="color: #0000FF; font-weight: bold;">cumsum</span></a><span style="color: #080;">&#40;</span>res<span style="color: #080;">&#91;</span>,<span style="color: #ff0000;">2</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
 spread <span style="color: #080;">&lt;-</span> path_a <span style="color: #080;">-</span> path_b
                                 <span style="color: #228B22;">#Set the plotting area to a 2 by 1 grid</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/layout.html"><span style="color: #0000FF; font-weight: bold;">layout</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rbind.html"><span style="color: #0000FF; font-weight: bold;">rbind</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">2</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
 <span style="color: #228B22;">#Plot the two price series that have correlated returns</span>
 <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>path_a, main<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Two Price Series with Correlated Returns&quot;</span>, ylab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Price&quot;</span>, type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;l&quot;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span><span style="color: #080;">&#41;</span>
 <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/lines.html"><span style="color: #0000FF; font-weight: bold;">lines</span></a><span style="color: #080;">&#40;</span>path_b, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;blue&quot;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>spread, type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;l&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
 <span style="color: #228B22;">##Cointegrated pair</span>
 <span style="color: #228B22;">#The input data</span>
 nsim <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">250</span>  <span style="color: #228B22;">#Number of data points</span>
 mu_a <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.0002</span>  <span style="color: #228B22;">#Mu_a growth rate for stock a</span>
 sigma_a <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.010</span>   <span style="color: #228B22;">#Sigma_a volatility for stock a</span>
 mu_b <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.0002</span>  <span style="color: #228B22;">#Mu_a growth rate for stock a</span>
 sigma_b <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.005</span>   <span style="color: #228B22;">#Sigma_a volatility for stock a</span>
coea <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.0200</span>    <span style="color: #228B22;">#Co-integration coefficient for x</span>
coeb <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.0200</span>    <span style="color: #228B22;">#Co-integration coefficient for y</span>
&nbsp;
<span style="color: #228B22;">#Generate the noise terms for x and y</span>
rana <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">rnorm</span><span style="color: #080;">&#40;</span>nsim, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/mean.html"><span style="color: #0000FF; font-weight: bold;">mean</span></a><span style="color: #080;">=</span>mu_a, <span style="color: #0000FF; font-weight: bold;">sd</span><span style="color: #080;">=</span>sigma_a<span style="color: #080;">&#41;</span> <span style="color: #228B22;">#White noise for a</span>
ranb <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">rnorm</span><span style="color: #080;">&#40;</span>nsim, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/mean.html"><span style="color: #0000FF; font-weight: bold;">mean</span></a><span style="color: #080;">=</span>mu_b, <span style="color: #0000FF; font-weight: bold;">sd</span><span style="color: #080;">=</span>sigma_b<span style="color: #080;">&#41;</span> <span style="color: #228B22;">#White noise for b</span>
&nbsp;
<span style="color: #228B22;">#Generate the co-integrated series x and y</span>
a <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/numeric.html"><span style="color: #0000FF; font-weight: bold;">numeric</span></a><span style="color: #080;">&#40;</span>nsim<span style="color: #080;">&#41;</span>
b <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/numeric.html"><span style="color: #0000FF; font-weight: bold;">numeric</span></a><span style="color: #080;">&#40;</span>nsim<span style="color: #080;">&#41;</span>
a<span style="color: #080;">&#91;</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0</span>
b<span style="color: #080;">&#91;</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/for.html"><span style="color: #0000FF; font-weight: bold;">for</span></a> <span style="color: #080;">&#40;</span>i <span style="color: #0000FF; font-weight: bold;">in</span> <span style="color: #ff0000;">2</span><span style="color: #080;">:</span>nsim<span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span>
<span style="color: #228B22;">#Logic here is that is b&gt;a then we add on the difference so that</span>
<span style="color: #228B22;">#a starts to catch up with b, hence causing the spread to close</span>
  a<span style="color: #080;">&#91;</span>i<span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> a<span style="color: #080;">&#91;</span>i<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span> <span style="color: #080;">+</span> <span style="color: #080;">&#40;</span>coea <span style="color: #080;">*</span> <span style="color: #080;">&#40;</span>b<span style="color: #080;">&#91;</span>i<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span> <span style="color: #080;">-</span> a<span style="color: #080;">&#91;</span>i<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #080;">+</span> rana<span style="color: #080;">&#91;</span>i<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span>
  b<span style="color: #080;">&#91;</span>i<span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> b<span style="color: #080;">&#91;</span>i<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span> <span style="color: #080;">+</span> <span style="color: #080;">&#40;</span>coeb <span style="color: #080;">*</span> <span style="color: #080;">&#40;</span>a<span style="color: #080;">&#91;</span>i<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span> <span style="color: #080;">-</span> b<span style="color: #080;">&#91;</span>i<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #080;">+</span> ranb<span style="color: #080;">&#91;</span>i<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#93;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
<span style="color: #228B22;">#Plot a and b as prices</span>
ylim <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/range.html"><span style="color: #0000FF; font-weight: bold;">range</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/exp.html"><span style="color: #0000FF; font-weight: bold;">exp</span></a><span style="color: #080;">&#40;</span>a<span style="color: #080;">&#41;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/exp.html"><span style="color: #0000FF; font-weight: bold;">exp</span></a><span style="color: #080;">&#40;</span>b<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
path_a <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/exp.html"><span style="color: #0000FF; font-weight: bold;">exp</span></a><span style="color: #080;">&#40;</span>a<span style="color: #080;">&#41;</span>
path_b <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/exp.html"><span style="color: #0000FF; font-weight: bold;">exp</span></a><span style="color: #080;">&#40;</span>b<span style="color: #080;">&#41;</span>
spread <span style="color: #080;">&lt;-</span> path_a <span style="color: #080;">-</span> path_b
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/layout.html"><span style="color: #0000FF; font-weight: bold;">layout</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rbind.html"><span style="color: #0000FF; font-weight: bold;">rbind</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">1</span>,<span style="color: #ff0000;">2</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>path_a, ylim<span style="color: #080;">=</span>ylim, type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;l&quot;</span>, main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Co-integrated Pair (coea=&quot;</span>,coea,<span style="color: #ff0000;">&quot;,  coeb=&quot;</span>,coeb,<span style="color: #ff0000;">&quot;)&quot;</span>, sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span>, ylab<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;Price&quot;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;red&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/lines.html"><span style="color: #0000FF; font-weight: bold;">lines</span></a><span style="color: #080;">&#40;</span>path_b, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><span style="color: #ff0000;">&quot;blue&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/legend.html"><span style="color: #0000FF; font-weight: bold;">legend</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;bottomleft&quot;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;exp(a)&quot;</span>, <span style="color: #ff0000;">&quot;exp(b)&quot;</span><span style="color: #080;">&#41;</span>, lty<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">1</span>, <span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/col.html"><span style="color: #0000FF; font-weight: bold;">col</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;red&quot;</span>, <span style="color: #ff0000;">&quot;blue&quot;</span><span style="color: #080;">&#41;</span>, bg<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;white&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/plot.html"><span style="color: #0000FF; font-weight: bold;">plot</span></a><span style="color: #080;">&#40;</span>spread,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;l&quot;</span><span style="color: #080;">&#41;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2012/10/21/statistical-arbitrage-correlation-vs-cointegration/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Parameter Optimisation &amp; Backtesting &#8211; Part 2</title>
		<link>http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part-2/</link>
		<comments>http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part-2/#comments</comments>
		<pubDate>Wed, 29 Aug 2012 00:36:05 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[R Code]]></category>
		<category><![CDATA[Trading Strategy]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=260</guid>
		<description><![CDATA[This is a follow on from: http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part1/ The code presented here will aim to optimise a strategy based upon the simple moving average indicator. The strategy will go Long when moving average A &#62; moving average B. The optimisation is to determine &#8230; <a href="http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This is a follow on from: <a href="http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part1/">http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part1/</a></p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2012/08/MovingAverage-backtest.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-262" title="MovingAverage-backtest" src="http://gekkoquant.com/wp-content/uploads/2012/08/MovingAverage-backtest.jpeg"  alt="" width="653" height="653" /></a></p>
<p><a href="http://gekkoquant.com/wp-content/uploads/2012/08/MovingAverage-outofsample.jpeg" class="gallery_colorbox"><img class="aligncenter size-full wp-image-261" title="MovingAverage-outofsample" src="http://gekkoquant.com/wp-content/uploads/2012/08/MovingAverage-outofsample.jpeg"  alt="" width="653" height="653" /></a></p>
<p>The code presented here will aim to optimise a strategy based upon the simple moving average indicator. The strategy will go Long when moving average A &gt; moving average B. The optimisation is to determine what period to make each of the moving averages A &amp; B.</p>
<p>Please note that this isn&#8217;t intended to be a good strategy, it is merely here to give an example of how to optimise a parameter.</p>
<p>Onto the code:</p>
<p><strong>Functions</strong></p>
<ul>
<li><strong>TradingStrategy</strong> this function implements the trading logic and calculates the returns</li>
<li><strong>RunIterativeStrategy </strong>this function iterates through possible parameter combinations and calls TradingStrategy for each new parameter set</li>
<li><strong>CalculatePerformanceMetric </strong>takes in a table of returns (from RunIterativeStrategy) and runs a function/metric over each set of returns.</li>
<li><strong>PerformanceTable</strong> calls CalculatePerformanceMetric for lots of different metric and compiles the results into a table</li>
<li><strong>OrderPerformanceTable</strong> lets us order the performance table by a given metric, ie order by highest sharpe ratio</li>
<li><strong>SelectTopNStrategies</strong> selects the best N strategies for a specified performance metric (charts.PerformanceSummary can only plot ~20 strategies, hence this function to select a sample)</li>
<li><strong>FindOptimumStrategy</strong> does what it says on the tin</li>
</ul>
<div>Note that when performing the out of sample test, you will need to manual specify the parameter set that you wish to use.</div>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p260code14'); return false;">View Code</a> RSPLUS</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p26014"><td class="code" id="p260code14"><pre class="rsplus" style="font-family:monospace;">&nbsp;
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;quantmod&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;PerformanceAnalytics&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
nameOfStrategy <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;GSPC Moving Average Strategy&quot;</span>
&nbsp;
<span style="color: #228B22;">#Specify dates for downloading data, training models and running simulation</span>
trainingStartDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2000-01-01&quot;</span><span style="color: #080;">&#41;</span>
trainingEndDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2010-01-01&quot;</span><span style="color: #080;">&#41;</span>
outofSampleStartDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2010-01-02&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
<span style="color: #228B22;">#Download the data</span>
symbolData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/new.env.html"><span style="color: #0000FF; font-weight: bold;">new.<span style="">env</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Make a new environment for quantmod to store data in</span>
getSymbols<span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;^GSPC&quot;</span>, env <span style="color: #080;">=</span> symbolData, src <span style="color: #080;">=</span> <span style="color: #ff0000;">&quot;yahoo&quot;</span>, from <span style="color: #080;">=</span> trainingStartDate<span style="color: #080;">&#41;</span>
trainingData <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">window</span><span style="color: #080;">&#40;</span>symbolData$GSPC, <span style="color: #0000FF; font-weight: bold;">start</span> <span style="color: #080;">=</span> trainingStartDate, <span style="color: #0000FF; font-weight: bold;">end</span> <span style="color: #080;">=</span> trainingEndDate<span style="color: #080;">&#41;</span>
testData <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">window</span><span style="color: #080;">&#40;</span>symbolData$GSPC, <span style="color: #0000FF; font-weight: bold;">start</span> <span style="color: #080;">=</span> outofSampleStartDate<span style="color: #080;">&#41;</span>
indexReturns <span style="color: #080;">&lt;-</span> Delt<span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span><span style="color: #0000FF; font-weight: bold;">window</span><span style="color: #080;">&#40;</span>symbolData$GSPC, <span style="color: #0000FF; font-weight: bold;">start</span> <span style="color: #080;">=</span> outofSampleStartDate<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>indexReturns<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;GSPC Buy&amp;Hold&quot;</span>
&nbsp;
TradingStrategy <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>mktdata,mavga_period,mavgb_period<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  <span style="color: #228B22;">#This is where we define the trading strategy</span>
  <span style="color: #228B22;">#Check moving averages at start of the day and use as the direciton signal</span>
  <span style="color: #228B22;">#Enter trade at the start of the day and exit at the close</span>
&nbsp;
  <span style="color: #228B22;">#Lets print the name of whats running</span>
  runName <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;MAVGa&quot;</span>,mavga_period,<span style="color: #ff0000;">&quot;.b&quot;</span>,mavgb_period,sep<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Running Strategy: &quot;</span>,runName<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
&nbsp;
  <span style="color: #228B22;">#Calculate the Open Close return</span>
  returns <span style="color: #080;">&lt;-</span> <span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">/</span>Op<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">-</span><span style="color: #ff0000;">1</span>
&nbsp;
  <span style="color: #228B22;">#Calculate the moving averages</span>
  mavga <span style="color: #080;">&lt;-</span> SMA<span style="color: #080;">&#40;</span>Op<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span>,n<span style="color: #080;">=</span>mavga_period<span style="color: #080;">&#41;</span>
  mavgb <span style="color: #080;">&lt;-</span> SMA<span style="color: #080;">&#40;</span>Op<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span>,n<span style="color: #080;">=</span>mavgb_period<span style="color: #080;">&#41;</span>
&nbsp;
  signal <span style="color: #080;">&lt;-</span> mavga <span style="color: #080;">/</span> mavgb
  <span style="color: #228B22;">#If mavga &gt; mavgb go long</span>
  signal <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/apply.html"><span style="color: #0000FF; font-weight: bold;">apply</span></a><span style="color: #080;">&#40;</span>signal,<span style="color: #ff0000;">1</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a> <span style="color: #080;">&#40;</span>x<span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>x<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span><span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#125;</span> <span style="color: #0000FF; font-weight: bold;">else</span> <span style="color: #080;">&#123;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span>x<span style="color: #080;">&gt;</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#125;</span> <span style="color: #0000FF; font-weight: bold;">else</span> <span style="color: #080;">&#123;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span><span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>
&nbsp;
  tradingreturns <span style="color: #080;">&lt;-</span> signal <span style="color: #080;">*</span> returns
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>tradingreturns<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> runName
&nbsp;
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span>tradingreturns<span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
RunIterativeStrategy <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  <span style="color: #228B22;">#This function will run the TradingStrategy</span>
  <span style="color: #228B22;">#It will iterate over a given set of input variables</span>
  <span style="color: #228B22;">#In this case we try lots of different periods for the moving average</span>
  firstRun <span style="color: #080;">&lt;-</span> TRUE
    <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/for.html"><span style="color: #0000FF; font-weight: bold;">for</span></a><span style="color: #080;">&#40;</span>a <span style="color: #0000FF; font-weight: bold;">in</span> <span style="color: #ff0000;">1</span><span style="color: #080;">:</span><span style="color: #ff0000;">10</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span>
        <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/for.html"><span style="color: #0000FF; font-weight: bold;">for</span></a><span style="color: #080;">&#40;</span>b <span style="color: #0000FF; font-weight: bold;">in</span> <span style="color: #ff0000;">1</span><span style="color: #080;">:</span><span style="color: #ff0000;">10</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span>
&nbsp;
          runResult <span style="color: #080;">&lt;-</span> TradingStrategy<span style="color: #080;">&#40;</span>mktdata,a,b<span style="color: #080;">&#41;</span>
&nbsp;
          <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span>firstRun<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
              firstRun <span style="color: #080;">&lt;-</span> FALSE
              results <span style="color: #080;">&lt;-</span> runResult
          <span style="color: #080;">&#125;</span> <span style="color: #0000FF; font-weight: bold;">else</span> <span style="color: #080;">&#123;</span>
              results <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>results,runResult<span style="color: #080;">&#41;</span>
          <span style="color: #080;">&#125;</span>
        <span style="color: #080;">&#125;</span>
    <span style="color: #080;">&#125;</span>
&nbsp;
   <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a><span style="color: #080;">&#40;</span>results<span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
CalculatePerformanceMetric <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>returns,metric<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  <span style="color: #228B22;">#Get given some returns in columns</span>
  <span style="color: #228B22;">#Apply the function metric to the data</span>
&nbsp;
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a> <span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Calculating Performance Metric:&quot;</span>,metric<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
&nbsp;
  metricFunction <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/match.fun.html"><span style="color: #0000FF; font-weight: bold;">match.<span style="">fun</span></span></a><span style="color: #080;">&#40;</span>metric<span style="color: #080;">&#41;</span>
  metricData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.matrix.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">matrix</span></span></a><span style="color: #080;">&#40;</span>metricFunction<span style="color: #080;">&#40;</span>returns<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
  <span style="color: #228B22;">#Some functions return the data the wrong way round</span>
  <span style="color: #228B22;">#Hence cant label columns to need to check and transpose it</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/nrow.html"><span style="color: #0000FF; font-weight: bold;">nrow</span></a><span style="color: #080;">&#40;</span>metricData<span style="color: #080;">&#41;</span> <span style="color: #080;">==</span> <span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
    metricData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/t.html"><span style="color: #0000FF; font-weight: bold;">t</span></a><span style="color: #080;">&#40;</span>metricData<span style="color: #080;">&#41;</span>
  <span style="color: #080;">&#125;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>metricData<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> metric
&nbsp;
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span>metricData<span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
PerformanceTable <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>returns<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  pMetric <span style="color: #080;">&lt;-</span> CalculatePerformanceMetric<span style="color: #080;">&#40;</span>returns,<span style="color: #ff0000;">&quot;colSums&quot;</span><span style="color: #080;">&#41;</span>
  pMetric <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>pMetric,CalculatePerformanceMetric<span style="color: #080;">&#40;</span>returns,<span style="color: #ff0000;">&quot;SharpeRatio.annualized&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
  pMetric <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>pMetric,CalculatePerformanceMetric<span style="color: #080;">&#40;</span>returns,<span style="color: #ff0000;">&quot;maxDrawdown&quot;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>pMetric<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Profit&quot;</span>,<span style="color: #ff0000;">&quot;SharpeRatio&quot;</span>,<span style="color: #ff0000;">&quot;MaxDrawDown&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Performance Table&quot;</span><span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span>pMetric<span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span>pMetric<span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
OrderPerformanceTable <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>performanceTable,metric<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span>performanceTable<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/order.html"><span style="color: #0000FF; font-weight: bold;">order</span></a><span style="color: #080;">&#40;</span>performanceTable<span style="color: #080;">&#91;</span>,metric<span style="color: #080;">&#93;</span>,decreasing<span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span>,<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
SelectTopNStrategies <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>returns,performanceTable,metric,n<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
<span style="color: #228B22;">#Metric is the name of the function to apply to the column to select the Top N</span>
<span style="color: #228B22;">#n is the number of strategies to select</span>
  pTab <span style="color: #080;">&lt;-</span> OrderPerformanceTable<span style="color: #080;">&#40;</span>performanceTable,metric<span style="color: #080;">&#41;</span>
&nbsp;
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span>n <span style="color: #080;">&gt;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/ncol.html"><span style="color: #0000FF; font-weight: bold;">ncol</span></a><span style="color: #080;">&#40;</span>returns<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
     n <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/ncol.html"><span style="color: #0000FF; font-weight: bold;">ncol</span></a><span style="color: #080;">&#40;</span>returns<span style="color: #080;">&#41;</span>
  <span style="color: #080;">&#125;</span>
  strategyNames <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/rownames.html"><span style="color: #0000FF; font-weight: bold;">rownames</span></a><span style="color: #080;">&#40;</span>pTab<span style="color: #080;">&#41;</span><span style="color: #080;">&#91;</span><span style="color: #ff0000;">1</span><span style="color: #080;">:</span>n<span style="color: #080;">&#93;</span>
  topNMetrics <span style="color: #080;">&lt;-</span> returns<span style="color: #080;">&#91;</span>,strategyNames<span style="color: #080;">&#93;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span>topNMetrics<span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
FindOptimumStrategy <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>trainingData<span style="color: #080;">&#41;</span><span style="color: #080;">&#123;</span>
  <span style="color: #228B22;">#Optimise the strategy</span>
  trainingReturns <span style="color: #080;">&lt;-</span> RunIterativeStrategy<span style="color: #080;">&#40;</span>trainingData<span style="color: #080;">&#41;</span>
  pTab <span style="color: #080;">&lt;-</span> PerformanceTable<span style="color: #080;">&#40;</span>trainingReturns<span style="color: #080;">&#41;</span>
  toptrainingReturns <span style="color: #080;">&lt;-</span> SelectTopNStrategies<span style="color: #080;">&#40;</span>trainingReturns,pTab,<span style="color: #ff0000;">&quot;SharpeRatio&quot;</span>,<span style="color: #ff0000;">5</span><span style="color: #080;">&#41;</span>
  charts.<span style="">PerformanceSummary</span><span style="color: #080;">&#40;</span>toptrainingReturns,main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span>nameOfStrategy,<span style="color: #ff0000;">&quot;- Training&quot;</span><span style="color: #080;">&#41;</span>,geometric<span style="color: #080;">=</span>FALSE<span style="color: #080;">&#41;</span>
  <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span>pTab<span style="color: #080;">&#41;</span>
<span style="color: #080;">&#125;</span>
&nbsp;
pTab <span style="color: #080;">&lt;-</span> FindOptimumStrategy<span style="color: #080;">&#40;</span>trainingData<span style="color: #080;">&#41;</span> <span style="color: #228B22;">#pTab is the performance table of the various parameters tested</span>
&nbsp;
<span style="color: #228B22;">#Test out of sample</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">#Manually specify the parameter that we want to trade here, just because a strategy is at the top of</span>
<span style="color: #228B22;">#pTab it might not be good (maybe due to overfit)</span>
outOfSampleReturns <span style="color: #080;">&lt;-</span> TradingStrategy<span style="color: #080;">&#40;</span>testData,mavga_period<span style="color: #080;">=</span><span style="color: #ff0000;">9</span>,mavgb_period<span style="color: #080;">=</span><span style="color: #ff0000;">6</span><span style="color: #080;">&#41;</span>
finalReturns <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>outOfSampleReturns,indexReturns<span style="color: #080;">&#41;</span>
charts.<span style="">PerformanceSummary</span><span style="color: #080;">&#40;</span>finalReturns,main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span>nameOfStrategy,<span style="color: #ff0000;">&quot;- Out of Sample&quot;</span><span style="color: #080;">&#41;</span>,geometric<span style="color: #080;">=</span>FALSE<span style="color: #080;">&#41;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Parameter Optimisation &amp; Backtesting &#8211; Part 1</title>
		<link>http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part1/</link>
		<comments>http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part1/#comments</comments>
		<pubDate>Wed, 29 Aug 2012 00:10:56 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=253</guid>
		<description><![CDATA[When developing a strategy that uses a technical indicator, such as a moving average, it is often difficult to decide on what period to use with the indicator. Should it look at the last 10, 20, or n days? The &#8230; <a href="http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>When developing a strategy that uses a technical indicator, such as a moving average, it is often difficult to decide on what period to use with the indicator. Should it look at the last 10, 20, or n days? The simple solution is just to iterate over many different parameters and look for the parameter combination that optimises a performance metric perhaps the Sharpe Ratio or minimises the Max Drawdown or some combination of both of them.</p>
<p>This method must be approached in a sensible manner, essentially we are fitting the strategy to the data and must be careful not to over fit and capture spurious profits. It is likely that any parameter that is trained will vary over time, the strategy must be able to deal with changes to this parameter.</p>
<p>For example say we are tuning the variable A, and we find that the optimum solution is A=n in the training data (it is very profitable with high sharpe ratio). How well does the strategy perform when we set A=n+1, or A=n-1 do we still get good results? If you don&#8217;t it&#8217;s an indicator that maybe you have over fitted.</p>
<p>For more discussion on this see <a href="http://epchan.blogspot.co.uk/2010/01/method-for-optimizing-parameters.html">http://epchan.blogspot.co.uk/2010/01/method-for-optimizing-parameters.html</a></p>
<p>Part two will contain a script to perform an optimisation on a simple moving average strategy.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2012/08/29/parameter-optimisation-backtesting-part1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Trading Strategy &#8211; VWAP Mean Reversion</title>
		<link>http://gekkoquant.com/2012/07/31/trading-strategy-vwap-mean-reversion/</link>
		<comments>http://gekkoquant.com/2012/07/31/trading-strategy-vwap-mean-reversion/#comments</comments>
		<pubDate>Tue, 31 Jul 2012 13:42:29 +0000</pubDate>
		<dc:creator>GekkoQuant</dc:creator>
				<category><![CDATA[R Code]]></category>
		<category><![CDATA[Trading Strategy]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gekkoquant.com/?p=247</guid>
		<description><![CDATA[This strategy is going to use the volume weighted average price (VWAP) as an indicator to trade mean version back to VWAP. Annualized Sharpe Ratio (Rf=0%) is 0.9016936. This post is a response to http://gekkoquant.com/2012/07/29/trading-strategy-sp-vwap-trend-follow/ where there was a bug in the &#8230; <a href="http://gekkoquant.com/2012/07/31/trading-strategy-vwap-mean-reversion/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://gekkoquant.com/wp-content/uploads/2012/07/sp-500-VWAP-mean-revert.jpeg" class="gallery_colorbox"><img src="http://gekkoquant.com/wp-content/uploads/2012/07/sp-500-VWAP-mean-revert.jpeg"  alt="" title="s&amp;p 500 VWAP mean revert" width="653" height="653" class="aligncenter size-full wp-image-248" /></a></p>
<p>This strategy is going to use the volume weighted average price (VWAP) as an indicator to trade mean version back to VWAP. <strong>Annualized Sharpe Ratio (Rf=0%) is</strong><span style="color: #ff0000;"><strong> 0.9016936</strong></span>.</p>
<p>This post is a response to <a href="http://gekkoquant.com/2012/07/29/trading-strategy-sp-vwap-trend-follow/" title="S&#038;P VWAP Trend Follow">http://gekkoquant.com/2012/07/29/trading-strategy-sp-vwap-trend-follow/</a> where there was a bug in the code indicating that VWAP wasn&#8217;t reverting (this didn&#8217;t sit well with me, or some of the people who commented). As always don&#8217;t take my word for anything, backtest the strategy yourself. One of the dangers of using R or Matlab is that it&#8217;s easy for forward bias to slip into your code. There are libraries such as Quantstrat for R which protect against this, but I&#8217;ve found them terribly slow to run.</p>
<p>Trade logic:</p>
<ul>
<li>All conditions are checked at the close, and the trade held for one day from the close</li>
<li>If price/vwap &gt; uLim go short</li>
<li>If price/vwap &lt; lLim go long</li>
</ul>
<p>Onto the code:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p247code16'); return false;">View Code</a> RSPLUS</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p24716"><td class="code" id="p247code16"><pre class="rsplus" style="font-family:monospace;"><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;quantmod&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/library.html"><span style="color: #0000FF; font-weight: bold;">library</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;PerformanceAnalytics&quot;</span><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Trade logic - Look for mean reversion</span>
<span style="color: #228B22;">#If price/vwap &gt; uLim go SHORT</span>
<span style="color: #228B22;">#If price/vwap &lt; lLim go LONG</span>
&nbsp;
<span style="color: #228B22;">#Script parameters</span>
symbol <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;^GSPC&quot;</span>     <span style="color: #228B22;">#Symbol</span>
nlookback <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">3</span> <span style="color: #228B22;">#Number of days to lookback and calculate vwap</span>
uLim <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">1.001</span>  <span style="color: #228B22;">#If price/vwap &gt; uLim enter a short trade</span>
lLim <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">0.999</span>  <span style="color: #228B22;">#If price/vwap &lt; lLim enter a long trade</span>
&nbsp;
&nbsp;
<span style="color: #228B22;">#Specify dates for downloading data</span>
startDate <span style="color: #080;">=</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/as.Date.html"><span style="color: #0000FF; font-weight: bold;">as.<span style="">Date</span></span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;2006-01-01&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Specify what date to get the prices from</span>
symbolData <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/new.env.html"><span style="color: #0000FF; font-weight: bold;">new.<span style="">env</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Make a new environment for quantmod to store data in</span>
getSymbols<span style="color: #080;">&#40;</span>symbol, env <span style="color: #080;">=</span> symbolData, src <span style="color: #080;">=</span> <span style="color: #ff0000;">&quot;yahoo&quot;</span>, from <span style="color: #080;">=</span> startDate<span style="color: #080;">&#41;</span>
mktdata <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/eval.html"><span style="color: #0000FF; font-weight: bold;">eval</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/parse.html"><span style="color: #0000FF; font-weight: bold;">parse</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/text.html"><span style="color: #0000FF; font-weight: bold;">text</span></a><span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;symbolData$&quot;</span>,<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/sub.html"><span style="color: #0000FF; font-weight: bold;">sub</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;^&quot;</span>,<span style="color: #ff0000;">&quot;&quot;</span>,symbol,fixed<span style="color: #080;">=</span>TRUE<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
mktdata <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">head</span><span style="color: #080;">&#40;</span>mktdata,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Hack to fix some stupid duplicate date problem with yahoo</span>
&nbsp;
<span style="color: #228B22;">#Calculate volume weighted average price</span>
vwap <span style="color: #080;">&lt;-</span> VWAP<span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span>, Vo<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span>, n<span style="color: #080;">=</span>nlookback<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">#Can calculate vwap like this, but it is slower</span>
<span style="color: #228B22;">#vwap &lt;- runSum(Cl(mktdata)*Vo(mktdata),nlookback)/runSum(Vo(mktdata),nlookback)</span>
&nbsp;
<span style="color: #228B22;">#Calulate the daily returns</span>
dailyRet <span style="color: #080;">&lt;-</span> Delt<span style="color: #080;">&#40;</span>Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span>,k<span style="color: #080;">=</span><span style="color: #ff0000;">1</span>,type<span style="color: #080;">=</span><span style="color: #ff0000;">&quot;arithmetic&quot;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Daily Returns</span>
&nbsp;
<span style="color: #228B22;">#signal = price/vwap</span>
signal <span style="color: #080;">&lt;-</span> Cl<span style="color: #080;">&#40;</span>mktdata<span style="color: #080;">&#41;</span> <span style="color: #080;">/</span> vwap
signal<span style="color: #080;">&#91;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/is.na.html"><span style="color: #0000FF; font-weight: bold;">is.<span style="">na</span></span></a><span style="color: #080;">&#40;</span>signal<span style="color: #080;">&#41;</span><span style="color: #080;">&#93;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">1</span> <span style="color: #228B22;">#Setting to one means that no trade will occur for NA's</span>
<span style="color: #228B22;">#Stripping NA's caused all manner of problems in a previous post</span>
trade <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/apply.html"><span style="color: #0000FF; font-weight: bold;">apply</span></a><span style="color: #080;">&#40;</span>signal,<span style="color: #ff0000;">1</span>, <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/function.html"><span style="color: #0000FF; font-weight: bold;">function</span></a><span style="color: #080;">&#40;</span>x<span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span>x<span style="color: #080;">&lt;</span>lLim<span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#125;</span> <span style="color: #0000FF; font-weight: bold;">else</span> <span style="color: #080;">&#123;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/if.html"><span style="color: #0000FF; font-weight: bold;">if</span></a><span style="color: #080;">&#40;</span>x<span style="color: #080;">&gt;</span>uLim<span style="color: #080;">&#41;</span> <span style="color: #080;">&#123;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a><span style="color: #080;">&#40;</span><span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#125;</span> <span style="color: #0000FF; font-weight: bold;">else</span> <span style="color: #080;">&#123;</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/return.html"><span style="color: #0000FF; font-weight: bold;">return</span></a> <span style="color: #080;">&#40;</span><span style="color: #ff0000;">0</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#125;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Calculate the P&amp;L</span>
<span style="color: #228B22;">#The daily ret is DailyRet(T)=(Close(T)-Close(T-1))/Close(T-1)</span>
<span style="color: #228B22;">#We enter the trade on day T so need the DailyRet(T+1) as our potential profit</span>
<span style="color: #228B22;">#Hence the lag in the line below</span>
strategyReturns <span style="color: #080;">&lt;-</span> trade <span style="color: #080;">*</span> <span style="color: #0000FF; font-weight: bold;">lag</span><span style="color: #080;">&#40;</span>dailyRet,<span style="color: #080;">-</span><span style="color: #ff0000;">1</span><span style="color: #080;">&#41;</span>
strategyReturns <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">na.<span style="">omit</span></span><span style="color: #080;">&#40;</span>strategyReturns<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#### Performance Analysis ###</span>
<span style="color: #228B22;">#Calculate returns for the index</span>
indexRet <span style="color: #080;">&lt;-</span> dailyRet <span style="color: #228B22;">#Daily returns</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>indexRet<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <span style="color: #ff0000;">&quot;IndexRet&quot;</span>
zooTradeVec <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cbind.html"><span style="color: #0000FF; font-weight: bold;">cbind</span></a><span style="color: #080;">&#40;</span>as.<span style="">zoo</span><span style="color: #080;">&#40;</span>strategyReturns<span style="color: #080;">&#41;</span>,as.<span style="">zoo</span><span style="color: #080;">&#40;</span>indexRet<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">#Convert to zoo object</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/colnames.html"><span style="color: #0000FF; font-weight: bold;">colnames</span></a><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span> <span style="color: #080;">&lt;-</span> <a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/c.html"><span style="color: #0000FF; font-weight: bold;">c</span></a><span style="color: #080;">&#40;</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span>symbol,<span style="color: #ff0000;">&quot; VWAP Trade&quot;</span><span style="color: #080;">&#41;</span>,symbol<span style="color: #080;">&#41;</span>
zooTradeVec <span style="color: #080;">&lt;-</span> <span style="color: #0000FF; font-weight: bold;">na.<span style="">omit</span></span><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">#Lets see how all the strategies faired against the index</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/stats/html/summary.lm.html"><span style="color: #0000FF; font-weight: bold;">dev.<span style="">new</span></span></a><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
charts.<span style="">PerformanceSummary</span><span style="color: #080;">&#40;</span>zooTradeVec,main<span style="color: #080;">=</span><a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/paste.html"><span style="color: #0000FF; font-weight: bold;">paste</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Performance of &quot;</span>, symbol, <span style="color: #ff0000;">&quot; VWAP Strategy&quot;</span><span style="color: #080;">&#41;</span>,geometric<span style="color: #080;">=</span>FALSE<span style="color: #080;">&#41;</span>
&nbsp;
&nbsp;
<span style="color: #228B22;">#Lets calculate a table of montly returns by year and strategy</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cat.html"><span style="color: #0000FF; font-weight: bold;">cat</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Calander Returns - Note 13.5 means a return of 13.5%<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span>table.<span style="">CalendarReturns</span><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">#Calculate the sharpe ratio</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/cat.html"><span style="color: #0000FF; font-weight: bold;">cat</span></a><span style="color: #080;">&#40;</span><span style="color: #ff0000;">&quot;Sharpe Ratio&quot;</span><span style="color: #080;">&#41;</span>
<a href="http://astrostatistics.psu.edu/su07/R/html/graphics/html/print.html"><span style="color: #0000FF; font-weight: bold;">print</span></a><span style="color: #080;">&#40;</span>SharpeRatio.<span style="">annualized</span><span style="color: #080;">&#40;</span>zooTradeVec<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://gekkoquant.com/2012/07/31/trading-strategy-vwap-mean-reversion/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
