Overall Statistics
Total Trades
65
Average Win
1.65%
Average Loss
-0.81%
Annual Return
12.921%
Drawdown
16.700%
Expectancy
1.206
Net Profit
85.783%
Sharpe Ratio
0.8
Loss Rate
28%
Win Rate
72%
Profit-Loss Ratio
2.05
Trade Frequency
Weekly trades
using System;
using System.Collections;
using System.Collections.Generic;
using QuantConnect.Securities;
using QuantConnect.Models;

namespace QuantConnect {

    //  HOW TO USE:
    //  1. Create new instance of consolidator: 5 minutes / 5 bars joined.
    //   public Consolidator barConsolidator = new Consolidator(5);
    //
    //  2. Exit the dataHandler until it returns true:
    //      //Add this 1 min to the Consolidator.
    //      if (!barConsolidator.Update(data["MSFT"])) return;
    //
    //  3. Once we have 5 bars it returns true, and we fetch the bar here:
    //      TradeBar msft = barConsolidator.Bar;
    //
	public class Consolidator {
        
        private int requestedCount = 0;
        private int barCount = 0;
        private Queue<TradeBar> barQueue;
        
           
        //Accessor - Create the x-"Bar" when the Update returns true.
        public TradeBar Bar {
            get {
                return this.Generate();
            }
        }
        
        //Initialize the Consolidator
        public Consolidator(int iBars) {
            //Number of TradeBars we want to join together (e.g. 5 min bars = 5 x 1 min bars)
            this.requestedCount = iBars;
            this.barCount = 0;
            // Queue to store the bars temporarily.
            this.barQueue = new Queue<TradeBar>(barCount);
            
        }
        
        // Add a bar to the list, when it totals X bars return a new tradebar.
        public bool Update(TradeBar bar) {
            //Add this bar to the queue:
            barQueue.Enqueue(bar);
            
            //Use a counter to speed up the counting.
            barCount++;
            
            if (barCount == requestedCount) {
                return true;
            } else {
                return false;
            }
        }
        
        //Using the barQueue generate a new "consolidated bar" then return
        private TradeBar Generate() {
            
            string symbol = "";
            long volume = 0;
            DateTime barOpenTime = new DateTime();
            decimal open = Decimal.Zero, high = Decimal.MinValue, low = Decimal.MaxValue, close = Decimal.Zero;
            
            //Create the new bar:
            while(barCount > 0) {
                TradeBar bar = barQueue.Dequeue();
                if (barOpenTime == new DateTime()) barOpenTime = bar.Time;
                if (symbol == "") symbol = bar.Symbol;
                if (open == Decimal.Zero) open = bar.Open;
                if (high < bar.High) high = bar.High;
                if (low > bar.Low) low = bar.Low;
                close = bar.Close;
                volume = bar.Volume;
                barCount--;
            }
            
            //Reset ready for next bar:
            barQueue.Clear();
            
            //Create the new trade bar.
            return new TradeBar(barOpenTime, symbol, open, high, low, close, volume);
            

        }
        
    }
}
using System;
using System.Collections;
using System.Collections.Generic; 
using System.Collections.Concurrent;
using System.Text;
using System.Linq;
using QuantConnect.Models;

namespace QuantConnect {
    
    /*
    *   SMA Indicator: Online calculator for faster backtesting.
    *
    *   To use this indicator: 
    *   1. Create an instance of it in your algorithm:
    *   SMA sma10 = new SMA(10);
    *   
    *   2. Push in data with AddSample:
    *   decimal sma = sma10.AddSample(data["spy"].Close);
    *
    *   3. If you're sensitive to the precise SMA values you push wait until the indicator is Ready.
    */
    
    public class SimpleMovingAverage 
    {
        //Class Variables:
        private int period, samples;
		private decimal sma, sum, divisor;
		private FixedSizedQueue<decimal> sampleQueue;
		
