Overall Statistics
Total Trades
240
Average Win
0.13%
Average Loss
-0.19%
Compounding Annual Return
35.571%
Drawdown
16.100%
Expectancy
0.069
Net Profit
28.019%
Sharpe Ratio
1.522
Probabilistic Sharpe Ratio
62.848%
Loss Rate
36%
Win Rate
64%
Profit-Loss Ratio
0.68
Alpha
0.295
Beta
0.049
Annual Standard Deviation
0.198
Annual Variance
0.039
Information Ratio
0.429
Tracking Error
0.367
Treynor Ratio
6.204
Total Fees
$0.00
from datetime import datetime,timedelta
import numpy as np

class ReversalAlpha(QCAlgorithm):

    def Initialize(self):
        
        self.SetStartDate(2020, 1, 1)
        self.SetEndDate(2020, 10, 23)
        self.SetCash(100000)  # Set Strategy Cash
     
        tickers = ["EURUSD","USDCAD"]
        # Rolling Windows to hold bar close data keyed by symbol
        self.closingData = {}
        self.SMA45 = {}
        for ticker in tickers:
            symbol = self.AddForex(ticker, Resolution.Hour, Market.Oanda).Symbol
            self.closingData[symbol] = RollingWindow[float](50)
        # Warm up our rolling windows
            self.SMA45[symbol] = self.RC(symbol, 100, 2, Resolution.Hour) 
        self.SetWarmUp(50)
        self.previous=None
        self.current=None
        self.marketTicket=None
        self.stopLimitTicket=None
        self.stopMarketTicket=None
    def OnData(self, data):
        
        for symbol, window in self.closingData.items():
            if data.ContainsKey(symbol) and data[symbol] is not None:
                window.Add(data[symbol].Close)
        
        if self.IsWarmingUp or not all([window.IsReady for window in self.closingData.values()]):
            return
        
        for symbol, sma in self.SMA45.items():
            self.Plot('SMA', symbol.Value, sma.Current.Value)
        
        for symbol, window in self.closingData.items():
            supports, resistances = self.GetPriceLevels(window)
            #self.Log(f"Symbol: {symbol.Value} , Supports: {supports} , Resistances: {resistances}")
            self.Debug(self.SMA45[symbol].Slope.Current.Value)
            
            support=supports[0]
            resistance=resistances[0]
            self.Debug(support)
            if self.previous is not None and self.previous == self.Time.date():
                return
            if not self.Portfolio[symbol].Invested and self.Securities[symbol].Price>support and self.SMA45[symbol].Slope.Current.Value<0:
                self.marketTicket=self.MarketOrder(symbol, -100000)
                self.stopLimitTicket = self.LimitOrder(symbol, 100000, support)
                self.stopMarketTicket = self.StopMarketOrder(symbol, 100000, resistance)
            #if self.SMA45[symbol].Current.Value<0:
             #   self.marketTicket=self.MarketOrder(symbol, -100000)
    
    def GetPriceLevels(self, series, variation = 0.005, h = 3):
        
        supports = []
        resistances = []
        
        maxima = []
        minima = []
        
        # finding maxima and minima by looking for hills/troughs locally
        for i in range(h, series.Size-h):
            if series[i] > series[i-h] and series[i] > series[i+h]:
                maxima.append(series[i])
            elif series[i] < series[i-h] and series[i] < series[i+h]:
                minima.append(series[i])
       
        # identifying maximas which are resistances
        for m in maxima:
            r = m * variation
            # maxima which are near each other
            commonLevel = [x for x in maxima if x > m - r and x < m + r]
            # if 2 or more maxima are clustered near an area, it is a resistance
            if len(commonLevel) > 1:
                # we pick the highest maxima if the cluster as our resistance
                level = max(commonLevel)
                if level not in resistances:
                    resistances.append(level)
        
        # identify minima which are supports
        for l in minima:
            r = l * variation
            # minima which are near each other
            commonLevel = [x for x in minima if x > l - r and x < l + r]
            # if 2 or more minima are clustered near an area, it is a support
            if len(commonLevel) > 1:
                # We pick the lowest minima of the cluster as our support
                level = min(commonLevel)
                if level not in supports:
                    supports.append(level)
            
        
        return supports, resistances
    
    def OnOrderEvent(self, orderEvent):
        self.previous=self.Time.date()
        if self.stopLimitTicket !=None and self.stopLimitTicket.OrderId == orderEvent.OrderId:
            self.stopMarketTicket.Cancel()
            self.marketTicket=None
        if self.stopMarketTicket !=None and self.stopMarketTicket.OrderId == orderEvent.OrderId:
            self.stopLimitTicket.Cancel()
            self.marketTicket=None