66< div class ="section-example-container ">
77< pre class ="python ">
88def Initialize(self):
9+
910 self.SetStartDate(2001, 1, 1)
1011 self.SetEndDate(2018, 8, 1)
1112 self.SetCash(100000)
12- self.tickers = [
13- "IJJ", # iShares S&P MidCap 400 Value Index ETF
14- "IJS", # iShares S&P SmallCap 600 Value ETF
15- "IVE", # iShares S&P 500 Value Index ETF
16- "IVW", # iShares S&P 500 Growth ETF
17- "IJK", # iShares S&P Mid-Cap 400 Growth ETF
18- "IJT", # iShares S&P Small-Cap 600 Growth ETF
19- ]
20- self.symbols = []
21- for ticker in self.tickers:
22- self.symbols.append(self.AddEquity(ticker, Resolution.Daily).Symbol)
23- self.SetWarmUp(timedelta(days=12*20))
24- # save all momentum indicator in the dictionary
25- self.mom = {i:self.MOM(i, 12*20, Resolution.Daily) for i in self.symbols}
13+
14+ tickers = ["IJJ", # iShares S&P Mid-Cap 400 Value Index ETF
15+ "IJK", # iShares S&P Mid-Cap 400 Growth ETF
16+ "IJS", # iShares S&P Small-Cap 600 Value ETF
17+ "IJT", # iShares S&P Small-Cap 600 Growth ETF
18+ "IVE", # iShares S&P 500 Value Index ETF
19+ "IVW"] # iShares S&P 500 Growth ETF
20+
21+ lookback = 12*20
22+
23+ # Save all momentum indicator into the dictionary
24+ self.mom = dict()
25+ for ticker in tickers:
26+ symbol = self.AddEquity(ticker, Resolution.Daily).Symbol
27+ self.mom[symbol] = self.MOM(symbol, lookback)
2628</ pre >
2729</ div >
2830< p >
3335< div class ="section-example-container ">
3436< pre class ="python ">
3537def Rebalance(self):
38+ # Order the MOM dictionary by value
3639 sorted_mom = sorted(self.mom, key = lambda x: self.mom[x].Current.Value)
37- invested = [x.Key for x in self.Portfolio if x.Value.Invested]
38- for i in invested:
39- if i not in [sorted_mom[0], sorted_mom[1]]:
40- self.Liquidate(i)
41- self.SetHoldings(sorted_mom[0], -0.5)
42- self.SetHoldings(sorted_mom[-1], 0.5)
40+
41+ # Liquidate the ETFs that are no longer selected
42+ for symbol in sorted_mom[1:-1]:
43+ if self.Portfolio[symbol].Invested:
44+ self.Liquidate(symbol, 'No longer selected')
45+
46+ self.SetHoldings(sorted_mom[-1], -0.5) # Short the ETF with lowest MOM
47+ self.SetHoldings(sorted_mom[0], 0.5) # Long the ETF with highest MOM
4348</ pre >
44- </ div >
49+ </ div >
0 commit comments