Overall Statistics
Total Trades
1339
Average Win
1.28%
Average Loss
-1.73%
Compounding Annual Return
9.238%
Drawdown
41.100%
Expectancy
0.094
Net Profit
579.292%
Sharpe Ratio
0.58
Probabilistic Sharpe Ratio
1.727%
Loss Rate
37%
Win Rate
63%
Profit-Loss Ratio
0.74
Alpha
0
Beta
0
Annual Standard Deviation
0.196
Annual Variance
0.039
Information Ratio
0.58
Tracking Error
0.196
Treynor Ratio
0
Total Fees
$34765.15
Estimated Strategy Capacity
$610000000.00
Lowest Capacity Asset
SPY R735QTJ8XC9X
from System.Drawing import Color


class SMAStrategy(QCAlgorithm):

    def Initialize(self):
        
        self.SetStartDate(2000, 1, 1)  # Set Start Date
        self.SetEndDate(2021, 8, 31)  # Set End Date
        self.SetCash(100000)  # Set Strategy Cash
        
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage) #, AccountType.Margin)
        
        self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
        
        lenght = self.GetParameter("sma_lenght")
        lenght = 5 if lenght is None else int(lenght)  
        
        self.toleranc = self.GetParameter("crossover_tolerance")
        self.tolerance = float(0.0002) if self.toleranc is None else float(self.toleranc)
        
        
        self.sma = self.SMA(self.spy, lenght, Resolution.Daily)
        self.SetWarmUp(timedelta(lenght))

        self.Schedule.On(self.DateRules.On(2021,8, 31), self.TimeRules.At(15,45),
                        self.ExitPositions)
        
        stockPlot = Chart("Trade Plot")
        
        stockPlot.AddSeries(Series("Buy", SeriesType.Scatter, "$", Color.Green, ScatterMarkerSymbol.Triangle))
        stockPlot.AddSeries(Series("Sell", SeriesType.Scatter, "$", Color.Red, ScatterMarkerSymbol.TriangleDown))
        
        self.AddChart(stockPlot)

  
    def OnData(self, data):
        
        if not self.sma.IsReady:
            return
        
        price = self.Securities[self.spy].Price
        
        tolerance = self.tolerance
        
        self.Plot("Trade Plot", "Price", price)
        self.Plot("Trade Plot", "SMA", self.sma.Current.Value)
        
        holdings = self.Portfolio[self.spy].Quantity
        
        if holdings <= 0:
            if self.sma.Current.Value > price * (1 + tolerance):
                self.SetHoldings(self.spy,1)
                self.Plot("Trade Plot", "Buy", price)
        elif self.sma.Current.Value < price * (1 - tolerance):
            self.SetHoldings(self.spy,-1)
            self.Plot("Trade Plot", "Sell", price)
        
        
    def ExitPositions(self):
        self.Liquidate()