Overall Statistics
Total Trades
9
Average Win
2.21%
Average Loss
-0.92%
Compounding Annual Return
27.109%
Drawdown
7.400%
Expectancy
1.276
Net Profit
16.314%
Sharpe Ratio
1.83
Loss Rate
33%
Win Rate
67%
Profit-Loss Ratio
2.41
Alpha
0.216
Beta
-0.138
Annual Standard Deviation
0.11
Annual Variance
0.012
Information Ratio
0.701
Tracking Error
0.133
Treynor Ratio
-1.459
Total Fees
$9.00
import decimal as d
import numpy as np

class MovingAverageCrossAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetCash(100000)
        self.SetStartDate(2017,1,1)
        self.SetEndDate(2017,8,20)

        self.fast = dict()
        self.slow = dict()

        for ticker in ["AAPL", "TSLA", "BA", "FB"]:
		    symbol = self.AddEquity(ticker).Symbol
		    self.fast[symbol] = self.SMA(symbol, 20, Resolution.Daily)
		    self.slow[symbol] = self.SMA(symbol, 50, Resolution.Daily)


    def OnData(self, data):
    	
    	tolerance = 0.00015
    	
        for symbol in data.Keys:
        	
        	# Check whether the indicator that need more datapoint is ready 
            if not self.slow[symbol].IsReady:
                continue
        	
            fast = self.fast[symbol].Current.Value
            slow = self.slow[symbol].Current.Value
            quantity = self.Portfolio[symbol].Quantity
        
            # Go Long If MA20 > MA50
            if quantity <= 0 and fast > slow * d.Decimal(1 + tolerance):
                self.Log("BUY {0} for {1}".format(symbol, self.Securities[symbol].Price))
                self.SetHoldings(symbol, 0.24)

            # Go Short if MA20 < MA50
            if quantity > 0 and fast < slow:
            	self.Log("SELL {0} for {1}".format(symbol, self.Securities[symbol].Price))
            	self.Liquidate(symbol)