		// Initialise the Simple Moving Average
        public SimpleMovingAverage(int period) {
            this.period = period;
            this.samples = 0;
            this.sampleQueue = new FixedSizedQueue<decimal>(period);
        }
		
		//Public Result Access: Current value of the SMA.
		public decimal SMA {
			get{ return sma;}
		}
		
		//Public Result Access: Track the number of samples:
		public int Samples {
		    get { return samples; }
		}
		
		//Public Result Access: We've got sufficient data samples to know its the SMA.
		public bool Ready {
		    get { return samples >= period; }
		}
		
		// Online implementation of simple moving average 
        public decimal AddSample(decimal quote)
        {
            samples++;
            sum += quote;
		  
            //Add this sample to the SMA, subtract the previous
            sampleQueue.Enqueue(quote);
            if (sampleQueue.Size == period) {
                //"last" is a dequeued item: minus it from the SMA.
                sum -= sampleQueue.LastDequeued;
            }
            
            //When less than period samples, only divide by the number of samples.
            if (samples < period) {
                divisor = samples;
            } else {
                divisor = period;
            }
            
            sma = sum / divisor;
            
		    return sma;
        }
        
        
        //Fixed length queue that dumps things off when no more space in queue.
        private class FixedSizedQueue<T> : ConcurrentQueue<T> {
            public int Size { get; private set; }
            public T LastDequeued { get; private set; }
            public FixedSizedQueue(int size) { Size = size; }
            public new void Enqueue(T obj) {
                base.Enqueue(obj);
                lock (this) {
                    if (base.Count > Size) {
                        T outObj;
                        base.TryDequeue(out outObj);
                        LastDequeued = outObj;
                    }
                }
            }
        }
        
    }
}
using System;
using System.Collections;
using System.Collections.Generic; 
using System.Text;
using System.Linq;
using QuantConnect.Models;

namespace QuantConnect {
    
    public class ExponentialMovingAverage
    {
        private int _period;
		private decimal _ema;
		private int _samples;
		private decimal _expConstant;
		private bool flag;
        private Queue<decimal> _data = new Queue<decimal>();
		
        //Initialize the Algorithm
        public ExponentialMovingAverage(int period) {
            _period = period;
            _ema = 0;
            flag = false;
            _expConstant = (decimal) (2 / (_period +1));
        }
		
		//Public Result Access: Current value of the EMA.
		public decimal EMA {
			get{ return _ema;}
		}
		
		//Public Result Access: Track the number of samples:
		public int Samples {
		    get { return _samples; }
		}
		
		//Public Result Access: We've got sufficient data samples to know its the EMA.
		public bool Ready {
		    get { return _data.Count >= _period; }
		}
		
		/// Calculate the exponential moving average 
        public decimal AddSample(decimal quote)
        {
		  _data.Enqueue(quote);
		  _samples++;
		  
          if(_data.Count < _period)
		  {
			return _data.Average();
		  }
		  else
		  {
			if(!flag) 
			{
				_ema = _data.Average();
				flag = true;
			} 
			else 
			{
				_ema = (1-_expConstant) * _ema + _expConstant * quote;
			} 
		  }
		  return _ema;
        }
    } 
}
using System;
using System.Collections;
using System.Collections.Generic; 
using System.Text;
using System.Threading.Tasks;
using QuantConnect.Indicator;

namespace QuantConnect 
{
    using QuantConnect.Securities;
    using QuantConnect.Models; 
    

    public class BasicTemplateAlgorithm : QCAlgorithm, IAlgorithm 
    { 


      SimpleMovingAverage sma19500 = new SimpleMovingAverage(19500);
      SimpleMovingAverage sma39000 = new SimpleMovingAverage(39000);
      
//  1. Create new instance of consolidator: 5 minutes / 5 bars joined.
      

        

