Overall Statistics
Total Trades
762
Average Win
0.58%
Average Loss
-1.30%
Compounding Annual Return
6.995%
Drawdown
29.300%
Expectancy
0.238
Net Profit
330.578%
Sharpe Ratio
0.717
Probabilistic Sharpe Ratio
7.776%
Loss Rate
14%
Win Rate
86%
Profit-Loss Ratio
0.45
Alpha
0.053
Beta
0.251
Annual Standard Deviation
0.106
Annual Variance
0.011
Information Ratio
-0.092
Tracking Error
0.173
Treynor Ratio
0.304
Total Fees
$1950.33
Estimated Strategy Capacity
$2700000.00
Lowest Capacity Asset
GSG TKH7EPK7SRC5
# https://quantpedia.com/strategies/asset-class-trend-following/
#
# Use 5 ETFs (SPY - US stocks, EFA - foreign stocks, IEF - bonds, VNQ - REITs, 
# GSG - commodities), equal weight the portfolio. Hold asset class ETF only when 
# it is over its 10 month Simple Moving Average, otherwise stay in cash.
#
# QC implementation:
#   - SMA with period of  days is used.

class AssetClassTrendFollowing(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2000, 1, 1)
        self.SetCash(100000)
        
        self.data = {}
        period = 10 * 21
        self.SetWarmUp(period)
        
        self.symbols = ["SPY", "EFA", "IEF", "VNQ", "GSG"]
        self.rebalance_flag = False
        
        self.tracked_symbol = None
        for symbol in self.symbols:
            self.AddEquity(symbol, Resolution.Minute)
            self.data[symbol] = self.SMA(symbol, period, Resolution.Daily)
        
        self.data["SPY"].Updated += self.OnSmaUpdated
        self.recent_month = -1
    
    def OnSmaUpdated(self, sender, updated):
        # set rebalance flag
        if self.recent_month != self.Time.month:
            self.recent_month = self.Time.month
            self.rebalance_flag = True
            
    def OnData(self, data):
        # rebalance once a month
        if self.rebalance_flag:
            self.rebalance_flag = False
            
            long = []
            for symbol in self.symbols:
                if symbol in data and data[symbol]:
                    if self.data[symbol].IsReady:
                        if data[symbol].Value > self.data[symbol].Current.Value:
                            long.append(symbol)
            
            # Trade execution.
            invested = [x.Key.Value for x in self.Portfolio if x.Value.Invested]
            for symbol in invested:
                if symbol not in long:
                    self.Liquidate(symbol)
        
            for symbol in long:
                hist = self.History(self.Symbol(symbol), 2, Resolution.Daily)
                self.SetHoldings(symbol, 1 / len(long))