Overall Statistics
Total Trades
35
Average Win
0.85%
Average Loss
-0.49%
Compounding Annual Return
15.706%
Drawdown
5.100%
Expectancy
0.257
Net Profit
12.962%
Sharpe Ratio
1.375
Loss Rate
54%
Win Rate
46%
Profit-Loss Ratio
1.72
Alpha
0.009
Beta
0.814
Annual Standard Deviation
0.09
Annual Variance
0.008
Information Ratio
-0.229
Tracking Error
0.075
Treynor Ratio
0.151
Total Fees
$37.15
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Data import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from System.Collections.Generic import List
import decimal as d

### <summary>
### In this algorithm we demonstrate how to perform some technical analysis as
### part of your coarse fundamental universe selection
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="indicators" />
### <meta name="tag" content="universes" />
### <meta name="tag" content="coarse universes" />
class EmaCrossUniverseSelectionAlgorithm(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,1,1)  #Set Start Date
        self.SetEndDate(2017,11,1)    #Set End Date
        self.SetCash(100000)           #Set Strategy Cash

        self.UniverseSettings.Resolution = Resolution.Daily
        self.UniverseSettings.Leverage = 2

        self.coarse_count = 10
        self.averages = { };

        # this add universe method accepts two parameters:
        # - coarse selection function: accepts an IEnumerable<CoarseFundamental> and returns an IEnumerable<Symbol>
        self.AddUniverse(self.CoarseSelectionFunction)


    # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
    def CoarseSelectionFunction(self, coarse):

        # We are going to use a dictionary to refer the object that will keep the moving averages
        for cf in coarse:
            if cf.Symbol not in self.averages:
                self.averages[cf.Symbol] = SymbolData(cf.Symbol)

            # Updates the SymbolData object with current EOD price
            avg = self.averages[cf.Symbol]
            avg.update(cf)

        # Filter the values of the dict: wait for indicator to be ready
        values = filter(lambda x: x.is_ready, self.averages.values())

        # Sorts the values of the dict: we want those with greater difference between the moving averages
        values.sort(key=lambda x: x.vol.Current.Value, reverse=True)

        for x in values[:self.coarse_count]:
            self.Log('symbol: ' + str(x.symbol.Value) + '  mean vol: ' + str(x.vol.Current.Value) + '  mean price: ' + str(x.sma.Current.Value))
        
        # we need to return only the symbol objects
        return [ x.symbol for x in values[:self.coarse_count] ]

    # this event fires whenever we have changes to our universe
    def OnSecuritiesChanged(self, changes):
        # liquidate removed securities
        for security in changes.RemovedSecurities:
            if security.Invested:
                self.Liquidate(security.Symbol)

        # we want 20% allocation in each security in our universe
        for security in changes.AddedSecurities:
            self.SetHoldings(security.Symbol, 0.1)


class SymbolData(object):
    def __init__(self, symbol):
        self.symbol = symbol
        self.vol = SimpleMovingAverage(20)
        self.sma = SimpleMovingAverage(90)
        self.is_ready = False

    def update(self, value):
        self.is_ready = self.sma.Update(value.EndTime, value.Price) and self.vol.Update(value.EndTime, value.DollarVolume)