Overall Statistics
Total Trades
166
Average Win
3.70%
Average Loss
-1.27%
Compounding Annual Return
18.765%
Drawdown
16.100%
Expectancy
1.633
Net Profit
416.484%
Sharpe Ratio
1.514
Probabilistic Sharpe Ratio
87.579%
Loss Rate
33%
Win Rate
67%
Profit-Loss Ratio
2.93
Alpha
0.168
Beta
0.174
Annual Standard Deviation
0.131
Annual Variance
0.017
Information Ratio
0.121
Tracking Error
0.186
Treynor Ratio
1.141
Total Fees
$166.40
Estimated Strategy Capacity
$9100000.00
Lowest Capacity Asset
IEF SGNKIKYGE9NP
"""
Based on 'In & Out' strategy by Peter Guenther 10-04-2020
expanded/inspired by Tentor Testivis, Dan Whitnable (Quantopian), Vladimir, and Thomas Chang.

https://www.quantopian.com/posts/new-strategy-in-and-out
"""

# Import packages
import numpy as np
import pandas as pd
import scipy as sc


class InOut(QCAlgorithm):

    def Initialize(self):
        self.first_loop = True
        self.is_invested = False

        self.SetStartDate(2012, 1, 1)  # Set Start Date
        self.SetCash(10000)  # Set Strategy Cash
        self.UniverseSettings.Resolution = Resolution.Daily
        res = Resolution.Hour
        
        # stock selection
        self.STKSEL = self.AddEquity('QQQ', res).Symbol
        
        # Feed-in constants
        self.INI_WAIT_DAYS = 15  # out for 3 trading weeks

        self.MRKT = self.AddEquity('SPY', res).Symbol
        
        self.TLT = self.AddEquity('TLT', res).Symbol  # Treasury Bond ETF (20 yrs)
        self.IEF = self.AddEquity('IEF', res).Symbol  # Treasury Bond ETF (7-10 yrs)

        # Market and list of signals based on ETFs
        self.PRDC = self.AddEquity('XLI', res).Symbol  # production (industrials)
        self.METL = self.AddEquity('DBB', res).Symbol  # input prices (metals)
        self.NRES = self.AddEquity('IGE', res).Symbol  # input prices (natural res)
        self.DEBT = self.AddEquity('SHY', res).Symbol  # cost of debt (bond yield)
        self.USDX = self.AddEquity('UUP', res).Symbol  # safe haven (USD) - Dolar Index
        self.GOLD = self.AddEquity('GLD', res).Symbol  # gold
        self.SLVA = self.AddEquity('SLV', res).Symbol  # VS silver
        self.UTIL = self.AddEquity('XLU', res).Symbol  # utilities
        self.SHCU = self.AddEquity('FXF', res).Symbol  # safe haven (CHF)
        self.RICU = self.AddEquity('FXA', res).Symbol  # risk currency (AUD)
        self.INDU = self.PRDC  # vs industrials

        self.FORPAIRS = [self.GOLD, self.SLVA, self.UTIL, self.SHCU, self.RICU]
        self.SIGNALS = [self.PRDC, self.METL, self.NRES, self.DEBT, self.USDX]

        # 'In' and 'out' holdings incl. weights
        # When "In the market" hold the QQQ ETF
        self.HLD_IN = {self.STKSEL: 1.0}
        
        # When "Out of the Market", hold treasury bonds
        self.HLD_OUT = {self.TLT: .5, self.IEF: .5}

        # Initialize variables
        ## 'In'/'out' indicator
        self.be_in = 1
        ## Day count variables
        self.dcount = 0  # count of total days since start
        self.outday = 0  # dcount when self.be_in=0
        ## Flexi wait days
        self.WDadjvar = self.INI_WAIT_DAYS


        self.Schedule.On(
            self.DateRules.EveryDay(),
            self.TimeRules.AfterMarketOpen('SPY', 120),
            self.rebalance_when_out_of_the_market
        )


        self.Schedule.On(
            self.DateRules.WeekEnd(),
            self.TimeRules.AfterMarketOpen('SPY', 120),
            self.rebalance_when_in_the_market
        )

    def rebalance_when_out_of_the_market(self):
        if self.first_loop:
            self.base_portfolio = self.Portfolio.TotalPortfolioValue
            self.base_spy = self.ActiveSecurities[self.MRKT].Price
            self.base_qqq = self.ActiveSecurities[self.STKSEL].Price
            self.first_loop = False
        
        # Returns sample to detect extreme observations
        hist = self.History(
            self.SIGNALS + [self.MRKT] + self.FORPAIRS, 252, Resolution.Daily)['close'].unstack(level=0).dropna()

        # In the first version, it used the pct_chg of the assets in last 3 months
        # hist_shift = hist.rolling(66).apply(lambda x: x[:11].mean())

        # To get rid of single noise, it was updated to consider the mean from 55-66 previous readings
        hist_shift = hist.apply(lambda x: (x.shift(65) + x.shift(64) + x.shift(63) + x.shift(62) + x.shift(
            61) + x.shift(60) + x.shift(59) + x.shift(58) + x.shift(57) + x.shift(56) + x.shift(55)) / 11)

        returns_sample = (hist / hist_shift - 1)
        
        # Reverse code USDX: sort largest changes to bottom
        returns_sample[self.USDX] = returns_sample[self.USDX] * (-1)
        
        # For pairs, take returns differential, reverse coded
        # G_S = Gold vs Silver
        returns_sample['G_S'] = -(returns_sample[self.GOLD] - returns_sample[self.SLVA])
        
        # U_I = Utilities vs Industrial
        returns_sample['U_I'] = -(returns_sample[self.UTIL] - returns_sample[self.INDU])
        
        # C_A = Swiss Franc vs Australian Dollar
        returns_sample['C_A'] = -(returns_sample[self.SHCU] - returns_sample[self.RICU])    
        self.pairlist = ['G_S', 'U_I', 'C_A']

        # Extreme observations; statist. significance = 1%
        pctl_b = np.nanpercentile(returns_sample, 1, axis=0)
        extreme_b = returns_sample.iloc[-1] < pctl_b

        # Determine waitdays empirically via safe haven excess returns, 50% decay
        self.WDadjvar = int(
            max(0.50 * self.WDadjvar,
                self.INI_WAIT_DAYS * max(1,
                                         #returns_sample[self.GOLD].iloc[-1] / returns_sample[self.SLVA].iloc[-1],
                                         #returns_sample[self.UTIL].iloc[-1] / returns_sample[self.INDU].iloc[-1],
                                         #returns_sample[self.SHCU].iloc[-1] / returns_sample[self.RICU].iloc[-1]
                                         np.where((returns_sample[self.GOLD].iloc[-1]>0) & (returns_sample[self.SLVA].iloc[-1]<0) & (returns_sample[self.SLVA].iloc[-2]>0), self.INI_WAIT_DAYS, 1),
                                         np.where((returns_sample[self.UTIL].iloc[-1]>0) & (returns_sample[self.INDU].iloc[-1]<0) & (returns_sample[self.INDU].iloc[-2]>0), self.INI_WAIT_DAYS, 1),
                                         np.where((returns_sample[self.SHCU].iloc[-1]>0) & (returns_sample[self.RICU].iloc[-1]<0) & (returns_sample[self.RICU].iloc[-2]>0), self.INI_WAIT_DAYS, 1)
                                         ))
        )
        adjwaitdays = min(60, self.WDadjvar)

        # self.Debug('{}'.format(self.WDadjvar))

        # Determine whether 'in' or 'out' of the market
        # If any return (3 months return) that is being tracked is bellow the 1% percentile should be off market
        if (extreme_b[self.SIGNALS + self.pairlist]).any():
            self.be_in = False
            self.outday = self.dcount
            
        # if out of the market for adjwaitdays, then go in the market
        if self.dcount >= self.outday + adjwaitdays:
            self.be_in = True
            
        self.dcount += 1

        self.Plot("In Out", "in_market", int(self.be_in))
        self.Plot("In Out", "num_out_signals", extreme_b[self.SIGNALS + self.pairlist].sum())
        self.Plot("Wait Days", "waitdays", adjwaitdays)
        
        self.Plot("My Control", "SPY", self.ActiveSecurities[self.MRKT].Price/self.base_spy)
        self.Plot("My Control", "QQQ", self.ActiveSecurities[self.STKSEL].Price/self.base_qqq)
        self.Plot("My Control", "Portfolio", self.Portfolio.TotalPortfolioValue/self.base_portfolio)
                


    def rebalance_when_in_the_market(self):
        # Swap to 'in' assets if applicable
        if self.be_in and self.is_invested != "in":
            # Close 'Out' holdings
            for asset, weight in self.HLD_OUT.items():
                self.SetHoldings(asset, 0)

            for asset, weight in self.HLD_IN.items():
                self.SetHoldings(asset, weight)
                
            self.is_invested = "in"
        
        # Swap to 'out' assets if applicable
        if not self.be_in and self.is_invested != "out":
            # Close 'In' holdings
            for asset, weight in self.HLD_IN.items():
                self.SetHoldings(asset, 0)

            for asset, weight in self.HLD_OUT.items():
                self.SetHoldings(asset, weight)
            
            self.is_invested = "out"