Overall Statistics
from collections import deque
from datetime import datetime, timedelta
from numpy import sum
from decimal import *


# Demonstrates how to create a custom indicator
class CustomIndicatorAlgorithm(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2005,10,1)
        self.SetEndDate(2019,1,1)
        self.spy=self.AddEquity("SPY", Resolution.Daily)

        # Create a custom indicator for average momentum
        self.customIndicator = averageMomentumIndicator('Average Momentum', 252)
        self.RegisterIndicator("SPY", self.customIndicator, Resolution.Daily)
    
        
    def OnData(self, data):
        if not self.Portfolio.Invested:
            self.SetHoldings("SPY", 1)
        
        if self.customIndicator.IsReady:
            self.Log('Average momentum indicator value: ' + str(self.customIndicator.Value))
            self.Plot("customIndicator", "Value", str(self.customIndicator.Value))
            


class averageMomentumIndicator:
    def __init__(self, name, period):
        self.Name = name
        self.Time = datetime.min
        self.Value = 0
        self.IsReady = False
        self.queue = deque(maxlen=period)
        self.mom = deque(maxlen=period)

    def __repr__(self):
        return "{0} -> IsReady: {1}. Time: {2}. Value: {3}".format(self.Name, self.IsReady, self.Time, self.Value)

    # Update method is mandatory
    def Update(self, input):
        self.queue.appendleft(input.Close)
        count = len(self.queue)
        self.Time = input.EndTime
        self.mom.appendleft(input.Close/self.queue[-1]-1)
        self.Value = sum(self.mom)/count
        self.IsReady = count == self.queue.maxlen