Overall Statistics
Total Trades
686
Average Win
0.43%
Average Loss
-0.41%
Compounding Annual Return
14.687%
Drawdown
9.200%
Expectancy
0.102
Net Profit
14.696%
Sharpe Ratio
1.09
Loss Rate
47%
Win Rate
53%
Profit-Loss Ratio
1.07
Alpha
0.142
Beta
-0.112
Annual Standard Deviation
0.107
Annual Variance
0.011
Information Ratio
-0.718
Tracking Error
0.154
Treynor Ratio
-1.044
Total Fees
$1219.56
namespace QuantConnect 
{   
    /*
    *   QuantConnect University: pairs trading, MACD example
    *   by Jean-Paul van Brakel
    */
    public class PairsTradingAlgorithm : QCAlgorithm
    {
    	decimal _diff;
    	MovingAverageConvergenceDivergence _macd;
    	
        //Initialize the data and resolution you require for your strategy:
        public override void Initialize() 
        {
            //Start and End Date range for the backtest:
            SetStartDate(2013, 1, 1);         
            SetEndDate(2014, 1, 1);
            
            //Cash allocation
            SetCash(25000);
            
            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, "AAPL", Resolution.Minute);
            AddSecurity(SecurityType.Equity, "MSFT", Resolution.Minute);
            
            //Initialise MACD
            _macd = new MovingAverageConvergenceDivergence(12, 26, 9, MovingAverageType.Simple);
        }

        //Data Event Handler: All data arrives here in slices.
        public override void OnData(Slice slice) 
        {   
        	if (!slice.ContainsKey("MSFT") || !slice.ContainsKey("AAPL")) return;
        	
            //Calculate difference MSFT and AAPL
            _diff = slice["MSFT"].Close - slice["AAPL"].Close;
            
            //Update MACD
            _macd.Update(slice.Time, _diff);
            
            //Calculate MACD difference
			decimal signalDeltaPercent = (_macd - _macd.Signal)/_macd.Fast;
            var tolerance = 0.0025m;
            
            //If MACD gives signal and we're not in a position right now
            if (!Portfolio.HoldStock && signalDeltaPercent > tolerance) 
            {
                //Calculate quantities of individual positions
                int quantityA = (int)Math.Floor(0.5M*Portfolio.Cash/slice["MSFT"].Close);
                int quantityB = (int)Math.Floor(0.5M*Portfolio.Cash/slice["AAPL"].Close);
                
                //Go long on first, go short on second
                Order("MSFT",  quantityA);
                Order("AAPL",  -quantityB);
            } else if (signalDeltaPercent < -tolerance) {
            	//If MACD gives opposite signal
            	Liquidate("MSFT");
            	Liquidate("AAPL");
            }
            
            //Plot MACD lines
            Plot("MACD", "Difference", _diff);
            Plot("MACD", _macd.Fast, _macd.Slow);
        }
    }
}