Overall Statistics
Total Trades
21
Average Win
2.10%
Average Loss
-1.19%
Compounding Annual Return
7.410%
Drawdown
8.100%
Expectancy
0.382
Net Profit
4.937%
Sharpe Ratio
0.52
Loss Rate
50%
Win Rate
50%
Profit-Loss Ratio
1.76
Alpha
-0.434
Beta
25.976
Annual Standard Deviation
0.163
Annual Variance
0.026
Information Ratio
0.398
Tracking Error
0.162
Treynor Ratio
0.003
Total Fees
$21.00
import numpy as np
from System.Drawing import Color
from decimal import *

class macdExample(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2018, 6, 1)
        self.SetEndDate(2019, 2, 1)
        
        self.SetCash(10000)
        
        self.spy = self.AddEquity("SPY", Resolution.Daily)
        self.macd = self.MACD("SPY", 12,26,9,Resolution.Daily)
        
        # Establish Trade Plot
        IndicatorPlot = Chart("Trade Plot")
        IndicatorPlot.AddSeries(Series("macd", SeriesType.Line,"", Color.Red))
        IndicatorPlot.AddSeries(Series("signal", SeriesType.Line,"", Color.Blue))
        IndicatorPlot.AddSeries(Series("histogram", SeriesType.Bar,"", Color.Black))
        IndicatorPlot.AddSeries(Series("Long", SeriesType.Scatter,"", Color.Green))
        IndicatorPlot.AddSeries(Series("Short", SeriesType.Scatter,"", Color.Red))
        self.AddChart(IndicatorPlot)
        
    def OnData(self,data):
        if not (data.ContainsKey("SPY")): return
        if not self.macd.IsReady: return
    
        # Indicator values
        hist=self.macd.Histogram.Current.Value
        
        # If histogram is positive, then go long SPY
        if hist>=0:
            if not self.Portfolio["SPY"].Quantity > 0:
                self.SetHoldings("SPY",1)
                self.Plot("Trade Plot", "Long", 0)
                
        # If histogram is negative, then go short SPY
        elif hist < 0:
            if not self.Portfolio["SPY"].Quantity < 0:
                self.SetHoldings("SPY",-1)
                self.Plot("Trade Plot", "Short", 0)
    
    def OnEndOfDay(self):
        # Add values to plot
        if not self.macd.IsReady: return

        self.Plot("Trade Plot", "macd", self.macd.Current.Value)
        self.Plot("Trade Plot", "signal", self.macd.Signal.Current.Value)
        self.Plot("Trade Plot", "histogram", self.macd.Histogram.Current.Value)