Overall Statistics
Total Trades
28
Average Win
17.86%
Average Loss
-4.21%
Compounding Annual Return
16.154%
Drawdown
24.900%
Expectancy
3.440
Net Profit
656.280%
Sharpe Ratio
1.011
Probabilistic Sharpe Ratio
39.996%
Loss Rate
15%
Win Rate
85%
Profit-Loss Ratio
4.25
Alpha
0.145
Beta
0.25
Annual Standard Deviation
0.175
Annual Variance
0.031
Information Ratio
0.222
Tracking Error
0.226
Treynor Ratio
0.706
Total Fees
$429.44
Estimated Strategy Capacity
$4900000.00
Lowest Capacity Asset
XLB RGRPZX100F39
## SIMON LesFlex June 2021 ##
## Modified by Vladimir

from QuantConnect.Python import PythonQuandl

### Simon LesFlex June 2021 ###
### Key Short—Term Economic Indicators. The Key Economic Indicators (KEI) database contains monthly and quarterly statistics 
### (and associated statistical methodological information) for the 33 OECD member and for a selection of non—member countries 
### on a wide variety of economic indicators, namely: quarterly national accounts, industrial production, composite leading indicators, 
### business tendency and consumer opinion surveys, retail trade, consumer and producer prices, hourly earnings, employment/unemployment,
### interest rates, monetary aggregates, exchange rates, international trade and balance of payments. Indicators have been prepared by national statistical 
### agencies primarily to meet the requirements of users within their own country. In most instances, the indicators are compiled in accordance with 
### international statistical guidelines and recommendations. However, national practices may depart from these guidelines, and these departures may 
### impact on comparability between countries. There is an on—going process of review and revision of the contents of the database in order to maximise 
### the relevance of the database for short—term economic analysis.
### For more information see: http://stats.oecd.org/OECDStat_Metadata/ShowMetadata.ashx?Dataset=KEI&Lang=en
### Reference Data Set: https://www.quandl.com/data/OECD/KEI_LOLITOAA_OECDE_ST_M-Leading-indicator-amplitude-adjusted-OECD-Europe-Level-ratio-or-index-Monthly
import numpy as np

class QuandlImporterAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.quandlCode = "OECD/KEI_LOLITOAA_OECDE_ST_M"
        ## Optional argument - personal token necessary for restricted dataset
        Quandl.SetAuthCode("MLNarxdsMU92vk-ZJDvg")
        
        self.SetStartDate(2008,1,1)                                 #Set Start Date
        self.SetEndDate(datetime.today() - timedelta(1))            #Set End Date
        self.SetCash(100000)                                         #Set Strategy Cash
        self.SetWarmup(100)
        self.SetBenchmark("SPY")
        self.init = True
        self.kei = self.AddData(QuandlCustomColumns, self.quandlCode, Resolution.Daily, TimeZones.NewYork).Symbol
        self.sma = self.SMA(self.kei, 1)
        self.mom = self.MOMP(self.kei, 2)
        #self.SPY = self.AddEquity('SPY', Resolution.Daily).Symbol
        self.stock = self.AddEquity('QQQ', Resolution.Hour).Symbol
        self.bond = self.AddEquity('TLT', Resolution.Hour).Symbol
        
        self.XLF = self.AddEquity('XLF', Resolution.Hour).Symbol
        self.XLE = self.AddEquity('XLE', Resolution.Hour).Symbol
        self.XLB = self.AddEquity('XLB', Resolution.Hour).Symbol
        self.XLI = self.AddEquity('XLI', Resolution.Hour).Symbol
        self.XLY = self.AddEquity('XLY', Resolution.Hour).Symbol
        self.XLP = self.AddEquity('XLP', Resolution.Hour).Symbol
        self.XLU = self.AddEquity('XLU', Resolution.Hour).Symbol
        self.XLK = self.AddEquity('XLK', Resolution.Hour).Symbol
        self.XLV = self.AddEquity('XLV', Resolution.Hour).Symbol
        self.XLC = self.AddEquity('XLC', Resolution.Hour).Symbol
        
        self.Schedule.On(self.DateRules.WeekStart(self.stock), self.TimeRules.AfterMarketOpen(self.stock, 31), 
            self.Rebalance)
        

    def Rebalance(self):
        if self.IsWarmingUp or not self.mom.IsReady or not self.sma.IsReady: return
        initial_asset = self.stock if self.mom.Current.Value > 0 else self.bond
        
        if self.init:
            self.SetHoldings(initial_asset, 1)
            self.init = False
            

        #keihist = self.History([self.kei], 1400)
        keihist = self.History([self.kei],self.StartDate-timedelta(100),self.StartDate-timedelta(10))
        #keihist = keihist['Value'].unstack(level=0).dropna()
        keihistlowt = np.nanpercentile(keihist, 15)
        keihistmidt = np.nanpercentile(keihist, 50)
        keihisthight = np.nanpercentile(keihist, 90)
        kei = self.sma.Current.Value
        keimom = self.mom.Current.Value
            
        if (keimom < 0 and kei < keihistmidt and  kei > keihistlowt) and not (self.Securities[self.bond].Invested):
            # DECLINE
            self.Liquidate()
            #self.SetHoldings(self.XLP, 1)
            self.SetHoldings(self.bond, 1)
            self.Debug("STAPLES {0} >> {1}".format(self.XLP, self.Time))
        
        elif (keimom > 0 and kei < keihistlowt) and not (self.Securities[self.XLB].Invested):
            # RECOVERY
            self.Liquidate()
            self.SetHoldings(self.XLB, .5)
            self.SetHoldings(self.XLY, .5)
            self.Debug("MATERIALS {0} >> {1}".format(self.XLB, self.Time))
            
        elif (keimom > 0 and kei > keihistlowt and kei < keihistmidt) and not (self.Securities[self.XLE].Invested):
            # EARLY
            self.Liquidate()
            self.SetHoldings(self.XLE, .33)
            self.SetHoldings(self.XLF, .33)
            self.SetHoldings(self.XLI, .33)
            self.Debug("ENERGY {0} >> {1}".format(self.XLE, self.Time))
            
        elif (keimom > 0 and kei > keihistmidt and kei < keihisthight) and not (self.Securities[self.XLU].Invested):
            # REBOUND
            self.Liquidate()
            self.SetHoldings(self.XLK, .5)
            self.SetHoldings(self.XLU, .5)
            self.Debug("UTILITIES {0} >> {1}".format(self.XLU, self.Time))
        
        elif (keimom < 0 and kei < keihisthight and kei > keihistmidt) and not (self.Securities[self.XLK].Invested):
            # LATE
            self.Liquidate()
            self.SetHoldings(self.XLK, .5)
            self.SetHoldings(self.XLV, .5)
            self.Debug("INFO TECH {0} >> {1}".format(self.XLK, self.Time))
        
        elif (keimom < 0 and kei < 100 and not self.Securities[self.bond].Invested):
            self.Liquidate()
            self.SetHoldings(self.bond, 1)
        

        self.Plot("LeadInd", "SMA(LeadInd)", self.sma.Current.Value)
        self.Plot("LeadInd", "THRESHOLD", 100)
        self.Plot("MOMP", "MOMP(LeadInd)", self.mom.Current.Value)
        self.Plot("MOMP", "THRESHOLD", 0)

        
# Quandl often doesn't use close columns so need to tell LEAN which is the "value" column.
class QuandlCustomColumns(PythonQuandl):
    def __init__(self):
        # Define ValueColumnName: cannot be None, Empty or non-existant column name
        self.ValueColumnName = "Value"