Overall Statistics
import numpy as np
from QuantConnect.Indicators import *
### <summary>
### Basic template algorithm simply initializes the date range and cash. This is a skeleton
### framework you can use for designing an algorithm.
### </summary>
class BasicTemplateAlgorithm(QCAlgorithm):
    '''Basic template algorithm simply initializes the date range and cash'''
    
    def __init__(self):
        self.previous = None
        self.sma_3 = None
        self.sma_45 = None
    
    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(2013,1,1)  #Set Start Date
        self.SetEndDate(2013,1,15)    #Set End Date
        self.SetCash(100000)           #Set Strategy Cash

        self.AddUniverse(self.CoarseSelectionFunction)
        self.UniverseSettings.Resolution = Resolution.Daily
        #self.Debug(str(len(fine_select)))
        

    def CoarseSelectionFunction(self, coarse):
        #self.Debug(str(LowerBound)+" "+str(UpperBound))
        #Condition1 = coarse.filter(lambda x:x.price>3 and x.price<20)
        base_filter = [x for x in coarse if (x.Price>3 and x.Price<20 and x.HasFundamentalData)]
        
        sortedByDollarVolume = sorted(base_filter, \
        key=lambda x: x.DollarVolume, reverse=True)
        
        Total = len(sortedByDollarVolume)
        LowerBound = int(Total*0.06)
        UpperBound = int(Total*0.4)
        select = []
        for x in range(UpperBound):
            if x>=LowerBound:
                select.append(sortedByDollarVolume[x]) 
        return [ x.Symbol for x in select ]

    def OnData(self, data):
        #for x in range(len(self.UniverseManager.Values.items())):
        #    self.Debug(self.UniverseManager.Values.items()[x].Members)
        #for y in range(min(10,len(UniverseManager[1].Members.items()))):
        #    self.Debug(list(self.UniverseManager[1].Members)[y].Symbol)
        #self.Debug(str(self.UniverseManager.Values[1].Members.Keys))
        
        MaxCandidates = 100
        
        for x in self.UniverseManager.Values[1].Members.Keys:
            self.Debug(str(x))
            self.sma_3 = self.SMA(x, 3, Resolution.Daily)
            self.sma_45 = self.SMA(x, 45, Resolution.Daily)
            if not self.sma_3.IsReady:
                return
            self.Debug(str(self.sma_3.Current.Value))
            fine_select[x.Symbol] = (self.sma_3.Current.Value - self.sma_45.Current.Value) / self.sma_45.Current.Value
            fine_select = sorted(fine_select, key=fine_select.__getitem__)
            fine_select = fine_select[:MaxCandidates]
        x=1
        for key in fine_select:
        #for key in fine_select:
            #self.Debug(str(key))
            if x%30==0 and not self.Portfolio[key].Invested:
                self.MarketOrder(key,1)
            x=x+1