      //Initialize the data and resolution you require for your strategy:
        public override void Initialize() 
        {            
            
            //Initialize the start, end dates for simulation; cash and data required.
            SetStartDate(2008, 06, 01);
            SetEndDate(2012, 12, 30); 
            SetCash(30000); //Starting Cash in USD.
            AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute); //Minute, Second or Tick
            SetRunMode(RunMode.Series); //Series or Parallel for intraday strategies.
        }

        //Handle TradeBar Events: a TradeBar occurs on every time-interval
        public override void OnTradeBar(Dictionary<string, TradeBar> data) 
        {
            

  
      

      
            sma19500.AddSample(Securities["SPY"].Close);
            sma39000.AddSample(Securities["SPY"].Close);
            if (sma19500.SMA > sma39000.SMA)
            {
              
                Order("SPY", 50); //symbol, quantity
                return;
            } 
            else
            {

                Order("SPY", -50); //symbol, quantity
                return;
            }
           
            
        }
        
        //Handle Tick Events
        public override void OnTick(Dictionary<string, List<Tick>> ticks) 
        {   
            if (Portfolio["SPY"].HoldStock == false) 
            {
                Order("SPY", 5);
            }
        }


    }
}
/*
    	Created July 2013 by Cheng Yan
*/

/**********************************************************
 * USING NAMESPACES
 **********************************************************/
using System;
using System.Collections;
using System.Collections.Generic; 
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using QuantConnect;
using QuantConnect.Models;

namespace QuantConnect.Indicator
{
    /******************************************************** 
    * CLASS DEFINITIONS
    *********************************************************/
	/// <summary>
    /// An indicator shows the average value of secuitry's price  
    /// over a set period 
    /// </summary>
    public class ExponentialMovingAverage : QCAlgorithm
    {
		/******************************************************** 
        * CLASS VARIABLES
        *********************************************************/
        private int _period;
		private decimal _ema;
		private bool flag;
        private Queue <decimal>_data = new Queue <decimal> ();
		
		
		
		/******************************************************** 
        * CLASS PUBLIC VARIABLES
        *********************************************************/
		
		
		
		public decimal EMA
		{
			get{ return _ema;}
		}
		public decimal GetExpConst
		{
			get{ return (decimal) 2/(_period +1);}
		}
		/******************************************************** 
        * CLASS CONSTRUCTOR
        *********************************************************/
		/// <summary>
        /// Initialise the Algorithm
        /// </summary>
        public ExponentialMovingAverage(int period)
       {
           _period = period;
		   _ema = 0;
		   flag = false;
       }
        
	   /******************************************************** 
            * CLASS METHODS
        *********************************************************/
		/// <summary>
		/// Calculate the exponential moving average 
        /// </summary>	
		public void Push(decimal quote)
		{
			_data.Enqueue(quote);
		}
		
		/// <summary>
		/// Calculate the exponential moving average 
        /// </summary>		
        public void GetEMA(decimal quote)
        {
		  Push(quote);
          if(_data.Count < _period)
		  {
			return;
		  }
		  else
		  {
			if(!flag)
			{
				_ema = _data.Average();
				flag = true;
			}
			else
			{
				_ema = (1-GetExpConst) * _ema +GetExpConst * quote;
			}
		  }
        }
    } 
}
/// <summary>
///    Basic Template v0.1 :: Rolling Average
/// </summary>	
using System;
using System.Collections;
using System.Collections.Generic;

namespace QuantConnect {

	/// <summary>
	/// Example Helper Class: Basic Math Routines.
	/// Using the QCS you can create subfolders, classes. 
    /// All the code is compiled into your algorithm.
	/// </summary>	
    public partial class MathAverage {

        public int iSamplePeriod = 10;
        public decimal dCurrentAverage = 0;

        /// <summary>
        /// Example helper class: Add a new sample to a rolling average.
        /// </summary>
        /// <param name="dNewSample">Decimal new sample value</param>
        /// <returns>decimal current rolling average.</returns>
        public static decimal RollingAverage(decimal dNewSample) {

            Random cRand = new Random();
            return dNewSample * ((decimal)cRand.NextDouble());
        
        }

    }
}