Overall Statistics
Total Trades
659
Average Win
3.11%
Average Loss
-1.80%
Compounding Annual Return
93.879%
Drawdown
28.600%
Expectancy
0.669
Net Profit
3280.641%
Sharpe Ratio
2.471
Probabilistic Sharpe Ratio
99.597%
Loss Rate
39%
Win Rate
61%
Profit-Loss Ratio
1.73
Alpha
0.824
Beta
-0.122
Annual Standard Deviation
0.329
Annual Variance
0.108
Information Ratio
1.93
Tracking Error
0.379
Treynor Ratio
-6.663
Total Fees
$660.08
### <summary>
### Simple RSI Strategy intended to provide a minimal algorithm example using
### one indicator
### </summary>
from System.Drawing import Color

class RSIAlgorithm(QCAlgorithm):

    # Order ticket for our stop order, Datetime when stop order was last hit
    stopMarketTicket = None
    stopMarketOrderFillTime = datetime.min
    highestSPYPrice = 0


    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.'''
        
        # Set our main strategy parameters
        self.SetStartDate(2015,1, 1)   # Set Start Date
        self.SetEndDate(2020,4,25)       # Set End Date
        self.SetCash(10000)             # Set Strategy Cash
        
        self.Equities = ["AMZN"]
        
        # self.AddEquity("AMZN").Symbol
        # self.Securities["AMZN"].SetLeverage(2.0)
        
        self.HK = dict() # Create dict to hold all our HK Indicators
        
        for Equity in self.Equities:
            # Find more symbols here: http://quantconnect.com/data
            self.AddEquity(Equity, Resolution.Daily)
            self.HK[Equity] = self.HeikinAshi(Equity, Resolution.Daily)
            
            
            # Plotting Suggestion 1: Line chart
            # --------------------------------------
            # Note: This has been commented out as
            #       we are limited to 10 series per
            #       backtest. To test, uncomment the
            #       lines below and then comment out
            #       either suggestion 3 or 4.
            # ---------------------------------------
            #self.PlotIndicator(
            #    Equity + " - Line",
            #    self.HK[Equity].Open,
            #    self.HK[Equity].High,
            #    self.HK[Equity].Low,
            #    self.HK[Equity].Close
            #    )
            
            # Plotting Suggestion 2: Candle Chart
            # ---------------------------------------
            CandChart = Chart(Equity + "- Candle", ChartType.Stacked)
            CandChart.AddSeries(Series('Heikinashi', SeriesType.Candle))
            self.AddChart(CandChart)
            
            # Plotting Suggestion 3: Scatter Chart
            # ---------------------------------------
            ScatPlot = Chart(Equity + "- X", ChartType.Stacked)
            ScatPlot.AddSeries(Series('Open',  SeriesType.Scatter, '$', Color.Black, ScatterMarkerSymbol.Circle))
            ScatPlot.AddSeries(Series('High',  SeriesType.Scatter, '$', Color.Green, ScatterMarkerSymbol.Triangle))
            ScatPlot.AddSeries(Series('Low',   SeriesType.Scatter, '$', Color.Red,   ScatterMarkerSymbol.TriangleDown))
            ScatPlot.AddSeries(Series('Close', SeriesType.Scatter, '$', Color.Black, ScatterMarkerSymbol.Square))
            self.AddChart(ScatPlot)
            
            # Plotting Suggestion 4: Mixed
            # ---------------------------------------
            SAPlot = Chart(Equity + "- Mix", ChartType.Stacked)
            SAPlot.AddSeries(Series('Price', SeriesType.Line, "$", Color.Black))
            SAPlot.AddSeries(Series('Bullish', SeriesType.Scatter, "$", Color.Green, ScatterMarkerSymbol.Circle))
            SAPlot.AddSeries(Series('Bearish', SeriesType.Scatter, "$", Color.Red, ScatterMarkerSymbol.Circle))
            SAPlot.AddSeries(Series('Neutral', SeriesType.Scatter, "$", Color.Black, ScatterMarkerSymbol.Circle))
            SAPlot.AddSeries(Series('High',  SeriesType.Scatter, '$', Color.Black, ScatterMarkerSymbol.Triangle))
            SAPlot.AddSeries(Series('Low',   SeriesType.Scatter, '$', Color.Black,   ScatterMarkerSymbol.TriangleDown))
            self.AddChart(SAPlot)
            
            
    def OnData(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        
        for Equity in self.Equities:
            
            # Aliases
            # -----------------------------------------------------------------
            
            # Heikin
            HK_O = self.HK[Equity].Open.Current.Value
            HK_H = self.HK[Equity].High.Current.Value
            HK_L = self.HK[Equity].Low.Current.Value
            HK_C = self.HK[Equity].Close.Current.Value
            HK_P = self.HK[Equity].Current.Price
            
            # OHLC
            O = data[Equity].Open
            H = data[Equity].High
            L = data[Equity].Low
            C = data[Equity].Close
            P = data[Equity].Price
            
            # -----------------------------------------------------------------
           
            # Work out Heikin Sentiment
            # ---------------------------------------
            if HK_O < HK_C:
                HK_S = "Bull" 
            elif HK_O > HK_C:
                HK_S = "Bear"
            else:
                HK_S = "Neut"
     
            
            # Plotting Option 2: Candle Chart
            # ---------------------------------------
            self.Plot(Equity + "- Candle", 'Heikinashi',  HK_P)
            
            
            # Plotting Option 3: Scatter Chart
            # ---------------------------------------
            self.Plot(Equity + "- X", 'Open', HK_O)
            self.Plot(Equity + "- X", 'High', HK_H)
            self.Plot(Equity + "- X", 'Low',  HK_L)
            self.Plot(Equity + "- X", 'Close', HK_C)
            
            # Plotting Option 4: Mixed
            # ---------------------------------------
            self.Plot(Equity + "- Mix", 'Price', HK_P)
            self.Plot(Equity + "- Mix", 'High', HK_H)
            self.Plot(Equity + "- Mix", 'Low',  HK_L)
            if HK_S == "Bull":
                self.Plot(Equity + "- Mix", 'Bullish', HK_P)
            elif HK_S == "Bear":
                self.Plot(Equity + "- Mix", 'Bearish', HK_P)
            else:
                self.Plot(Equity + "- Mix", 'Neutral', HK_P)
                
            
            # Logging
            # -----------------------------------------------------------------
            
            self.Log("{0} OHLC   >> O: {1} H: {2} L:{3}, C:{4} | Price: {5}".format(Equity, O,H,L,C,P))
            self.Log("{0} Heikin >> O: {1} H: {2} L:{3}, C:{4} | Price: {5} | Sentiment: {6}".format(Equity, HK_O,HK_H,HK_L,HK_C,HK_P,HK_S))
            
            # Entry / Exit Criteria
            # -----------------------------------------------------------------
            if (self.Time - self.stopMarketOrderFillTime).days < 150:
                return
            
            # Check if we are in the market
            if not self.Portfolio.Invested:
                # If not, we check HK sentiment is bullish
                if HK_S == "Bull":
                    
                    self.SetHoldings(Equity, 1)
                    # self.stopMarketTicket = self.StopMarketOrder(Equity, -0.5, 0.97 * self.Securities[Equity].Close)
            else:
                #1. Check if the SPY price is higher that highestSPYPrice.
                # if self.Securities['AMZN'].Close > self.highestSPYPrice:
                        
                #      #2. Save the new high to highestSPYPrice; then update the stop price to 90% of highestSPYPrice 
                #     self.highestSPYPrice = self.Securities['AMZN'].Close
                #     updateFields = UpdateOrderFields()
                #     updateFields.StopPrice = self.Securities['AMZN'].Close * 0.50
                #     self.stopMarketTicket.Update(updateFields)
                if HK_S == "Bear":
                   self.Liquidate(Equity)
    
    def OnOrderEvent(self, orderEvent):
        if orderEvent.Direction == 1:
            self.StopMarketOrder(orderEvent.Symbol, -orderEvent.FillQuantity, 0.95 * self.Securities[orderEvent.Symbol].Close)
        # else:
                # self.StopMarketOrder(orderEvent.Symbol, orderEvent.FillQuantity, 0.97 * self.Securities[orderEvent.Symbol].Close)
        if orderEvent.Status != OrderStatus.Filled:
            return
        if self.stopMarketTicket is not None and self.stopMarketTicket.OrderId == orderEvent.OrderId: 
            self.Debug("NUMBER OF SHARES ->>>" + str(orderEvent.FillQuantity))
            self.stopMarketOrderFillTime = self.Time