-
Notifications
You must be signed in to change notification settings - Fork 657
/
esg-factor-momentum-strategy.py
225 lines (170 loc) · 8.6 KB
/
esg-factor-momentum-strategy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#region imports
from AlgorithmImports import *
#endregion
# https://quantpedia.com/strategies/esg-factor-momentum-strategy/
#
# The investment universe consists of stocks in the MSCI World Index. Paper uses MSCI ESG Ratings as the ESG database.
# The ESG Momentum strategy is built by overweighting, relative to the MSCI World Index, companies that increased their
# ESG ratings most during the recent past and underweight those with decreased ESG ratings, where the increases and decreases
# are based on a 12-month ESG momentum. The paper uses the Barra Global Equity Model (GEM3) for portfolio construction with
# constraints that can be found in Appendix 2. Therefore, this strategy is very specific, but we aim to present the idea, not
# the portfolio construction. The strategy is rebalanced monthly.
#
# QC implementation:
# - Universe consists of ~700 stocks with ESG score data.
from numpy import floor
class ESGFactorMomentumStrategy(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2009, 6, 1)
self.SetEndDate(2019, 12, 31)
self.SetCash(100000)
# Decile weighting.
# True - Value weighted
# False - Equally weighted
self.value_weighting = True
self.symbol = self.AddEquity('SPY', Resolution.Daily).Symbol
self.esg_data = self.AddData(ESGData, 'ESG', Resolution.Daily)
self.tickers = []
self.holding_period = 3
self.managed_queue = []
# Monthly ESG decile data.
self.esg = {}
self.period = 14
self.latest_price = {}
self.selection_flag = False
self.UniverseSettings.Resolution = Resolution.Daily
self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
def OnSecuritiesChanged(self, changes):
for security in changes.AddedSecurities:
security.SetFeeModel(CustomFeeModel(self))
security.SetLeverage(10)
def CoarseSelectionFunction(self, coarse):
if not self.selection_flag:
return Universe.Unchanged
self.latest_price.clear()
selected = [x for x in coarse if (x.Symbol.Value).lower() in self.tickers]
for stock in selected:
symbol = stock.Symbol
self.latest_price[symbol] = stock.AdjustedPrice
return [x.Symbol for x in selected]
def FineSelectionFunction(self, fine):
fine = [x for x in fine if x.MarketCap != 0]
momentum = {}
# Momentum calc.
for stock in fine:
symbol = stock.Symbol
ticker = symbol.Value
# ESG data for 14 months is ready.
if ticker in self.esg and self.esg[ticker].IsReady:
esg_data = [x for x in self.esg[ticker]]
esg_decile_2_months_ago = esg_data[1]
esg_decile_14_months_ago = esg_data[13]
if esg_decile_14_months_ago != 0 and esg_decile_2_months_ago != 0:
# Momentum as difference.
# momentum_ = esg_decile_2_months_ago - esg_decile_14_months_ago
# Momentum as ratio.
momentum_ = (esg_decile_2_months_ago / esg_decile_14_months_ago) - 1
# Store momentum/market cap pair.
momentum[stock] = momentum_
# Momentum sorting.
sorted_by_momentum = sorted(momentum.items(), key = lambda x: x[1], reverse = True)
decile = int(len(sorted_by_momentum) / 10)
long = [x[0] for x in sorted_by_momentum[:decile]]
short = [x[0] for x in sorted_by_momentum[-decile:]]
long_symbol_q = []
short_symbol_q = []
# ew
if not self.value_weighting:
if len(long) != 0:
long_w = self.Portfolio.TotalPortfolioValue / self.holding_period / len(long)
long_symbol_q = [(x.Symbol, floor(long_w / self.latest_price[x.Symbol])) for x in long]
if len(short) != 0:
short_w = self.Portfolio.TotalPortfolioValue / self.holding_period / len(short)
short_symbol_q = [(x.Symbol, -floor(short_w / self.latest_price[x.Symbol])) for x in short]
# vw
else:
if len(long) != 0:
total_market_cap_long = sum([x.MarketCap for x in long])
long_w = self.Portfolio.TotalPortfolioValue / self.holding_period
long_symbol_q = [(x.Symbol, floor((long_w * (x.MarketCap / total_market_cap_long))) / self.latest_price[x.Symbol]) for x in long]
short_symbol_q = []
if len(short) != 0:
total_market_cap_short = sum([x.MarketCap for x in short])
short_w = self.Portfolio.TotalPortfolioValue / self.holding_period
short_symbol_q = [(x.Symbol, -floor((short_w * (x.MarketCap / total_market_cap_short))) / self.latest_price[x.Symbol]) for x in short]
self.managed_queue.append(RebalanceQueueItem(long_symbol_q + short_symbol_q))
return [x.Symbol for x in long + short]
def OnData(self, data):
new_data_arrived = False
if 'ESG' in data and data['ESG']:
# Store universe tickers.
if len(self.tickers) == 0:
# TODO '_typename' in storage dictionary?
self.tickers = [x.Key for x in self.esg_data.GetLastData().GetStorageDictionary()][:-1]
# Store history for every ticker.
for ticker in self.tickers:
ticker_u = ticker.upper()
if ticker_u not in self.esg:
self.esg[ticker_u] = RollingWindow[float](self.period)
decile = self.esg_data.GetLastData()[ticker]
self.esg[ticker_u].Add(decile)
# trigger selection after new esg data arrived.
if not self.selection_flag:
new_data_arrived = True
if new_data_arrived:
self.selection_flag = True
return
if not self.selection_flag:
return
self.selection_flag = False
# Trade execution
remove_item = None
# Rebalance portfolio
for item in self.managed_queue:
if item.holding_period == self.holding_period:
for symbol, quantity in item.symbol_q:
if quantity >= 1:
self.MarketOrder(symbol, -quantity)
remove_item = item
elif item.holding_period == 0:
open_symbol_q = []
for symbol, quantity in item.symbol_q:
if quantity >= 1:
if self.Securities[symbol].Price != 0 and self.Securities[symbol].IsTradable:
self.MarketOrder(symbol, quantity)
open_symbol_q.append((symbol, quantity))
# Only opened orders will be closed
item.symbol_q = open_symbol_q
item.holding_period += 1
if remove_item:
self.managed_queue.remove(remove_item)
class RebalanceQueueItem():
def __init__(self, symbol_q):
# symbol/quantity collections
self.symbol_q = symbol_q
self.holding_period = 0
# ESG data.
class ESGData(PythonData):
def __init__(self):
self.tickers = []
def GetSource(self, config, date, isLiveMode):
return SubscriptionDataSource("data.quantpedia.com/backtesting_data/economic/esg_deciles_data.csv", SubscriptionTransportMedium.RemoteFile, FileFormat.Csv)
def Reader(self, config, line, date, isLiveMode):
data = ESGData()
data.Symbol = config.Symbol
if not line[0].isdigit():
self.tickers = [x for x in line.split(';')][1:]
return None
split = line.split(';')
data.Time = datetime.strptime(split[0], "%Y-%m-%d") + timedelta(days=1)
index = 1
for ticker in self.tickers:
data[ticker] = float(split[index])
index += 1
data.Value = float(split[1])
return data
# Custom fee model.
class CustomFeeModel(FeeModel):
def GetOrderFee(self, parameters):
fee = parameters.Security.Price * parameters.Order.AbsoluteQuantity * 0.00005
return OrderFee(CashAmount(fee, "USD"))