Overall Statistics
Total Trades
8
Average Win
2.11%
Average Loss
-0.23%
Compounding Annual Return
1.675%
Drawdown
1.700%
Expectancy
4.093
Net Profit
3.778%
Sharpe Ratio
0.74
Probabilistic Sharpe Ratio
33.137%
Loss Rate
50%
Win Rate
50%
Profit-Loss Ratio
9.19
Alpha
0.015
Beta
0.012
Annual Standard Deviation
0.023
Annual Variance
0.001
Information Ratio
-0.871
Tracking Error
0.131
Treynor Ratio
1.454
Total Fees
$8.00
class EMAStopLoss(QCAlgorithm):
    def Initialize(self):
        
        self.SetStartDate(2017, 1, 7)
        self.SetEndDate(2019, 4, 1)
        self.SetCash(100000)
        self.ticker = self.AddEquity("TSLA", Resolution.Daily).Symbol
       
        #Define our indicators    
        self.slow = ExponentialMovingAverage(200)
        self.fast = ExponentialMovingAverage(50)
        
        self.RegisterIndicator(self.ticker, self.slow, Resolution.Daily, Field.Close)
        self.RegisterIndicator(self.ticker, self.fast, Resolution.Daily, Field.Close)
        
        self.SetWarmUp(200, Resolution.Daily)
        
        #Initialize our tradeLock
        self.tradeLock = False
        #For updating our trailing stop loss
        self.highestPrice = -1
        #Order Ticket to keep track of our stop loss
        self.stopLossTicket = None
        
        
    def OnData(self, data):
        
        #Make sure our algorithm is done warming up before continuing 
        if self.IsWarmingUp:
            return
        
        price = data[self.ticker].Close
        
        #Entry conditions: 1. trade lock not on, 2. long cross over, 3. not invested
        if not self.tradeLock and self.fast.Current.Value > self.slow.Current.Value and not self.Portfolio[self.ticker].Invested:           
            self.MarketOrder(self.ticker, 100)
            self.highestPrice = price
            self.stopLossTicket = self.StopMarketOrder(self.ticker, -100, price * 0.96)
        # If there is a short cross over and tradelock enabled, we now disable it, letting new trades take place
        elif self.tradeLock and self.fast.Current.Value < self.slow.Current.Value:
            self.tradeLock = False
            
        # Update our trailing stop loss as necessary
        if self.stopLossTicket is not None and price > self.highestPrice:
            self.highestPrice = price
            self.stopLossTicket.UpdateStopPrice(price * 0.96)
            
    def OnOrderEvent(self, OrderEvent):
        if self.stopLossTicket is None or OrderEvent.Status != OrderStatus.Filled:
            return
        #if our stop loss has been filled we place a lock on trading
        self.tradeLock = (OrderEvent.OrderId == self.stopLossTicket.OrderId)