Overall Statistics
import clr
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d
import math
import numpy as np
import pandas as pd
import statistics
from datetime import datetime, timedelta

class MovingAverageCrossAlgorithm(QCAlgorithm):

    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.SetStartDate(2017,9,8) #Set Start Date
        self.SetEndDate(2018,3,6)   #Set End Date
        self.SetCash(100000)             #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol

        # create a 21 day exponential moving average
        self.SPY = self.EMA("SPY", 252, Resolution.Daily);
        self.previous = None
    def OnData(self, data):
        #Define a small tolerance on our checks to avoid bouncing
        tolerance = 0.003;
        if self.Securities["SPY"].Price > self.SPY.Current.Value * d.Decimal(1 + tolerance):
            cash = self.Portfolio.Cash
            number_of_shares = (cash/self.Securities["SPY"].Price)
            self.MarketOrder("SPY", number_of_shares)
        if self.Securities["SPY"].Price < self.SPY.Current.Value * d.Decimal(1 - tolerance):
        self.previous = self.Time