title: How to back test pairs trading strategies in R
body: <p>I am trying to learn about pairs trading strategy and I am using this <a href="https://quant.stackexchange.com/a/28043/16754">pseudo code</a> for writing my R programme.</p>
  
  <pre><code>if X and Y are cointegrated:
      calculate Beta between X and Y 
      calculate spread as X - Beta * Y
      calculate z-score of spread
  
      # entering trade (spread is away from mean by two sigmas):
      if z-score &gt; 2:
          sell spread (sell 1000 of X, buy 1000 * Beta of Y)
      if z-score &lt; -2:
          buy spread (buy 1000 of X, sell 1000 * Beta of Y)
  
      # exiting trade (spread converged close to mean):
      if we're short spread and z-score &lt; 1:
          close the trades
      if we're long spread and z-score &gt; -1:
          close the trades
  
  # repeat above on each new bar, recalculating rolling Beta and spread etc.
  </code></pre>
  
  <p>I am currently using <code>Systematic Investor Toolbox (SIT)</code>  for backtesting using technical analysis but I dont know how to do backtest pair trading strategies using SIT.</p>
  
  <pre><code>#data downloading
  library(quantmod)
  
  #downloading cointegrated pepsi and coca cola time series data from yahoo
  pep&lt;-getSymbols("PEP",start="2010-01-01",auto.assign=F)
  ko&lt;-getSymbols("KO",start="2010-01-01",auto.assign=F)
  
  #close price of pepsi and coca cola
  pepc&lt;-Cl(pep)
  koc&lt;-Cl(ko)
  
  #rolling regression of close price of pepsi vs coca cola
  reg= rollSFM(pepc,koc , 50)
  
  
  #calculating spread
  spread=pepc-reg$beta*koc
  
  #mean of the spread
  avg=mean(spread)
  
  #standard deviation of spread
  std=sd(spread)
  
  #z-score
  z=(spread-avg)/std
  
  #pair trading longing and shorting
  if(z&gt; 2){
    sell spread()
    t=1
  } else if(z&lt;-2) {
    buy spread()
    t=2
  }
  else if(z&lt;1&amp;t=1) {
    close the short trade
  }else if(z&gt;-1&amp;t=2) {
    close the long trade
  }
  </code></pre>
  
  <p>The current problem is how to simulate buying and selling of pairs in SIT. If SIT cant do pairs trading strategy back testing then how should I perform pairs trading strategy especially entering and exiting. What logic should I use?</p>
  
  <p>EDIT</p>
  
  <p>After searching a while I know that we can make a backtester from scratch using <code>PerformanceAnalytics</code>; but before back testing we have to create signal and return values. Below is a sample code</p>
  
  <pre><code>library(quantmod)
  library(PerformanceAnalytics)
  
  s &lt;- get(getSymbols('SPY'))["2016::"]
  s$sma20 &lt;- SMA(Cl(s) , 20)
  s$signal &lt;- ifelse(Cl(s) &gt; s$sma20 , 1 , -1)
  myReturn &lt;- lag(s$signal) * dailyReturn(s)
  charts.PerformanceSummary(cbind(dailyReturn(s),myReturn))
  </code></pre>
  
  <p>In the above code creating signal is easy but for pairs trading what logic should I use for creating signals and return for that signals?</p>